]> git.lizzy.rs Git - rust.git/blobdiff - src/items.rs
fix: don't force a newline after an empty where clause
[rust.git] / src / items.rs
index 4ae3f383e7413bc2f6b8a4f8335e0e63b248ff2b..a11a02be2aeadff91c681691bb0df8528de1db7b 100644 (file)
@@ -1,13 +1,12 @@
 // Formatting top-level items - functions, structs, enums, traits, impls.
 
 use std::borrow::Cow;
-use std::cmp::{min, Ordering};
+use std::cmp::{max, min, Ordering};
 
 use regex::Regex;
-use rustc_target::spec::abi;
-use syntax::source_map::{self, BytePos, Span};
-use syntax::visit;
-use syntax::{ast, ptr, symbol};
+use rustc_ast::visit;
+use rustc_ast::{ast, ptr};
+use rustc_span::{symbol, BytePos, Span, DUMMY_SP};
 
 use crate::attr::filter_inline_attrs;
 use crate::comment::{
@@ -18,8 +17,7 @@
 use crate::config::lists::*;
 use crate::config::{BraceStyle, Config, IndentStyle, Version};
 use crate::expr::{
-    format_expr, is_empty_block, is_simple_block_stmt, rewrite_assign_rhs, rewrite_assign_rhs_with,
-    ExprType, RhsTactics,
+    is_empty_block, is_simple_block_stmt, rewrite_assign_rhs, rewrite_assign_rhs_with, RhsTactics,
 };
 use crate::lists::{definitive_tactic, itemize_list, write_list, ListFormatting, Separator};
 use crate::macros::{rewrite_macro, MacroPosition};
 use crate::shape::{Indent, Shape};
 use crate::source_map::{LineRangeUtils, SpanUtils};
 use crate::spanned::Spanned;
+use crate::stmt::Stmt;
 use crate::utils::*;
 use crate::vertical::rewrite_with_alignment;
 use crate::visitor::FmtVisitor;
 
-const DEFAULT_VISIBILITY: ast::Visibility = source_map::Spanned {
-    node: ast::VisibilityKind::Inherited,
-    span: source_map::DUMMY_SP,
+const DEFAULT_VISIBILITY: ast::Visibility = ast::Visibility {
+    kind: ast::VisibilityKind::Inherited,
+    span: DUMMY_SP,
+    tokens: None,
 };
 
 fn type_annotation_separator(config: &Config) -> &str {
@@ -126,7 +126,7 @@ fn rewrite(&self, context: &RewriteContext<'_>, shape: Shape) -> Option<String>
 // FIXME format modules in this style
 #[allow(dead_code)]
 struct Item<'a> {
-    keyword: &'static str,
+    unsafety: ast::Unsafe,
     abi: Cow<'static, str>,
     vis: Option<&'a ast::Visibility>,
     body: Vec<BodyElement<'a>>,
@@ -136,8 +136,12 @@ struct Item<'a> {
 impl<'a> Item<'a> {
     fn from_foreign_mod(fm: &'a ast::ForeignMod, span: Span, config: &Config) -> Item<'a> {
         Item {
-            keyword: "",
-            abi: format_abi(fm.abi, config.force_explicit_abi(), true),
+            unsafety: fm.unsafety,
+            abi: format_extern(
+                ast::Extern::from_abi(fm.abi),
+                config.force_explicit_abi(),
+                true,
+            ),
             vis: None,
             body: fm
                 .items
@@ -161,11 +165,11 @@ enum BodyElement<'a> {
 pub(crate) struct FnSig<'a> {
     decl: &'a ast::FnDecl,
     generics: &'a ast::Generics,
-    abi: abi::Abi,
-    is_async: Cow<'a, ast::IsAsync>,
-    constness: ast::Constness,
+    ext: ast::Extern,
+    is_async: Cow<'a, ast::Async>,
+    constness: ast::Const,
     defaultness: ast::Defaultness,
-    unsafety: ast::Unsafety,
+    unsafety: ast::Unsafe,
     visibility: ast::Visibility,
 }
 
@@ -178,25 +182,25 @@ pub(crate) fn new(
         FnSig {
             decl,
             generics,
-            abi: abi::Abi::Rust,
-            is_async: Cow::Owned(ast::IsAsync::NotAsync),
-            constness: ast::Constness::NotConst,
+            ext: ast::Extern::None,
+            is_async: Cow::Owned(ast::Async::No),
+            constness: ast::Const::No,
             defaultness: ast::Defaultness::Final,
-            unsafety: ast::Unsafety::Normal,
+            unsafety: ast::Unsafe::No,
             visibility: vis,
         }
     }
 
     pub(crate) fn from_method_sig(
-        method_sig: &'a ast::MethodSig,
+        method_sig: &'a ast::FnSig,
         generics: &'a ast::Generics,
     ) -> FnSig<'a> {
         FnSig {
             unsafety: method_sig.header.unsafety,
-            is_async: Cow::Borrowed(&method_sig.header.asyncness.node),
-            constness: method_sig.header.constness.node,
+            is_async: Cow::Borrowed(&method_sig.header.asyncness),
+            constness: method_sig.header.constness,
             defaultness: ast::Defaultness::Final,
-            abi: method_sig.header.abi,
+            ext: method_sig.header.ext,
             decl: &*method_sig.decl,
             generics,
             visibility: DEFAULT_VISIBILITY,
@@ -210,24 +214,24 @@ pub(crate) fn from_fn_kind(
         defaultness: ast::Defaultness,
     ) -> FnSig<'a> {
         match *fn_kind {
-            visit::FnKind::ItemFn(_, fn_header, visibility, _) => FnSig {
-                decl,
-                generics,
-                abi: fn_header.abi,
-                constness: fn_header.constness.node,
-                is_async: Cow::Borrowed(&fn_header.asyncness.node),
-                defaultness,
-                unsafety: fn_header.unsafety,
-                visibility: visibility.clone(),
-            },
-            visit::FnKind::Method(_, method_sig, vis, _) => {
-                let mut fn_sig = FnSig::from_method_sig(method_sig, generics);
-                fn_sig.defaultness = defaultness;
-                if let Some(vis) = vis {
+            visit::FnKind::Fn(fn_ctxt, _, fn_sig, vis, _) => match fn_ctxt {
+                visit::FnCtxt::Assoc(..) => {
+                    let mut fn_sig = FnSig::from_method_sig(fn_sig, generics);
+                    fn_sig.defaultness = defaultness;
                     fn_sig.visibility = vis.clone();
+                    fn_sig
                 }
-                fn_sig
-            }
+                _ => FnSig {
+                    decl,
+                    generics,
+                    ext: fn_sig.header.ext,
+                    constness: fn_sig.header.constness,
+                    is_async: Cow::Borrowed(&fn_sig.header.asyncness),
+                    defaultness,
+                    unsafety: fn_sig.header.unsafety,
+                    visibility: vis.clone(),
+                },
+            },
             _ => unreachable!(),
         }
     }
@@ -240,8 +244,8 @@ fn to_str(&self, context: &RewriteContext<'_>) -> String {
         result.push_str(format_constness(self.constness));
         result.push_str(format_async(&self.is_async));
         result.push_str(format_unsafety(self.unsafety));
-        result.push_str(&format_abi(
-            self.abi,
+        result.push_str(&format_extern(
+            self.ext,
             context.config.force_explicit_abi(),
             false,
         ));
@@ -251,6 +255,7 @@ fn to_str(&self, context: &RewriteContext<'_>) -> String {
 
 impl<'a> FmtVisitor<'a> {
     fn format_item(&mut self, item: &Item<'_>) {
+        self.buffer.push_str(format_unsafety(item.unsafety));
         self.buffer.push_str(&item.abi);
 
         let snippet = self.snippet(item.span);
@@ -263,19 +268,16 @@ fn format_item(&mut self, item: &Item<'_>) {
             self.last_pos = item.span.lo() + BytePos(brace_pos as u32 + 1);
             self.block_indent = self.block_indent.block_indent(self.config);
 
-            if item.body.is_empty() {
-                self.format_missing_no_indent(item.span.hi() - BytePos(1));
-                self.block_indent = self.block_indent.block_unindent(self.config);
-                let indent_str = self.block_indent.to_string(self.config);
-                self.push_str(&indent_str);
-            } else {
+            if !item.body.is_empty() {
                 for item in &item.body {
                     self.format_body_element(item);
                 }
-
-                self.block_indent = self.block_indent.block_unindent(self.config);
-                self.format_missing_with_indent(item.span.hi() - BytePos(1));
             }
+
+            self.format_missing_no_indent(item.span.hi() - BytePos(1));
+            self.block_indent = self.block_indent.block_unindent(self.config);
+            let indent_str = self.block_indent.to_string(self.config);
+            self.push_str(&indent_str);
         }
 
         self.push_str("}");
@@ -295,58 +297,45 @@ pub(crate) fn format_foreign_mod(&mut self, fm: &ast::ForeignMod, span: Span) {
 
     fn format_foreign_item(&mut self, item: &ast::ForeignItem) {
         let rewrite = item.rewrite(&self.get_context(), self.shape());
-        self.push_rewrite(item.span(), rewrite);
-        self.last_pos = item.span.hi();
+        let hi = item.span.hi();
+        let span = if item.attrs.is_empty() {
+            item.span
+        } else {
+            mk_sp(item.attrs[0].span.lo(), hi)
+        };
+        self.push_rewrite(span, rewrite);
+        self.last_pos = hi;
     }
 
-    pub(crate) fn rewrite_fn(
+    pub(crate) fn rewrite_fn_before_block(
         &mut self,
         indent: Indent,
-        ident: ast::Ident,
+        ident: symbol::Ident,
         fn_sig: &FnSig<'_>,
         span: Span,
-        block: &ast::Block,
-        inner_attrs: Option<&[ast::Attribute]>,
-    ) -> Option<String> {
+    ) -> Option<(String, FnBraceStyle)> {
         let context = self.get_context();
 
-        let mut newline_brace = newline_for_brace(self.config, &fn_sig.generics.where_clause);
-
-        let (mut result, force_newline_brace) =
-            rewrite_fn_base(&context, indent, ident, fn_sig, span, newline_brace, true)?;
+        let mut fn_brace_style = newline_for_brace(self.config, &fn_sig.generics.where_clause);
+        let (result, force_newline_brace) =
+            rewrite_fn_base(&context, indent, ident, fn_sig, span, fn_brace_style)?;
 
         // 2 = ` {`
         if self.config.brace_style() == BraceStyle::AlwaysNextLine
             || force_newline_brace
             || last_line_width(&result) + 2 > self.shape().width
         {
-            newline_brace = true;
-        } else if !result.contains('\n') {
-            newline_brace = false;
+            fn_brace_style = FnBraceStyle::NextLine
         }
 
-        if let rw @ Some(..) = self.single_line_fn(&result, block, inner_attrs) {
-            rw
-        } else {
-            // Prepare for the function body by possibly adding a newline and
-            // indent.
-            // FIXME we'll miss anything between the end of the signature and the
-            // start of the body, but we need more spans from the compiler to solve
-            // this.
-            if newline_brace {
-                result.push_str(&indent.to_string_with_newline(self.config));
-            } else {
-                result.push(' ');
-            }
-            Some(result)
-        }
+        Some((result, fn_brace_style))
     }
 
     pub(crate) fn rewrite_required_fn(
         &mut self,
         indent: Indent,
-        ident: ast::Ident,
-        sig: &ast::MethodSig,
+        ident: symbol::Ident,
+        sig: &ast::FnSig,
         generics: &ast::Generics,
         span: Span,
     ) -> Option<String> {
@@ -360,8 +349,7 @@ pub(crate) fn rewrite_required_fn(
             ident,
             &FnSig::from_method_sig(sig, generics),
             span,
-            false,
-            false,
+            FnBraceStyle::None,
         )?;
 
         // Re-attach semicolon
@@ -370,7 +358,7 @@ pub(crate) fn rewrite_required_fn(
         Some(result)
     }
 
-    fn single_line_fn(
+    pub(crate) fn single_line_fn(
         &self,
         fn_str: &str,
         block: &ast::Block,
@@ -380,34 +368,22 @@ fn single_line_fn(
             return None;
         }
 
-        let source_map = self.get_context().source_map;
+        let context = self.get_context();
 
         if self.config.empty_item_single_line()
-            && is_empty_block(block, None, source_map)
+            && is_empty_block(&context, block, None)
             && self.block_indent.width() + fn_str.len() + 3 <= self.config.max_width()
             && !last_line_contains_single_line_comment(fn_str)
         {
             return Some(format!("{} {{}}", fn_str));
         }
 
-        if !self.config.fn_single_line() || !is_simple_block_stmt(block, None, source_map) {
+        if !self.config.fn_single_line() || !is_simple_block_stmt(&context, block, None) {
             return None;
         }
 
-        let stmt = block.stmts.first()?;
-        let res = match stmt_expr(stmt) {
-            Some(e) => {
-                let suffix = if semicolon_for_expr(&self.get_context(), e) {
-                    ";"
-                } else {
-                    ""
-                };
-
-                format_expr(e, ExprType::Statement, &self.get_context(), self.shape())
-                    .map(|s| s + suffix)?
-            }
-            None => stmt.rewrite(&self.get_context(), self.shape())?,
-        };
+        let res = Stmt::from_ast_node(block.stmts.first()?, true)
+            .rewrite(&self.get_context(), self.shape())?;
 
         let width = self.block_indent.width() + fn_str.len() + res.len() + 5;
         if !res.contains('\n') && width <= self.config.max_width() {
@@ -434,7 +410,7 @@ pub(crate) fn visit_struct(&mut self, struct_parts: &StructParts<'_>) {
 
     pub(crate) fn visit_enum(
         &mut self,
-        ident: ast::Ident,
+        ident: symbol::Ident,
         vis: &ast::Visibility,
         enum_def: &ast::EnumDef,
         generics: &ast::Generics,
@@ -505,8 +481,8 @@ fn format_variant_list(
         let discr_ident_lens: Vec<usize> = enum_def
             .variants
             .iter()
-            .filter(|var| var.node.disr_expr.is_some())
-            .map(|var| rewrite_ident(&self.get_context(), var.node.ident).len())
+            .filter(|var| var.disr_expr.is_some())
+            .map(|var| rewrite_ident(&self.get_context(), var.ident).len())
             .collect();
         // cut the list at the point of longest discrim shorter than the threshold
         // All of the discrims under the threshold will get padded, and all above - left as is.
@@ -523,8 +499,8 @@ fn format_variant_list(
                 "}",
                 ",",
                 |f| {
-                    if !f.node.attrs.is_empty() {
-                        f.node.attrs[0].span.lo()
+                    if !f.attrs.is_empty() {
+                        f.attrs[0].span.lo()
                     } else {
                         f.span.lo()
                     }
@@ -565,8 +541,8 @@ fn format_variant(
         one_line_width: usize,
         pad_discrim_ident_to: usize,
     ) -> Option<String> {
-        if contains_skip(&field.node.attrs) {
-            let lo = field.node.attrs[0].span.lo();
+        if contains_skip(&field.attrs) {
+            let lo = field.attrs[0].span.lo();
             let span = mk_sp(lo, field.span.hi());
             return Some(self.snippet(span).to_owned());
         }
@@ -574,45 +550,40 @@ fn format_variant(
         let context = self.get_context();
         // 1 = ','
         let shape = self.shape().sub_width(1)?;
-        let attrs_str = field.node.attrs.rewrite(&context, shape)?;
+        let attrs_str = field.attrs.rewrite(&context, shape)?;
         let lo = field
-            .node
             .attrs
             .last()
             .map_or(field.span.lo(), |attr| attr.span.hi());
         let span = mk_sp(lo, field.span.lo());
 
-        let variant_body = match field.node.data {
+        let variant_body = match field.data {
             ast::VariantData::Tuple(..) | ast::VariantData::Struct(..) => format_struct(
                 &context,
                 &StructParts::from_variant(field),
                 self.block_indent,
                 Some(one_line_width),
             )?,
-            ast::VariantData::Unit(..) => {
-                if let Some(ref expr) = field.node.disr_expr {
-                    let lhs = format!(
-                        "{:1$} =",
-                        rewrite_ident(&context, field.node.ident),
-                        pad_discrim_ident_to
-                    );
-                    rewrite_assign_rhs_with(
-                        &context,
-                        lhs,
-                        &*expr.value,
-                        shape,
-                        RhsTactics::AllowOverflow,
-                    )?
-                } else {
-                    rewrite_ident(&context, field.node.ident).to_owned()
-                }
-            }
+            ast::VariantData::Unit(..) => rewrite_ident(&context, field.ident).to_owned(),
+        };
+
+        let variant_body = if let Some(ref expr) = field.disr_expr {
+            let lhs = format!("{:1$} =", variant_body, pad_discrim_ident_to);
+            rewrite_assign_rhs_with(
+                &context,
+                lhs,
+                &*expr.value,
+                shape,
+                RhsTactics::AllowOverflow,
+            )?
+        } else {
+            variant_body
         };
 
         combine_strs_with_missing_comments(&context, &attrs_str, &variant_body, span, shape, false)
     }
 
-    fn visit_impl_items(&mut self, items: &[ast::ImplItem]) {
+    fn visit_impl_items(&mut self, items: &[ptr::P<ast::AssocItem>]) {
         if self.get_context().config.reorder_impl_items() {
             // Create visitor for each items, then reorder them.
             let mut buffer = vec![];
@@ -621,31 +592,69 @@ fn visit_impl_items(&mut self, items: &[ast::ImplItem]) {
                 buffer.push((self.buffer.clone(), item.clone()));
                 self.buffer.clear();
             }
-            // type -> existential -> const -> macro -> method
-            use crate::ast::ImplItemKind::*;
-            fn need_empty_line(a: &ast::ImplItemKind, b: &ast::ImplItemKind) -> bool {
+
+            fn is_type(ty: &Option<rustc_ast::ptr::P<ast::Ty>>) -> bool {
+                if let Some(lty) = ty {
+                    if let ast::TyKind::ImplTrait(..) = lty.kind {
+                        return false;
+                    }
+                }
+                true
+            }
+
+            fn is_opaque(ty: &Option<rustc_ast::ptr::P<ast::Ty>>) -> bool {
+                !is_type(ty)
+            }
+
+            fn both_type(
+                a: &Option<rustc_ast::ptr::P<ast::Ty>>,
+                b: &Option<rustc_ast::ptr::P<ast::Ty>>,
+            ) -> bool {
+                is_type(a) && is_type(b)
+            }
+
+            fn both_opaque(
+                a: &Option<rustc_ast::ptr::P<ast::Ty>>,
+                b: &Option<rustc_ast::ptr::P<ast::Ty>>,
+            ) -> bool {
+                is_opaque(a) && is_opaque(b)
+            }
+
+            // In rustc-ap-v638 the `OpaqueTy` AssocItemKind variant was removed but
+            // we still need to differentiate to maintain sorting order.
+
+            // type -> opaque -> const -> macro -> method
+            use crate::ast::AssocItemKind::*;
+            fn need_empty_line(a: &ast::AssocItemKind, b: &ast::AssocItemKind) -> bool {
                 match (a, b) {
-                    (Type(..), Type(..))
-                    | (Const(..), Const(..))
-                    | (Existential(..), Existential(..)) => false,
+                    (TyAlias(_, _, _, ref lty), TyAlias(_, _, _, ref rty))
+                        if both_type(lty, rty) || both_opaque(lty, rty) =>
+                    {
+                        false
+                    }
+                    (Const(..), Const(..)) => false,
                     _ => true,
                 }
             }
 
-            buffer.sort_by(|(_, a), (_, b)| match (&a.node, &b.node) {
-                (Type(..), Type(..))
-                | (Const(..), Const(..))
-                | (Macro(..), Macro(..))
-                | (Existential(..), Existential(..)) => a.ident.as_str().cmp(&b.ident.as_str()),
-                (Method(..), Method(..)) => a.span.lo().cmp(&b.span.lo()),
-                (Type(..), _) => Ordering::Less,
-                (_, Type(..)) => Ordering::Greater,
-                (Existential(..), _) => Ordering::Less,
-                (_, Existential(..)) => Ordering::Greater,
+            buffer.sort_by(|(_, a), (_, b)| match (&a.kind, &b.kind) {
+                (TyAlias(_, _, _, ref lty), TyAlias(_, _, _, ref rty))
+                    if both_type(lty, rty) || both_opaque(lty, rty) =>
+                {
+                    a.ident.as_str().cmp(&b.ident.as_str())
+                }
+                (Const(..), Const(..)) | (MacCall(..), MacCall(..)) => {
+                    a.ident.as_str().cmp(&b.ident.as_str())
+                }
+                (Fn(..), Fn(..)) => a.span.lo().cmp(&b.span.lo()),
+                (TyAlias(_, _, _, ref ty), _) if is_type(ty) => Ordering::Less,
+                (_, TyAlias(_, _, _, ref ty)) if is_type(ty) => Ordering::Greater,
+                (TyAlias(..), _) => Ordering::Less,
+                (_, TyAlias(..)) => Ordering::Greater,
                 (Const(..), _) => Ordering::Less,
                 (_, Const(..)) => Ordering::Greater,
-                (Macro(..), _) => Ordering::Less,
-                (_, Macro(..)) => Ordering::Greater,
+                (MacCall(..), _) => Ordering::Less,
+                (_, MacCall(..)) => Ordering::Greater,
             });
             let mut prev_kind = None;
             for (buf, item) in buffer {
@@ -653,14 +662,14 @@ fn need_empty_line(a: &ast::ImplItemKind, b: &ast::ImplItemKind) -> bool {
                 // different impl items.
                 if prev_kind
                     .as_ref()
-                    .map_or(false, |prev_kind| need_empty_line(prev_kind, &item.node))
+                    .map_or(false, |prev_kind| need_empty_line(prev_kind, &item.kind))
                 {
                     self.push_str("\n");
                 }
                 let indent_str = self.block_indent.to_string_with_newline(self.config);
                 self.push_str(&indent_str);
                 self.push_str(buf.trim());
-                prev_kind = Some(item.node.clone());
+                prev_kind = Some(item.kind.clone());
             }
         } else {
             for item in items {
@@ -675,7 +684,13 @@ pub(crate) fn format_impl(
     item: &ast::Item,
     offset: Indent,
 ) -> Option<String> {
-    if let ast::ItemKind::Impl(_, _, _, ref generics, _, ref self_ty, ref items) = item.node {
+    if let ast::ItemKind::Impl {
+        ref generics,
+        ref self_ty,
+        ref items,
+        ..
+    } = item.kind
+    {
         let mut result = String::with_capacity(128);
         let ref_and_type = format_impl_ref_and_type(context, item, offset)?;
         let sep = offset.to_string_with_newline(context.config);
@@ -700,8 +715,8 @@ pub(crate) fn format_impl(
             option.allow_single_line();
         }
 
-        let misssing_span = mk_sp(self_ty.span.hi(), item.span.hi());
-        let where_span_end = context.snippet_provider.opt_span_before(misssing_span, "{");
+        let missing_span = mk_sp(self_ty.span.hi(), item.span.hi());
+        let where_span_end = context.snippet_provider.opt_span_before(missing_span, "{");
         let where_clause_str = rewrite_where_clause(
             context,
             &generics.where_clause,
@@ -732,7 +747,7 @@ pub(crate) fn format_impl(
             }
         }
 
-        if is_impl_single_line(context, items, &result, &where_clause_str, item)? {
+        if is_impl_single_line(context, items.as_slice(), &result, &where_clause_str, item)? {
             result.push_str(&where_clause_str);
             if where_clause_str.contains('\n') || last_line_contains_single_line_comment(&result) {
                 // if the where_clause contains extra comments AND
@@ -765,15 +780,16 @@ pub(crate) fn format_impl(
         }
 
         result.push('{');
-
-        let snippet = context.snippet(item.span);
+        // this is an impl body snippet(impl SampleImpl { /* here */ })
+        let lo = max(self_ty.span.hi(), generics.where_clause.span.hi());
+        let snippet = context.snippet(mk_sp(lo, item.span.hi()));
         let open_pos = snippet.find_uncommented("{")? + 1;
 
         if !items.is_empty() || contains_comment(&snippet[open_pos..]) {
             let mut visitor = FmtVisitor::from_context(context);
             let item_indent = offset.block_only().block_indent(context.config);
             visitor.block_indent = item_indent;
-            visitor.last_pos = item.span.lo() + BytePos(open_pos as u32);
+            visitor.last_pos = lo + BytePos(open_pos as u32);
 
             visitor.visit_attrs(&item.attrs, ast::AttrStyle::Inner);
             visitor.visit_impl_items(items);
@@ -800,7 +816,7 @@ pub(crate) fn format_impl(
 
 fn is_impl_single_line(
     context: &RewriteContext<'_>,
-    items: &[ast::ImplItem],
+    items: &[ptr::P<ast::AssocItem>],
     result: &str,
     where_clause_str: &str,
     item: &ast::Item,
@@ -822,15 +838,15 @@ fn format_impl_ref_and_type(
     item: &ast::Item,
     offset: Indent,
 ) -> Option<String> {
-    if let ast::ItemKind::Impl(
+    if let ast::ItemKind::Impl {
         unsafety,
         polarity,
         defaultness,
         ref generics,
-        ref trait_ref,
+        of_trait: ref trait_ref,
         ref self_ty,
-        _,
-    ) = item.node
+        ..
+    } = item.kind
     {
         let mut result = String::with_capacity(128);
 
@@ -838,18 +854,21 @@ fn format_impl_ref_and_type(
         result.push_str(format_defaultness(defaultness));
         result.push_str(format_unsafety(unsafety));
 
-        let shape = generics_shape_from_config(
-            context.config,
-            Shape::indented(offset + last_line_width(&result), context.config),
-            0,
-        )?;
+        let shape = if context.config.version() == Version::Two {
+            Shape::indented(offset + last_line_width(&result), context.config)
+        } else {
+            generics_shape_from_config(
+                context.config,
+                Shape::indented(offset + last_line_width(&result), context.config),
+                0,
+            )?
+        };
         let generics_str = rewrite_generics(context, "impl", generics, shape)?;
         result.push_str(&generics_str);
 
-        let polarity_str = if polarity == ast::ImplPolarity::Negative {
-            "!"
-        } else {
-            ""
+        let polarity_str = match polarity {
+            ast::ImplPolarity::Negative(_) => "!",
+            ast::ImplPolarity::Positive => "",
         };
 
         if let Some(ref trait_ref) = *trait_ref {
@@ -940,7 +959,7 @@ fn rewrite_trait_ref(
 
 pub(crate) struct StructParts<'a> {
     prefix: &'a str,
-    ident: ast::Ident,
+    ident: symbol::Ident,
     vis: &'a ast::Visibility,
     def: &'a ast::VariantData,
     generics: Option<&'a ast::Generics>,
@@ -955,16 +974,16 @@ fn format_header(&self, context: &RewriteContext<'_>) -> String {
     fn from_variant(variant: &'a ast::Variant) -> Self {
         StructParts {
             prefix: "",
-            ident: variant.node.ident,
+            ident: variant.ident,
             vis: &DEFAULT_VISIBILITY,
-            def: &variant.node.data,
+            def: &variant.data,
             generics: None,
             span: variant.span,
         }
     }
 
     pub(crate) fn from_item(item: &'a ast::Item) -> Self {
-        let (prefix, def, generics) = match item.node {
+        let (prefix, def, generics) = match item.kind {
             ast::ItemKind::Struct(ref def, ref generics) => ("struct ", def, generics),
             ast::ItemKind::Union(ref def, ref generics) => ("union ", def, generics),
             _ => unreachable!(),
@@ -1008,7 +1027,7 @@ pub(crate) fn format_trait(
         ref generics,
         ref generic_bounds,
         ref trait_items,
-    ) = item.node
+    ) = item.kind
     {
         let mut result = String::with_capacity(128);
         let header = format!(
@@ -1154,6 +1173,18 @@ pub(crate) fn format_trait(
     }
 }
 
+struct OpaqueTypeBounds<'a> {
+    generic_bounds: &'a ast::GenericBounds,
+}
+
+impl<'a> Rewrite for OpaqueTypeBounds<'a> {
+    fn rewrite(&self, context: &RewriteContext<'_>, shape: Shape) -> Option<String> {
+        self.generic_bounds
+            .rewrite(context, shape)
+            .map(|s| format!("impl {}", s))
+    }
+}
+
 pub(crate) struct TraitAliasBounds<'a> {
     generic_bounds: &'a ast::GenericBounds,
     generics: &'a ast::Generics,
@@ -1195,7 +1226,7 @@ fn rewrite(&self, context: &RewriteContext<'_>, shape: Shape) -> Option<String>
 
 pub(crate) fn format_trait_alias(
     context: &RewriteContext<'_>,
-    ident: ast::Ident,
+    ident: symbol::Ident,
     vis: &ast::Visibility,
     generics: &ast::Generics,
     generic_bounds: &ast::GenericBounds,
@@ -1335,7 +1366,7 @@ pub(crate) fn format_struct_struct(
 }
 
 fn get_bytepos_after_visibility(vis: &ast::Visibility, default_span: Span) -> BytePos {
-    match vis.node {
+    match vis.kind {
         ast::VisibilityKind::Crate(..) | ast::VisibilityKind::Restricted { .. } => vis.span.hi(),
         _ => default_span.lo(),
     }
@@ -1470,21 +1501,23 @@ fn format_tuple_struct(
     Some(result)
 }
 
-fn rewrite_type_prefix(
+fn rewrite_type<R: Rewrite>(
     context: &RewriteContext<'_>,
     indent: Indent,
-    prefix: &str,
-    ident: ast::Ident,
+    ident: symbol::Ident,
+    vis: &ast::Visibility,
     generics: &ast::Generics,
+    generic_bounds_opt: Option<&ast::GenericBounds>,
+    rhs: Option<&R>,
 ) -> Option<String> {
     let mut result = String::with_capacity(128);
-    result.push_str(prefix);
+    result.push_str(&format!("{}type ", format_visibility(context, vis)));
     let ident_str = rewrite_ident(context, ident);
 
-    // 2 = `= `
     if generics.params.is_empty() {
         result.push_str(ident_str)
     } else {
+        // 2 = `= `
         let g_shape = Shape::indented(indent, context.config)
             .offset_left(result.len())?
             .sub_width(2)?;
@@ -1492,8 +1525,20 @@ fn rewrite_type_prefix(
         result.push_str(&generics_str);
     }
 
+    if let Some(bounds) = generic_bounds_opt {
+        if !bounds.is_empty() {
+            // 2 = `: `
+            let shape = Shape::indented(indent, context.config).offset_left(result.len() + 2)?;
+            let type_bounds = bounds.rewrite(context, shape).map(|s| format!(": {}", s))?;
+            result.push_str(&type_bounds);
+        }
+    }
+
     let where_budget = context.budget(last_line_width(&result));
-    let option = WhereClauseOption::snuggled(&result);
+    let mut option = WhereClauseOption::snuggled(&result);
+    if rhs.is_none() {
+        option.suppress_comma();
+    }
     let where_clause_str = rewrite_where_clause(
         context,
         &generics.where_clause,
@@ -1507,68 +1552,41 @@ fn rewrite_type_prefix(
     )?;
     result.push_str(&where_clause_str);
 
-    Some(result)
-}
-
-fn rewrite_type_item<R: Rewrite>(
-    context: &RewriteContext<'_>,
-    indent: Indent,
-    prefix: &str,
-    suffix: &str,
-    ident: ast::Ident,
-    rhs: &R,
-    generics: &ast::Generics,
-    vis: &ast::Visibility,
-) -> Option<String> {
-    let mut result = String::with_capacity(128);
-    result.push_str(&rewrite_type_prefix(
-        context,
-        indent,
-        &format!("{}{} ", format_visibility(context, vis), prefix),
-        ident,
-        generics,
-    )?);
+    if let Some(ty) = rhs {
+        // If there's a where clause, add a newline before the assignment. Otherwise just add a
+        // space.
+        if !generics.where_clause.predicates.is_empty() {
+            result.push_str(&indent.to_string_with_newline(context.config));
+        } else {
+            result.push(' ');
+        }
+        let lhs = format!("{}=", result);
 
-    if generics.where_clause.predicates.is_empty() {
-        result.push_str(suffix);
+        // 1 = `;`
+        let shape = Shape::indented(indent, context.config).sub_width(1)?;
+        rewrite_assign_rhs(context, lhs, &*ty, shape).map(|s| s + ";")
     } else {
-        result.push_str(&indent.to_string_with_newline(context.config));
-        result.push_str(suffix.trim_start());
+        Some(format!("{};", result))
     }
-
-    // 1 = ";"
-    let rhs_shape = Shape::indented(indent, context.config).sub_width(1)?;
-    rewrite_assign_rhs(context, result, rhs, rhs_shape).map(|s| s + ";")
 }
 
-pub(crate) fn rewrite_type_alias(
+pub(crate) fn rewrite_opaque_type(
     context: &RewriteContext<'_>,
     indent: Indent,
-    ident: ast::Ident,
-    ty: &ast::Ty,
-    generics: &ast::Generics,
-    vis: &ast::Visibility,
-) -> Option<String> {
-    rewrite_type_item(context, indent, "type", " =", ident, ty, generics, vis)
-}
-
-pub(crate) fn rewrite_existential_type(
-    context: &RewriteContext<'_>,
-    indent: Indent,
-    ident: ast::Ident,
+    ident: symbol::Ident,
     generic_bounds: &ast::GenericBounds,
     generics: &ast::Generics,
     vis: &ast::Visibility,
 ) -> Option<String> {
-    rewrite_type_item(
+    let opaque_type_bounds = OpaqueTypeBounds { generic_bounds };
+    rewrite_type(
         context,
         indent,
-        "existential type",
-        ":",
         ident,
-        generic_bounds,
-        generics,
         vis,
+        generics,
+        Some(generic_bounds),
+        Some(&opaque_type_bounds),
     )
 }
 
@@ -1636,7 +1654,7 @@ pub(crate) fn rewrite_struct_field(
         shape,
         attrs_extendable,
     )?;
-    let overhead = last_line_width(&attr_prefix);
+    let overhead = trimmed_last_line_width(&attr_prefix);
     let lhs_offset = lhs_max_width.saturating_sub(overhead);
     for _ in 0..lhs_offset {
         spacing.push(' ');
@@ -1669,7 +1687,7 @@ pub(crate) fn rewrite_struct_field(
 pub(crate) struct StaticParts<'a> {
     prefix: &'a str,
     vis: &'a ast::Visibility,
-    ident: ast::Ident,
+    ident: symbol::Ident,
     ty: &'a ast::Ty,
     mutability: ast::Mutability,
     expr_opt: Option<&'a ptr::P<ast::Expr>>,
@@ -1679,10 +1697,12 @@ pub(crate) struct StaticParts<'a> {
 
 impl<'a> StaticParts<'a> {
     pub(crate) fn from_item(item: &'a ast::Item) -> Self {
-        let (prefix, ty, mutability, expr) = match item.node {
-            ast::ItemKind::Static(ref ty, mutability, ref expr) => ("static", ty, mutability, expr),
-            ast::ItemKind::Const(ref ty, ref expr) => {
-                ("const", ty, ast::Mutability::Immutable, expr)
+        let (defaultness, prefix, ty, mutability, expr) = match item.kind {
+            ast::ItemKind::Static(ref ty, mutability, ref expr) => {
+                (None, "static", ty, mutability, expr)
+            }
+            ast::ItemKind::Const(defaultness, ref ty, ref expr) => {
+                (Some(defaultness), "const", ty, ast::Mutability::Not, expr)
             }
             _ => unreachable!(),
         };
@@ -1692,15 +1712,17 @@ pub(crate) fn from_item(item: &'a ast::Item) -> Self {
             ident: item.ident,
             ty,
             mutability,
-            expr_opt: Some(expr),
-            defaultness: None,
+            expr_opt: expr.as_ref(),
+            defaultness,
             span: item.span,
         }
     }
 
-    pub(crate) fn from_trait_item(ti: &'a ast::TraitItem) -> Self {
-        let (ty, expr_opt) = match ti.node {
-            ast::TraitItemKind::Const(ref ty, ref expr_opt) => (ty, expr_opt),
+    pub(crate) fn from_trait_item(ti: &'a ast::AssocItem) -> Self {
+        let (defaultness, ty, expr_opt) = match ti.kind {
+            ast::AssocItemKind::Const(defaultness, ref ty, ref expr_opt) => {
+                (defaultness, ty, expr_opt)
+            }
             _ => unreachable!(),
         };
         StaticParts {
@@ -1708,16 +1730,16 @@ pub(crate) fn from_trait_item(ti: &'a ast::TraitItem) -> Self {
             vis: &DEFAULT_VISIBILITY,
             ident: ti.ident,
             ty,
-            mutability: ast::Mutability::Immutable,
+            mutability: ast::Mutability::Not,
             expr_opt: expr_opt.as_ref(),
-            defaultness: None,
+            defaultness: Some(defaultness),
             span: ti.span,
         }
     }
 
-    pub(crate) fn from_impl_item(ii: &'a ast::ImplItem) -> Self {
-        let (ty, expr) = match ii.node {
-            ast::ImplItemKind::Const(ref ty, ref expr) => (ty, expr),
+    pub(crate) fn from_impl_item(ii: &'a ast::AssocItem) -> Self {
+        let (defaultness, ty, expr) = match ii.kind {
+            ast::AssocItemKind::Const(defaultness, ref ty, ref expr) => (defaultness, ty, expr),
             _ => unreachable!(),
         };
         StaticParts {
@@ -1725,9 +1747,9 @@ pub(crate) fn from_impl_item(ii: &'a ast::ImplItem) -> Self {
             vis: &ii.vis,
             ident: ii.ident,
             ty,
-            mutability: ast::Mutability::Immutable,
-            expr_opt: Some(expr),
-            defaultness: Some(ii.defaultness),
+            mutability: ast::Mutability::Not,
+            expr_opt: expr.as_ref(),
+            defaultness: Some(defaultness),
             span: ii.span,
         }
     }
@@ -1745,7 +1767,7 @@ fn rewrite_static(
         static_parts.defaultness.map_or("", format_defaultness),
         static_parts.prefix,
         format_mutability(static_parts.mutability),
-        static_parts.ident,
+        rewrite_ident(context, static_parts.ident),
         colon,
     );
     // 2 = " =".len()
@@ -1785,96 +1807,116 @@ fn rewrite_static(
     }
 }
 
-pub(crate) fn rewrite_associated_type(
-    ident: ast::Ident,
+pub(crate) fn rewrite_type_alias(
+    ident: symbol::Ident,
     ty_opt: Option<&ptr::P<ast::Ty>>,
     generics: &ast::Generics,
     generic_bounds_opt: Option<&ast::GenericBounds>,
     context: &RewriteContext<'_>,
     indent: Indent,
+    vis: &ast::Visibility,
 ) -> Option<String> {
-    let ident_str = rewrite_ident(context, ident);
-    // 5 = "type "
-    let generics_shape = Shape::indented(indent, context.config).offset_left(5)?;
-    let generics_str = rewrite_generics(context, ident_str, generics, generics_shape)?;
-    let prefix = format!("type {}", generics_str);
+    rewrite_type(
+        context,
+        indent,
+        ident,
+        vis,
+        generics,
+        generic_bounds_opt,
+        ty_opt,
+    )
+}
 
-    let type_bounds_str = if let Some(bounds) = generic_bounds_opt {
-        if bounds.is_empty() {
-            String::new()
-        } else {
-            // 2 = ": ".len()
-            let shape = Shape::indented(indent, context.config).offset_left(prefix.len() + 2)?;
-            bounds.rewrite(context, shape).map(|s| format!(": {}", s))?
-        }
-    } else {
-        String::new()
-    };
+struct OpaqueType<'a> {
+    bounds: &'a ast::GenericBounds,
+}
 
-    if let Some(ty) = ty_opt {
-        // 1 = `;`
-        let shape = Shape::indented(indent, context.config).sub_width(1)?;
-        let lhs = format!("{}{} =", prefix, type_bounds_str);
-        rewrite_assign_rhs(context, lhs, &**ty, shape).map(|s| s + ";")
-    } else {
-        Some(format!("{}{};", prefix, type_bounds_str))
+impl<'a> Rewrite for OpaqueType<'a> {
+    fn rewrite(&self, context: &RewriteContext<'_>, shape: Shape) -> Option<String> {
+        let shape = shape.offset_left(5)?; // `impl `
+        self.bounds
+            .rewrite(context, shape)
+            .map(|s| format!("impl {}", s))
     }
 }
 
-pub(crate) fn rewrite_existential_impl_type(
+pub(crate) fn rewrite_opaque_impl_type(
     context: &RewriteContext<'_>,
-    ident: ast::Ident,
+    ident: symbol::Ident,
     generics: &ast::Generics,
     generic_bounds: &ast::GenericBounds,
     indent: Indent,
 ) -> Option<String> {
-    rewrite_associated_type(ident, None, generics, Some(generic_bounds), context, indent)
-        .map(|s| format!("existential {}", s))
+    let ident_str = rewrite_ident(context, ident);
+    // 5 = "type "
+    let generics_shape = Shape::indented(indent, context.config).offset_left(5)?;
+    let generics_str = rewrite_generics(context, ident_str, generics, generics_shape)?;
+    let prefix = format!("type {} =", generics_str);
+    let rhs = OpaqueType {
+        bounds: generic_bounds,
+    };
+
+    rewrite_assign_rhs(
+        context,
+        &prefix,
+        &rhs,
+        Shape::indented(indent, context.config).sub_width(1)?,
+    )
+    .map(|s| s + ";")
 }
 
 pub(crate) fn rewrite_associated_impl_type(
-    ident: ast::Ident,
+    ident: symbol::Ident,
+    vis: &ast::Visibility,
     defaultness: ast::Defaultness,
     ty_opt: Option<&ptr::P<ast::Ty>>,
     generics: &ast::Generics,
     context: &RewriteContext<'_>,
     indent: Indent,
 ) -> Option<String> {
-    let result = rewrite_associated_type(ident, ty_opt, generics, None, context, indent)?;
+    let result = rewrite_type_alias(ident, ty_opt, generics, None, context, indent, vis)?;
 
     match defaultness {
-        ast::Defaultness::Default => Some(format!("default {}", result)),
+        ast::Defaultness::Default(..) => Some(format!("default {}", result)),
         _ => Some(result),
     }
 }
 
-impl Rewrite for ast::FunctionRetTy {
+impl Rewrite for ast::FnRetTy {
     fn rewrite(&self, context: &RewriteContext<'_>, shape: Shape) -> Option<String> {
         match *self {
-            ast::FunctionRetTy::Default(_) => Some(String::new()),
-            ast::FunctionRetTy::Ty(ref ty) => {
-                let inner_width = shape.width.checked_sub(3)?;
-                ty.rewrite(context, Shape::legacy(inner_width, shape.indent + 3))
-                    .map(|r| format!("-> {}", r))
+            ast::FnRetTy::Default(_) => Some(String::new()),
+            ast::FnRetTy::Ty(ref ty) => {
+                if context.config.version() == Version::One
+                    || context.config.indent_style() == IndentStyle::Visual
+                {
+                    let inner_width = shape.width.checked_sub(3)?;
+                    return ty
+                        .rewrite(context, Shape::legacy(inner_width, shape.indent + 3))
+                        .map(|r| format!("-> {}", r));
+                }
+
+                ty.rewrite(context, shape.offset_left(3)?)
+                    .map(|s| format!("-> {}", s))
             }
         }
     }
 }
 
 fn is_empty_infer(ty: &ast::Ty, pat_span: Span) -> bool {
-    match ty.node {
+    match ty.kind {
         ast::TyKind::Infer => ty.span.hi() == pat_span.hi(),
         _ => false,
     }
 }
 
-/// Recover any missing comments between the argument and the type.
+/// Recover any missing comments between the param and the type.
 ///
 /// # Returns
 ///
 /// A 2-len tuple with the comment before the colon in first position, and the comment after the
 /// colon in second position.
-fn get_missing_arg_comments(
+fn get_missing_param_comments(
     context: &RewriteContext<'_>,
     pat_span: Span,
     ty_span: Span,
@@ -1904,18 +1946,45 @@ fn get_missing_arg_comments(
     (comment_before_colon, comment_after_colon)
 }
 
-impl Rewrite for ast::Arg {
+impl Rewrite for ast::Param {
     fn rewrite(&self, context: &RewriteContext<'_>, shape: Shape) -> Option<String> {
+        let param_attrs_result = self
+            .attrs
+            .rewrite(context, Shape::legacy(shape.width, shape.indent))?;
+        let (span, has_multiple_attr_lines) = if !self.attrs.is_empty() {
+            let num_attrs = self.attrs.len();
+            (
+                mk_sp(self.attrs[num_attrs - 1].span.hi(), self.pat.span.lo()),
+                param_attrs_result.contains("\n"),
+            )
+        } else {
+            (mk_sp(self.span.lo(), self.span.lo()), false)
+        };
+
         if let Some(ref explicit_self) = self.to_self() {
-            rewrite_explicit_self(context, explicit_self)
-        } else if is_named_arg(self) {
-            let mut result = self
-                .pat
-                .rewrite(context, Shape::legacy(shape.width, shape.indent))?;
+            rewrite_explicit_self(
+                context,
+                explicit_self,
+                &param_attrs_result,
+                span,
+                shape,
+                has_multiple_attr_lines,
+            )
+        } else if is_named_param(self) {
+            let mut result = combine_strs_with_missing_comments(
+                context,
+                &param_attrs_result,
+                &self
+                    .pat
+                    .rewrite(context, Shape::legacy(shape.width, shape.indent))?,
+                span,
+                shape,
+                !has_multiple_attr_lines,
+            )?;
 
             if !is_empty_infer(&*self.ty, self.pat.span) {
                 let (before_comment, after_comment) =
-                    get_missing_arg_comments(context, self.pat.span, self.ty.span, shape);
+                    get_missing_param_comments(context, self.pat.span, self.ty.span, shape);
                 result.push_str(&before_comment);
                 result.push_str(colon_spaces(context.config));
                 result.push_str(&after_comment);
@@ -1937,6 +2006,10 @@ fn rewrite(&self, context: &RewriteContext<'_>, shape: Shape) -> Option<String>
 fn rewrite_explicit_self(
     context: &RewriteContext<'_>,
     explicit_self: &ast::ExplicitSelf,
+    param_attrs: &str,
+    span: Span,
+    shape: Shape,
+    has_multiple_attr_lines: bool,
 ) -> Option<String> {
     match explicit_self.node {
         ast::SelfKind::Region(lt, m) => {
@@ -1947,9 +2020,23 @@ fn rewrite_explicit_self(
                         context,
                         Shape::legacy(context.config.max_width(), Indent::empty()),
                     )?;
-                    Some(format!("&{} {}self", lifetime_str, mut_str))
+                    Some(combine_strs_with_missing_comments(
+                        context,
+                        &param_attrs,
+                        &format!("&{} {}self", lifetime_str, mut_str),
+                        span,
+                        shape,
+                        !has_multiple_attr_lines,
+                    )?)
                 }
-                None => Some(format!("&{}self", mut_str)),
+                None => Some(combine_strs_with_missing_comments(
+                    context,
+                    &param_attrs,
+                    &format!("&{}self", mut_str),
+                    span,
+                    shape,
+                    !has_multiple_attr_lines,
+                )?),
             }
         }
         ast::SelfKind::Explicit(ref ty, mutability) => {
@@ -1958,49 +2045,69 @@ fn rewrite_explicit_self(
                 Shape::legacy(context.config.max_width(), Indent::empty()),
             )?;
 
-            Some(format!(
-                "{}self: {}",
-                format_mutability(mutability),
-                type_str
-            ))
+            Some(combine_strs_with_missing_comments(
+                context,
+                &param_attrs,
+                &format!("{}self: {}", format_mutability(mutability), type_str),
+                span,
+                shape,
+                !has_multiple_attr_lines,
+            )?)
         }
-        ast::SelfKind::Value(mutability) => Some(format!("{}self", format_mutability(mutability))),
+        ast::SelfKind::Value(mutability) => Some(combine_strs_with_missing_comments(
+            context,
+            &param_attrs,
+            &format!("{}self", format_mutability(mutability)),
+            span,
+            shape,
+            !has_multiple_attr_lines,
+        )?),
     }
 }
 
-pub(crate) fn span_lo_for_arg(arg: &ast::Arg) -> BytePos {
-    if is_named_arg(arg) {
-        arg.pat.span.lo()
+pub(crate) fn span_lo_for_param(param: &ast::Param) -> BytePos {
+    if param.attrs.is_empty() {
+        if is_named_param(param) {
+            param.pat.span.lo()
+        } else {
+            param.ty.span.lo()
+        }
     } else {
-        arg.ty.span.lo()
+        param.attrs[0].span.lo()
     }
 }
 
-pub(crate) fn span_hi_for_arg(context: &RewriteContext<'_>, arg: &ast::Arg) -> BytePos {
-    match arg.ty.node {
-        ast::TyKind::Infer if context.snippet(arg.ty.span) == "_" => arg.ty.span.hi(),
-        ast::TyKind::Infer if is_named_arg(arg) => arg.pat.span.hi(),
-        _ => arg.ty.span.hi(),
+pub(crate) fn span_hi_for_param(context: &RewriteContext<'_>, param: &ast::Param) -> BytePos {
+    match param.ty.kind {
+        ast::TyKind::Infer if context.snippet(param.ty.span) == "_" => param.ty.span.hi(),
+        ast::TyKind::Infer if is_named_param(param) => param.pat.span.hi(),
+        _ => param.ty.span.hi(),
     }
 }
 
-pub(crate) fn is_named_arg(arg: &ast::Arg) -> bool {
-    if let ast::PatKind::Ident(_, ident, _) = arg.pat.node {
+pub(crate) fn is_named_param(param: &ast::Param) -> bool {
+    if let ast::PatKind::Ident(_, ident, _) = param.pat.kind {
         ident.name != symbol::kw::Invalid
     } else {
         true
     }
 }
 
+#[derive(Copy, Clone, Debug, PartialEq, Eq)]
+pub(crate) enum FnBraceStyle {
+    SameLine,
+    NextLine,
+    None,
+}
+
 // Return type is (result, force_new_line_for_brace)
 fn rewrite_fn_base(
     context: &RewriteContext<'_>,
     indent: Indent,
-    ident: ast::Ident,
+    ident: symbol::Ident,
     fn_sig: &FnSig<'_>,
     span: Span,
-    newline_brace: bool,
-    has_body: bool,
+    fn_brace_style: FnBraceStyle,
 ) -> Option<(String, bool)> {
     let mut force_new_line_for_brace = false;
 
@@ -2013,7 +2120,7 @@ fn rewrite_fn_base(
     result.push_str("fn ");
 
     // Generics.
-    let overhead = if has_body && !newline_brace {
+    let overhead = if let FnBraceStyle::SameLine = fn_brace_style {
         // 4 = `() {`
         4
     } else {
@@ -2050,20 +2157,19 @@ fn rewrite_fn_base(
     let multi_line_ret_str = ret_str.contains('\n');
     let ret_str_len = if multi_line_ret_str { 0 } else { ret_str.len() };
 
-    // Args.
-    let (one_line_budget, multi_line_budget, mut arg_indent) = compute_budgets_for_args(
+    // Params.
+    let (one_line_budget, multi_line_budget, mut param_indent) = compute_budgets_for_params(
         context,
         &result,
         indent,
         ret_str_len,
-        newline_brace,
-        has_body,
+        fn_brace_style,
         multi_line_ret_str,
     )?;
 
     debug!(
-        "rewrite_fn_base: one_line_budget: {}, multi_line_budget: {}, arg_indent: {:?}",
-        one_line_budget, multi_line_budget, arg_indent
+        "rewrite_fn_base: one_line_budget: {}, multi_line_budget: {}, param_indent: {:?}",
+        one_line_budget, multi_line_budget, param_indent
     );
 
     result.push('(');
@@ -2072,79 +2178,85 @@ fn rewrite_fn_base(
         && !snuggle_angle_bracket
         && context.config.indent_style() == IndentStyle::Visual
     {
-        result.push_str(&arg_indent.to_string_with_newline(context.config));
+        result.push_str(&param_indent.to_string_with_newline(context.config));
     }
 
     // Skip `pub(crate)`.
     let lo_after_visibility = get_bytepos_after_visibility(&fn_sig.visibility, span);
     // A conservative estimation, to goal is to be over all parens in generics
-    let args_start = fn_sig
+    let params_start = fn_sig
         .generics
         .params
         .iter()
         .last()
         .map_or(lo_after_visibility, |param| param.span().hi());
-    let args_end = if fd.inputs.is_empty() {
+    let params_end = if fd.inputs.is_empty() {
         context
             .snippet_provider
-            .span_after(mk_sp(args_start, span.hi()), ")")
+            .span_after(mk_sp(params_start, span.hi()), ")")
     } else {
         let last_span = mk_sp(fd.inputs[fd.inputs.len() - 1].span().hi(), span.hi());
         context.snippet_provider.span_after(last_span, ")")
     };
-    let args_span = mk_sp(
+    let params_span = mk_sp(
         context
             .snippet_provider
-            .span_after(mk_sp(args_start, span.hi()), "("),
-        args_end,
+            .span_after(mk_sp(params_start, span.hi()), "("),
+        params_end,
     );
-    let arg_str = rewrite_args(
+    let param_str = rewrite_params(
         context,
         &fd.inputs,
         one_line_budget,
         multi_line_budget,
         indent,
-        arg_indent,
-        args_span,
-        fd.c_variadic,
+        param_indent,
+        params_span,
+        fd.c_variadic(),
     )?;
 
-    let put_args_in_block = match context.config.indent_style() {
-        IndentStyle::Block => arg_str.contains('\n') || arg_str.len() > one_line_budget,
+    let put_params_in_block = match context.config.indent_style() {
+        IndentStyle::Block => param_str.contains('\n') || param_str.len() > one_line_budget,
         _ => false,
     } && !fd.inputs.is_empty();
 
-    let mut args_last_line_contains_comment = false;
-    let mut no_args_and_over_max_width = false;
+    let mut params_last_line_contains_comment = false;
+    let mut no_params_and_over_max_width = false;
 
-    if put_args_in_block {
-        arg_indent = indent.block_indent(context.config);
-        result.push_str(&arg_indent.to_string_with_newline(context.config));
-        result.push_str(&arg_str);
+    if put_params_in_block {
+        param_indent = indent.block_indent(context.config);
+        result.push_str(&param_indent.to_string_with_newline(context.config));
+        result.push_str(&param_str);
         result.push_str(&indent.to_string_with_newline(context.config));
         result.push(')');
     } else {
-        result.push_str(&arg_str);
+        result.push_str(&param_str);
         let used_width = last_line_used_width(&result, indent.width()) + first_line_width(&ret_str);
         // Put the closing brace on the next line if it overflows the max width.
         // 1 = `)`
         let closing_paren_overflow_max_width =
             fd.inputs.is_empty() && used_width + 1 > context.config.max_width();
-        // If the last line of args contains comment, we cannot put the closing paren
+        // If the last line of params contains comment, we cannot put the closing paren
         // on the same line.
-        args_last_line_contains_comment = arg_str
+        params_last_line_contains_comment = param_str
             .lines()
             .last()
             .map_or(false, |last_line| last_line.contains("//"));
 
         if context.config.version() == Version::Two {
-            result.push(')');
-            if closing_paren_overflow_max_width || args_last_line_contains_comment {
+            if closing_paren_overflow_max_width {
+                result.push(')');
+                result.push_str(&indent.to_string_with_newline(context.config));
+                no_params_and_over_max_width = true;
+            } else if params_last_line_contains_comment {
                 result.push_str(&indent.to_string_with_newline(context.config));
-                no_args_and_over_max_width = true;
+                result.push(')');
+                no_params_and_over_max_width = true;
+            } else {
+                result.push(')');
             }
         } else {
-            if closing_paren_overflow_max_width || args_last_line_contains_comment {
+            if closing_paren_overflow_max_width || params_last_line_contains_comment {
                 result.push_str(&indent.to_string_with_newline(context.config));
             }
             result.push(')');
@@ -2152,16 +2264,16 @@ fn rewrite_fn_base(
     }
 
     // Return type.
-    if let ast::FunctionRetTy::Ty(..) = fd.output {
+    if let ast::FnRetTy::Ty(..) = fd.output {
         let ret_should_indent = match context.config.indent_style() {
-            // If our args are block layout then we surely must have space.
-            IndentStyle::Block if put_args_in_block || fd.inputs.is_empty() => false,
-            _ if args_last_line_contains_comment => false,
+            // If our params are block layout then we surely must have space.
+            IndentStyle::Block if put_params_in_block || fd.inputs.is_empty() => false,
+            _ if params_last_line_contains_comment => false,
             _ if result.contains('\n') || multi_line_ret_str => true,
             _ => {
                 // If the return type would push over the max width, then put the return type on
                 // a new line. With the +1 for the signature length an additional space between
-                // the closing parenthesis of the argument and the arrow '->' is considered.
+                // the closing parenthesis of the param and the arrow '->' is considered.
                 let mut sig_length = result.len() + indent.width() + ret_str_len + 1;
 
                 // If there is no where-clause, take into account the space after the return type
@@ -2173,38 +2285,58 @@ fn rewrite_fn_base(
                 sig_length > context.config.max_width()
             }
         };
-        let ret_indent = if ret_should_indent {
-            let indent = if arg_str.is_empty() {
-                // Aligning with non-existent args looks silly.
-                force_new_line_for_brace = true;
-                indent + 4
+        let ret_shape = if ret_should_indent {
+            if context.config.version() == Version::One
+                || context.config.indent_style() == IndentStyle::Visual
+            {
+                let indent = if param_str.is_empty() {
+                    // Aligning with non-existent params looks silly.
+                    force_new_line_for_brace = true;
+                    indent + 4
+                } else {
+                    // FIXME: we might want to check that using the param indent
+                    // doesn't blow our budget, and if it does, then fallback to
+                    // the where-clause indent.
+                    param_indent
+                };
+
+                result.push_str(&indent.to_string_with_newline(context.config));
+                Shape::indented(indent, context.config)
             } else {
-                // FIXME: we might want to check that using the arg indent
-                // doesn't blow our budget, and if it does, then fallback to
-                // the where-clause indent.
-                arg_indent
-            };
+                let mut ret_shape = Shape::indented(indent, context.config);
+                if param_str.is_empty() {
+                    // Aligning with non-existent params looks silly.
+                    force_new_line_for_brace = true;
+                    ret_shape = if context.use_block_indent() {
+                        ret_shape.offset_left(4).unwrap_or(ret_shape)
+                    } else {
+                        ret_shape.indent = ret_shape.indent + 4;
+                        ret_shape
+                    };
+                }
 
-            result.push_str(&indent.to_string_with_newline(context.config));
-            indent
+                result.push_str(&ret_shape.indent.to_string_with_newline(context.config));
+                ret_shape
+            }
         } else {
             if context.config.version() == Version::Two {
-                if !arg_str.is_empty() || !no_args_and_over_max_width {
+                if !param_str.is_empty() || !no_params_and_over_max_width {
                     result.push(' ');
                 }
             } else {
                 result.push(' ');
             }
 
-            Indent::new(indent.block_indent, last_line_width(&result))
+            let ret_shape = Shape::indented(indent, context.config);
+            ret_shape
+                .offset_left(last_line_width(&result))
+                .unwrap_or(ret_shape)
         };
 
         if multi_line_ret_str || ret_should_indent {
             // Now that we know the proper indent and width, we need to
             // re-layout the return type.
-            let ret_str = fd
-                .output
-                .rewrite(context, Shape::indented(ret_indent, context.config))?;
+            let ret_str = fd.output.rewrite(context, ret_shape)?;
             result.push_str(&ret_str);
         } else {
             result.push_str(&ret_str);
@@ -2238,19 +2370,19 @@ fn rewrite_fn_base(
     }
 
     let pos_before_where = match fd.output {
-        ast::FunctionRetTy::Default(..) => args_span.hi(),
-        ast::FunctionRetTy::Ty(ref ty) => ty.span.hi(),
+        ast::FnRetTy::Default(..) => params_span.hi(),
+        ast::FnRetTy::Ty(ref ty) => ty.span.hi(),
     };
 
-    let is_args_multi_lined = arg_str.contains('\n');
+    let is_params_multi_lined = param_str.contains('\n');
 
-    let space = if put_args_in_block && ret_str.is_empty() {
+    let space = if put_params_in_block && ret_str.is_empty() {
         WhereClauseSpace::Space
     } else {
         WhereClauseSpace::Newline
     };
-    let mut option = WhereClauseOption::new(!has_body, space);
-    if is_args_multi_lined {
+    let mut option = WhereClauseOption::new(fn_brace_style == FnBraceStyle::None, space);
+    if is_params_multi_lined {
         option.veto_single_line();
     }
     let where_clause_str = rewrite_where_clause(
@@ -2265,11 +2397,11 @@ fn rewrite_fn_base(
         option,
     )?;
     // If there are neither where-clause nor return type, we may be missing comments between
-    // args and `{`.
+    // params and `{`.
     if where_clause_str.is_empty() {
-        if let ast::FunctionRetTy::Default(ret_span) = fd.output {
+        if let ast::FnRetTy::Default(ret_span) = fd.output {
             match recover_missing_comment_in_span(
-                mk_sp(args_span.hi(), ret_span.hi()),
+                mk_sp(params_span.hi(), ret_span.hi()),
                 shape,
                 context,
                 last_line_width(&result),
@@ -2286,7 +2418,8 @@ fn rewrite_fn_base(
     result.push_str(&where_clause_str);
 
     force_new_line_for_brace |= last_line_contains_single_line_comment(&result);
-    force_new_line_for_brace |= is_args_multi_lined && context.config.where_single_line();
+    force_new_line_for_brace |=
+        is_params_multi_lined && context.config.where_single_line() && !where_clause_str.is_empty();
     Some((result, force_new_line_for_brace))
 }
 
@@ -2349,17 +2482,17 @@ fn veto_single_line(&mut self) {
     }
 }
 
-fn rewrite_args(
+fn rewrite_params(
     context: &RewriteContext<'_>,
-    args: &[ast::Arg],
+    params: &[ast::Param],
     one_line_budget: usize,
     multi_line_budget: usize,
     indent: Indent,
-    arg_indent: Indent,
+    param_indent: Indent,
     span: Span,
     variadic: bool,
 ) -> Option<String> {
-    if args.is_empty() {
+    if params.is_empty() {
         let comment = context
             .snippet(mk_sp(
                 span.lo(),
@@ -2369,16 +2502,17 @@ fn rewrite_args(
             .trim();
         return Some(comment.to_owned());
     }
-    let arg_items: Vec<_> = itemize_list(
+    let param_items: Vec<_> = itemize_list(
         context.snippet_provider,
-        args.iter(),
+        params.iter(),
         ")",
         ",",
-        |arg| span_lo_for_arg(arg),
-        |arg| arg.ty.span.hi(),
-        |arg| {
-            arg.rewrite(context, Shape::legacy(multi_line_budget, arg_indent))
-                .or_else(|| Some(context.snippet(arg.span()).to_owned()))
+        |param| span_lo_for_param(param),
+        |param| param.ty.span.hi(),
+        |param| {
+            param
+                .rewrite(context, Shape::legacy(multi_line_budget, param_indent))
+                .or_else(|| Some(context.snippet(param.span()).to_owned()))
         },
         span.lo(),
         span.hi(),
@@ -2387,11 +2521,11 @@ fn rewrite_args(
     .collect();
 
     let tactic = definitive_tactic(
-        &arg_items,
+        &param_items,
         context
             .config
             .fn_args_layout()
-            .to_list_tactic(arg_items.len()),
+            .to_list_tactic(param_items.len()),
         Separator::Comma,
         one_line_budget,
     );
@@ -2401,7 +2535,7 @@ fn rewrite_args(
     };
     let indent = match context.config.indent_style() {
         IndentStyle::Block => indent.block_indent(context.config),
-        IndentStyle::Visual => arg_indent,
+        IndentStyle::Visual => param_indent,
     };
     let trailing_separator = if variadic {
         SeparatorTactic::Never
@@ -2416,38 +2550,33 @@ fn rewrite_args(
         .trailing_separator(trailing_separator)
         .ends_with_newline(tactic.ends_with_newline(context.config.indent_style()))
         .preserve_newline(true);
-    write_list(&arg_items, &fmt)
+    write_list(&param_items, &fmt)
 }
 
-fn compute_budgets_for_args(
+fn compute_budgets_for_params(
     context: &RewriteContext<'_>,
     result: &str,
     indent: Indent,
     ret_str_len: usize,
-    newline_brace: bool,
-    has_braces: bool,
+    fn_brace_style: FnBraceStyle,
     force_vertical_layout: bool,
-) -> Option<((usize, usize, Indent))> {
+) -> Option<(usize, usize, Indent)> {
     debug!(
-        "compute_budgets_for_args {} {:?}, {}, {}",
+        "compute_budgets_for_params {} {:?}, {}, {:?}",
         result.len(),
         indent,
         ret_str_len,
-        newline_brace
+        fn_brace_style,
     );
     // Try keeping everything on the same line.
     if !result.contains('\n') && !force_vertical_layout {
         // 2 = `()`, 3 = `() `, space is before ret_string.
         let overhead = if ret_str_len == 0 { 2 } else { 3 };
         let mut used_space = indent.width() + result.len() + ret_str_len + overhead;
-        if has_braces {
-            if !newline_brace {
-                // 2 = `{}`
-                used_space += 2;
-            }
-        } else {
-            // 1 = `;`
-            used_space += 1;
+        match fn_brace_style {
+            FnBraceStyle::None => used_space += 1,     // 1 = `;`
+            FnBraceStyle::SameLine => used_space += 2, // 2 = `{}`
+            FnBraceStyle::NextLine => (),
         }
         let one_line_budget = context.budget(used_space);
 
@@ -2460,7 +2589,10 @@ fn compute_budgets_for_args(
                 }
                 IndentStyle::Visual => {
                     let indent = indent + result.len() + 1;
-                    let multi_line_overhead = indent.width() + if newline_brace { 2 } else { 4 };
+                    let multi_line_overhead = match fn_brace_style {
+                        FnBraceStyle::SameLine => 4,
+                        _ => 2,
+                    } + indent.width();
                     (indent, context.budget(multi_line_overhead))
                 }
             };
@@ -2469,7 +2601,7 @@ fn compute_budgets_for_args(
         }
     }
 
-    // Didn't work. we must force vertical layout and put args on a newline.
+    // Didn't work. we must force vertical layout and put params on a newline.
     let new_indent = indent.block_indent(context.config);
     let used_space = match context.config.indent_style() {
         // 1 = `,`
@@ -2480,16 +2612,21 @@ fn compute_budgets_for_args(
     Some((0, context.budget(used_space), new_indent))
 }
 
-fn newline_for_brace(config: &Config, where_clause: &ast::WhereClause) -> bool {
+fn newline_for_brace(config: &Config, where_clause: &ast::WhereClause) -> FnBraceStyle {
     let predicate_count = where_clause.predicates.len();
 
     if config.where_single_line() && predicate_count == 1 {
-        return false;
+        return FnBraceStyle::SameLine;
     }
     let brace_style = config.brace_style();
 
-    brace_style == BraceStyle::AlwaysNextLine
-        || (brace_style == BraceStyle::SameLineWhere && predicate_count > 0)
+    let use_next_line = brace_style == BraceStyle::AlwaysNextLine
+        || (brace_style == BraceStyle::SameLineWhere && predicate_count > 0);
+    if use_next_line {
+        FnBraceStyle::NextLine
+    } else {
+        FnBraceStyle::SameLine
+    }
 }
 
 fn rewrite_generics(
@@ -2509,11 +2646,7 @@ fn rewrite_generics(
     overflow::rewrite_with_angle_brackets(context, ident, params, shape, generics.span)
 }
 
-pub(crate) fn generics_shape_from_config(
-    config: &Config,
-    shape: Shape,
-    offset: usize,
-) -> Option<Shape> {
+fn generics_shape_from_config(config: &Config, shape: Shape, offset: usize) -> Option<Shape> {
     match config.indent_style() {
         IndentStyle::Visual => shape.visual_indent(1 + offset).sub_width(offset + 2),
         IndentStyle::Block => {
@@ -2800,7 +2933,7 @@ fn rewrite_comments_before_after_where(
 fn format_header(
     context: &RewriteContext<'_>,
     item_name: &str,
-    ident: ast::Ident,
+    ident: symbol::Ident,
     vis: &ast::Visibility,
 ) -> String {
     format!(
@@ -2924,18 +3057,17 @@ fn rewrite(&self, context: &RewriteContext<'_>, shape: Shape) -> Option<String>
         // FIXME: this may be a faulty span from libsyntax.
         let span = mk_sp(self.span.lo(), self.span.hi() - BytePos(1));
 
-        let item_str = match self.node {
-            ast::ForeignItemKind::Fn(ref fn_decl, ref generics) => rewrite_fn_base(
+        let item_str = match self.kind {
+            ast::ForeignItemKind::Fn(_, ref fn_sig, ref generics, _) => rewrite_fn_base(
                 context,
                 shape.indent,
                 self.ident,
-                &FnSig::new(fn_decl, generics, self.vis.clone()),
+                &FnSig::new(&fn_sig.decl, generics, self.vis.clone()),
                 span,
-                false,
-                false,
+                FnBraceStyle::None,
             )
             .map(|(s, _)| format!("{};", s)),
-            ast::ForeignItemKind::Static(ref ty, mutability) => {
+            ast::ForeignItemKind::Static(ref ty, mutability, _) => {
                 // FIXME(#21): we're dropping potential comments in between the
                 // function kw here.
                 let vis = format_visibility(context, &self.vis);
@@ -2949,15 +3081,21 @@ fn rewrite(&self, context: &RewriteContext<'_>, shape: Shape) -> Option<String>
                 // 1 = ;
                 rewrite_assign_rhs(context, prefix, &**ty, shape.sub_width(1)?).map(|s| s + ";")
             }
-            ast::ForeignItemKind::Ty => {
-                let vis = format_visibility(context, &self.vis);
-                Some(format!(
-                    "{}type {};",
-                    vis,
-                    rewrite_ident(context, self.ident)
-                ))
-            }
-            ast::ForeignItemKind::Macro(ref mac) => {
+            ast::ForeignItemKind::TyAlias(
+                _,
+                ref generics,
+                ref generic_bounds,
+                ref type_default,
+            ) => rewrite_type_alias(
+                self.ident,
+                type_default.as_ref(),
+                generics,
+                Some(generic_bounds),
+                &context,
+                shape.indent,
+                &self.vis,
+            ),
+            ast::ForeignItemKind::MacCall(ref mac) => {
                 rewrite_macro(mac, None, context, shape, MacroPosition::Item)
             }
         }?;
@@ -2996,7 +3134,7 @@ fn rewrite_attrs(
 
     let allow_extend = if attrs.len() == 1 {
         let line_len = attrs_str.len() + 1 + item_str.len();
-        !attrs.first().unwrap().is_sugared_doc
+        !attrs.first().unwrap().is_doc_comment()
             && context.config.inline_attribute_width() >= line_len
     } else {
         false
@@ -3047,21 +3185,21 @@ pub(crate) fn rewrite_extern_crate(
 
 /// Returns `true` for `mod foo;`, false for `mod foo { .. }`.
 pub(crate) fn is_mod_decl(item: &ast::Item) -> bool {
-    match item.node {
+    match item.kind {
         ast::ItemKind::Mod(ref m) => m.inner.hi() != item.span.hi(),
         _ => false,
     }
 }
 
 pub(crate) fn is_use_item(item: &ast::Item) -> bool {
-    match item.node {
+    match item.kind {
         ast::ItemKind::Use(_) => true,
         _ => false,
     }
 }
 
 pub(crate) fn is_extern_crate(item: &ast::Item) -> bool {
-    match item.node {
+    match item.kind {
         ast::ItemKind::ExternCrate(..) => true,
         _ => false,
     }