]> git.lizzy.rs Git - rust.git/blobdiff - src/items.rs
Merge pull request #3472 from devinalvaro/add-print-current-config
[rust.git] / src / items.rs
index a2bf023a33eb475c2f37780bdd6914a7341c289a..8cd6010f72f43fa531f04fe4973e58831e790877 100644 (file)
@@ -1,44 +1,34 @@
-// 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.
-
 // Formatting top-level items - functions, structs, enums, traits, impls.
 
 use std::borrow::Cow;
 use std::cmp::{min, Ordering};
 
-use config::lists::*;
 use regex::Regex;
 use rustc_target::spec::abi;
 use syntax::source_map::{self, BytePos, Span};
 use syntax::visit;
 use syntax::{ast, ptr, symbol};
 
-use comment::{
+use crate::comment::{
     combine_strs_with_missing_comments, contains_comment, recover_comment_removed,
     recover_missing_comment_in_span, rewrite_missing_comment, FindUncommented,
 };
-use config::{BraceStyle, Config, Density, IndentStyle, Version};
-use expr::{
+use crate::config::lists::*;
+use crate::config::{BraceStyle, Config, Density, IndentStyle, Version};
+use crate::expr::{
     format_expr, is_empty_block, is_simple_block_stmt, rewrite_assign_rhs, rewrite_assign_rhs_with,
     ExprType, RhsTactics,
 };
-use lists::{definitive_tactic, itemize_list, write_list, ListFormatting, ListItem, Separator};
-use macros::{rewrite_macro, MacroPosition};
-use overflow;
-use rewrite::{Rewrite, RewriteContext};
-use shape::{Indent, Shape};
-use source_map::{LineRangeUtils, SpanUtils};
-use spanned::Spanned;
-use utils::*;
-use vertical::rewrite_with_alignment;
-use visitor::FmtVisitor;
+use crate::lists::{definitive_tactic, itemize_list, write_list, ListFormatting, Separator};
+use crate::macros::{rewrite_macro, MacroPosition};
+use crate::overflow;
+use crate::rewrite::{Rewrite, RewriteContext};
+use crate::shape::{Indent, Shape};
+use crate::source_map::{LineRangeUtils, SpanUtils};
+use crate::spanned::Spanned;
+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,
@@ -52,7 +42,7 @@ fn type_annotation_separator(config: &Config) -> &str {
 // Statements of the form
 // let pat: ty = init;
 impl Rewrite for ast::Local {
-    fn rewrite(&self, context: &RewriteContext, shape: Shape) -> Option<String> {
+    fn rewrite(&self, context: &RewriteContext<'_>, shape: Shape) -> Option<String> {
         debug!(
             "Local::rewrite {:?} {} {:?}",
             self, shape.width, shape.indent
@@ -201,7 +191,7 @@ pub fn from_method_sig(
     ) -> FnSig<'a> {
         FnSig {
             unsafety: method_sig.header.unsafety,
-            is_async: method_sig.header.asyncness,
+            is_async: method_sig.header.asyncness.node,
             constness: method_sig.header.constness.node,
             defaultness: ast::Defaultness::Final,
             abi: method_sig.header.abi,
@@ -212,7 +202,7 @@ pub fn from_method_sig(
     }
 
     pub fn from_fn_kind(
-        fn_kind: &'a visit::FnKind,
+        fn_kind: &'a visit::FnKind<'_>,
         generics: &'a ast::Generics,
         decl: &'a ast::FnDecl,
         defaultness: ast::Defaultness,
@@ -223,7 +213,7 @@ pub fn from_fn_kind(
                 generics,
                 abi: fn_header.abi,
                 constness: fn_header.constness.node,
-                is_async: fn_header.asyncness,
+                is_async: fn_header.asyncness.node,
                 defaultness,
                 unsafety: fn_header.unsafety,
                 visibility: visibility.clone(),
@@ -240,7 +230,7 @@ pub fn from_fn_kind(
         }
     }
 
-    fn to_str(&self, context: &RewriteContext) -> String {
+    fn to_str(&self, context: &RewriteContext<'_>) -> String {
         let mut result = String::with_capacity(128);
         // Vis defaultness constness unsafety abi.
         result.push_str(&*format_visibility(context, &self.visibility));
@@ -258,7 +248,7 @@ fn to_str(&self, context: &RewriteContext) -> String {
 }
 
 impl<'a> FmtVisitor<'a> {
-    fn format_item(&mut self, item: &Item) {
+    fn format_item(&mut self, item: &Item<'_>) {
         self.buffer.push_str(&item.abi);
 
         let snippet = self.snippet(item.span);
@@ -290,7 +280,7 @@ fn format_item(&mut self, item: &Item) {
         self.last_pos = item.span.hi();
     }
 
-    fn format_body_element(&mut self, element: &BodyElement) {
+    fn format_body_element(&mut self, element: &BodyElement<'_>) {
         match *element {
             BodyElement::ForeignItem(item) => self.format_foreign_item(item),
         }
@@ -311,7 +301,7 @@ pub fn rewrite_fn(
         &mut self,
         indent: Indent,
         ident: ast::Ident,
-        fn_sig: &FnSig,
+        fn_sig: &FnSig<'_>,
         span: Span,
         block: &ast::Block,
         inner_attrs: Option<&[ast::Attribute]>,
@@ -333,19 +323,21 @@ pub fn rewrite_fn(
             newline_brace = false;
         }
 
-        // 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));
+        if let rw @ Some(..) = self.single_line_fn(&result, block, inner_attrs) {
+            rw
         } else {
-            result.push(' ');
+            // 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)
         }
-
-        self.single_line_fn(&result, block, inner_attrs)
-            .or_else(|| Some(result))
     }
 
     pub fn rewrite_required_fn(
@@ -390,50 +382,45 @@ fn single_line_fn(
 
         if self.config.empty_item_single_line()
             && is_empty_block(block, None, source_map)
-            && self.block_indent.width() + fn_str.len() + 2 <= self.config.max_width()
+            && 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));
+            return Some(format!("{} {{}}", fn_str));
         }
 
-        if self.config.fn_single_line() && is_simple_block_stmt(block, None, source_map) {
-            let rewrite = {
-                if let Some(stmt) = block.stmts.first() {
-                    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)
-                                .or_else(|| Some(self.snippet(e.span).to_owned()))
-                        }
-                        None => stmt.rewrite(&self.get_context(), self.shape()),
-                    }
+        if !self.config.fn_single_line() || !is_simple_block_stmt(block, None, source_map) {
+            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 {
-                    None
-                }
-            };
+                    ""
+                };
 
-            if let Some(res) = rewrite {
-                let width = self.block_indent.width() + fn_str.len() + res.len() + 4;
-                if !res.contains('\n') && width <= self.config.max_width() {
-                    return Some(format!("{}{{ {} }}", fn_str, res));
-                }
+                format_expr(e, ExprType::Statement, &self.get_context(), self.shape())
+                    .map(|s| s + suffix)?
             }
-        }
+            None => stmt.rewrite(&self.get_context(), self.shape())?,
+        };
 
-        None
+        let width = self.block_indent.width() + fn_str.len() + res.len() + 5;
+        if !res.contains('\n') && width <= self.config.max_width() {
+            Some(format!("{} {{ {} }}", fn_str, res))
+        } else {
+            None
+        }
     }
 
-    pub fn visit_static(&mut self, static_parts: &StaticParts) {
+    pub fn visit_static(&mut self, static_parts: &StaticParts<'_>) {
         let rewrite = rewrite_static(&self.get_context(), static_parts, self.block_indent);
         self.push_rewrite(static_parts.span, rewrite);
     }
 
-    pub fn visit_struct(&mut self, struct_parts: &StructParts) {
+    pub fn visit_struct(&mut self, struct_parts: &StructParts<'_>) {
         let is_tuple = struct_parts.def.is_tuple();
         let rewrite = format_struct(&self.get_context(), struct_parts, self.block_indent, None)
             .map(|s| if is_tuple { s + ";" } else { s });
@@ -624,7 +611,7 @@ fn visit_impl_items(&mut self, items: &[ast::ImplItem]) {
                 self.buffer.clear();
             }
             // type -> existential -> const -> macro -> method
-            use ast::ImplItemKind::*;
+            use crate::ast::ImplItemKind::*;
             fn need_empty_line(a: &ast::ImplItemKind, b: &ast::ImplItemKind) -> bool {
                 match (a, b) {
                     (Type(..), Type(..))
@@ -673,7 +660,7 @@ fn need_empty_line(a: &ast::ImplItemKind, b: &ast::ImplItemKind) -> bool {
 }
 
 pub fn format_impl(
-    context: &RewriteContext,
+    context: &RewriteContext<'_>,
     item: &ast::Item,
     offset: Indent,
     where_span_end: Option<BytePos>,
@@ -716,7 +703,7 @@ pub fn format_impl(
             false,
         )?;
 
-        // If there is no where clause, we may have missing comments between the trait name and
+        // If there is no where-clause, we may have missing comments between the trait name and
         // the opening brace.
         if generics.where_clause.predicates.is_empty() {
             if let Some(hi) = where_span_end {
@@ -738,7 +725,7 @@ pub fn format_impl(
             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
-                // there is only one where clause predicate
+                // there is only one where-clause predicate
                 // recover the suppressed comma in single line where_clause formatting
                 if generics.where_clause.predicates.len() == 1 {
                     result.push_str(",");
@@ -801,7 +788,7 @@ pub fn format_impl(
 }
 
 fn is_impl_single_line(
-    context: &RewriteContext,
+    context: &RewriteContext<'_>,
     items: &[ast::ImplItem],
     result: &str,
     where_clause_str: &str,
@@ -820,7 +807,7 @@ fn is_impl_single_line(
 }
 
 fn format_impl_ref_and_type(
-    context: &RewriteContext,
+    context: &RewriteContext<'_>,
     item: &ast::Item,
     offset: Indent,
 ) -> Option<String> {
@@ -869,7 +856,7 @@ fn format_impl_ref_and_type(
         // ` for`
         let trait_ref_overhead = if trait_ref.is_some() { 4 } else { 0 };
         let curly_brace_overhead = if generics.where_clause.predicates.is_empty() {
-            // If there is no where clause adapt budget for type formatting to take space and curly
+            // If there is no where-clause adapt budget for type formatting to take space and curly
             // brace into account.
             match context.config.brace_style() {
                 BraceStyle::AlwaysNextLine => 0,
@@ -914,7 +901,7 @@ fn format_impl_ref_and_type(
 }
 
 fn rewrite_trait_ref(
-    context: &RewriteContext,
+    context: &RewriteContext<'_>,
     trait_ref: &ast::TraitRef,
     offset: Indent,
     polarity_str: &str,
@@ -950,7 +937,7 @@ pub struct StructParts<'a> {
 }
 
 impl<'a> StructParts<'a> {
-    fn format_header(&self, context: &RewriteContext) -> String {
+    fn format_header(&self, context: &RewriteContext<'_>) -> String {
         format_header(context, self.prefix, self.ident, self.vis)
     }
 
@@ -983,8 +970,8 @@ pub fn from_item(item: &'a ast::Item) -> Self {
 }
 
 fn format_struct(
-    context: &RewriteContext,
-    struct_parts: &StructParts,
+    context: &RewriteContext<'_>,
+    struct_parts: &StructParts<'_>,
     offset: Indent,
     one_line_width: Option<usize>,
 ) -> Option<String> {
@@ -999,7 +986,11 @@ fn format_struct(
     }
 }
 
-pub fn format_trait(context: &RewriteContext, item: &ast::Item, offset: Indent) -> Option<String> {
+pub fn format_trait(
+    context: &RewriteContext<'_>,
+    item: &ast::Item,
+    offset: Indent,
+) -> Option<String> {
     if let ast::ItemKind::Trait(
         is_auto,
         unsafety,
@@ -1044,7 +1035,7 @@ pub fn format_trait(context: &RewriteContext, item: &ast::Item, offset: Indent)
             )?;
         }
 
-        // Rewrite where clause.
+        // Rewrite where-clause.
         if !generics.where_clause.predicates.is_empty() {
             let where_density = if context.config.indent_style() == IndentStyle::Block {
                 Density::Compressed
@@ -1071,8 +1062,8 @@ pub fn format_trait(context: &RewriteContext, item: &ast::Item, offset: Indent)
                 option,
                 false,
             )?;
-            // If the where clause cannot fit on the same line,
-            // put the where clause on a new line
+            // If the where-clause cannot fit on the same line,
+            // put the where-clause on a new line
             if !where_clause_str.contains('\n')
                 && last_line_width(&result) + where_clause_str.len() + offset.width()
                     > context.config.comment_width()
@@ -1158,8 +1149,9 @@ pub fn format_trait(context: &RewriteContext, item: &ast::Item, offset: Indent)
 }
 
 pub fn format_trait_alias(
-    context: &RewriteContext,
+    context: &RewriteContext<'_>,
     ident: ast::Ident,
+    vis: &ast::Visibility,
     generics: &ast::Generics,
     generic_bounds: &ast::GenericBounds,
     shape: Shape,
@@ -1168,12 +1160,17 @@ pub fn format_trait_alias(
     // 6 = "trait ", 2 = " ="
     let g_shape = shape.offset_left(6)?.sub_width(2)?;
     let generics_str = rewrite_generics(context, &alias, generics, g_shape)?;
-    let lhs = format!("trait {} =", generics_str);
+    let vis_str = format_visibility(context, vis);
+    let lhs = format!("{}trait {} =", vis_str, generics_str);
     // 1 = ";"
     rewrite_assign_rhs(context, lhs, generic_bounds, shape.sub_width(1)?).map(|s| s + ";")
 }
 
-fn format_unit_struct(context: &RewriteContext, p: &StructParts, offset: Indent) -> Option<String> {
+fn format_unit_struct(
+    context: &RewriteContext<'_>,
+    p: &StructParts<'_>,
+    offset: Indent,
+) -> Option<String> {
     let header_str = format_header(context, p.prefix, p.ident, p.vis);
     let generics_str = if let Some(generics) = p.generics {
         let hi = if generics.where_clause.predicates.is_empty() {
@@ -1198,8 +1195,8 @@ fn format_unit_struct(context: &RewriteContext, p: &StructParts, offset: Indent)
 }
 
 pub fn format_struct_struct(
-    context: &RewriteContext,
-    struct_parts: &StructParts,
+    context: &RewriteContext<'_>,
+    struct_parts: &StructParts<'_>,
     fields: &[ast::StructField],
     offset: Indent,
     one_line_width: Option<usize>,
@@ -1302,7 +1299,7 @@ fn get_bytepos_after_visibility(vis: &ast::Visibility, default_span: Span) -> By
 // Format tuple or struct without any fields. We need to make sure that the comments
 // inside the delimiters are preserved.
 fn format_empty_struct_or_tuple(
-    context: &RewriteContext,
+    context: &RewriteContext<'_>,
     span: Span,
     offset: Indent,
     result: &mut String,
@@ -1335,8 +1332,8 @@ fn format_empty_struct_or_tuple(
 }
 
 fn format_tuple_struct(
-    context: &RewriteContext,
-    struct_parts: &StructParts,
+    context: &RewriteContext<'_>,
+    struct_parts: &StructParts<'_>,
     fields: &[ast::StructField],
     offset: Indent,
 ) -> Option<String> {
@@ -1417,8 +1414,8 @@ fn format_tuple_struct(
             || offset.block_indent + result.len() + where_clause_str.len() + 1
                 > context.config.max_width())
     {
-        // We need to put the where clause on a new line, but we didn't
-        // know that earlier, so the where clause will not be indented properly.
+        // We need to put the where-clause on a new line, but we didn't
+        // know that earlier, so the where-clause will not be indented properly.
         result.push('\n');
         result.push_str(
             &(offset.block_only() + (context.config.tab_spaces() - 1)).to_string(context.config),
@@ -1430,7 +1427,7 @@ fn format_tuple_struct(
 }
 
 fn rewrite_type_prefix(
-    context: &RewriteContext,
+    context: &RewriteContext<'_>,
     indent: Indent,
     prefix: &str,
     ident: ast::Ident,
@@ -1471,7 +1468,7 @@ fn rewrite_type_prefix(
 }
 
 fn rewrite_type_item<R: Rewrite>(
-    context: &RewriteContext,
+    context: &RewriteContext<'_>,
     indent: Indent,
     prefix: &str,
     suffix: &str,
@@ -1502,7 +1499,7 @@ fn rewrite_type_item<R: Rewrite>(
 }
 
 pub fn rewrite_type_alias(
-    context: &RewriteContext,
+    context: &RewriteContext<'_>,
     indent: Indent,
     ident: ast::Ident,
     ty: &ast::Ty,
@@ -1513,7 +1510,7 @@ pub fn rewrite_type_alias(
 }
 
 pub fn rewrite_existential_type(
-    context: &RewriteContext,
+    context: &RewriteContext<'_>,
     indent: Indent,
     ident: ast::Ident,
     generic_bounds: &ast::GenericBounds,
@@ -1540,7 +1537,7 @@ fn type_annotation_spacing(config: &Config) -> (&str, &str) {
 }
 
 pub fn rewrite_struct_field_prefix(
-    context: &RewriteContext,
+    context: &RewriteContext<'_>,
     field: &ast::StructField,
 ) -> Option<String> {
     let vis = format_visibility(context, &field.vis);
@@ -1557,13 +1554,13 @@ pub fn rewrite_struct_field_prefix(
 }
 
 impl Rewrite for ast::StructField {
-    fn rewrite(&self, context: &RewriteContext, shape: Shape) -> Option<String> {
+    fn rewrite(&self, context: &RewriteContext<'_>, shape: Shape) -> Option<String> {
         rewrite_struct_field(context, self, shape, 0)
     }
 }
 
 pub fn rewrite_struct_field(
-    context: &RewriteContext,
+    context: &RewriteContext<'_>,
     field: &ast::StructField,
     shape: Shape,
     lhs_max_width: usize,
@@ -1694,8 +1691,8 @@ pub fn from_impl_item(ii: &'a ast::ImplItem) -> Self {
 }
 
 fn rewrite_static(
-    context: &RewriteContext,
-    static_parts: &StaticParts,
+    context: &RewriteContext<'_>,
+    static_parts: &StaticParts<'_>,
     offset: Indent,
 ) -> Option<String> {
     let colon = colon_spaces(
@@ -1753,7 +1750,7 @@ pub fn rewrite_associated_type(
     ty_opt: Option<&ptr::P<ast::Ty>>,
     generics: &ast::Generics,
     generic_bounds_opt: Option<&ast::GenericBounds>,
-    context: &RewriteContext,
+    context: &RewriteContext<'_>,
     indent: Indent,
 ) -> Option<String> {
     let ident_str = rewrite_ident(context, ident);
@@ -1785,7 +1782,7 @@ pub fn rewrite_associated_type(
 }
 
 pub fn rewrite_existential_impl_type(
-    context: &RewriteContext,
+    context: &RewriteContext<'_>,
     ident: ast::Ident,
     generics: &ast::Generics,
     generic_bounds: &ast::GenericBounds,
@@ -1800,7 +1797,7 @@ pub fn rewrite_associated_impl_type(
     defaultness: ast::Defaultness,
     ty_opt: Option<&ptr::P<ast::Ty>>,
     generics: &ast::Generics,
-    context: &RewriteContext,
+    context: &RewriteContext<'_>,
     indent: Indent,
 ) -> Option<String> {
     let result = rewrite_associated_type(ident, ty_opt, generics, None, context, indent)?;
@@ -1812,7 +1809,7 @@ pub fn rewrite_associated_impl_type(
 }
 
 impl Rewrite for ast::FunctionRetTy {
-    fn rewrite(&self, context: &RewriteContext, shape: Shape) -> Option<String> {
+    fn rewrite(&self, context: &RewriteContext<'_>, shape: Shape) -> Option<String> {
         match *self {
             ast::FunctionRetTy::Default(_) => Some(String::new()),
             ast::FunctionRetTy::Ty(ref ty) => {
@@ -1832,8 +1829,10 @@ fn is_empty_infer(ty: &ast::Ty, pat_span: Span) -> bool {
 }
 
 impl Rewrite for ast::Arg {
-    fn rewrite(&self, context: &RewriteContext, shape: Shape) -> Option<String> {
-        if is_named_arg(self) {
+    fn rewrite(&self, context: &RewriteContext<'_>, shape: Shape) -> Option<String> {
+        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))?;
@@ -1862,9 +1861,8 @@ fn rewrite(&self, context: &RewriteContext, shape: Shape) -> Option<String> {
 }
 
 fn rewrite_explicit_self(
+    context: &RewriteContext<'_>,
     explicit_self: &ast::ExplicitSelf,
-    args: &[ast::Arg],
-    context: &RewriteContext,
 ) -> Option<String> {
     match explicit_self.node {
         ast::SelfKind::Region(lt, m) => {
@@ -1880,10 +1878,7 @@ fn rewrite_explicit_self(
                 None => Some(format!("&{}self", mut_str)),
             }
         }
-        ast::SelfKind::Explicit(ref ty, _) => {
-            assert!(!args.is_empty(), "&[ast::Arg] shouldn't be empty.");
-
-            let mutability = explicit_self_mutability(&args[0]);
+        ast::SelfKind::Explicit(ref ty, mutability) => {
             let type_str = ty.rewrite(
                 context,
                 Shape::legacy(context.config.max_width(), Indent::empty()),
@@ -1895,23 +1890,7 @@ fn rewrite_explicit_self(
                 type_str
             ))
         }
-        ast::SelfKind::Value(_) => {
-            assert!(!args.is_empty(), "&[ast::Arg] shouldn't be empty.");
-
-            let mutability = explicit_self_mutability(&args[0]);
-
-            Some(format!("{}self", format_mutability(mutability)))
-        }
-    }
-}
-
-// Hacky solution caused by absence of `Mutability` in `SelfValue` and
-// `SelfExplicit` variants of `ast::ExplicitSelf_`.
-fn explicit_self_mutability(arg: &ast::Arg) -> ast::Mutability {
-    if let ast::PatKind::Ident(ast::BindingMode::ByValue(mutability), _, _) = arg.pat.node {
-        mutability
-    } else {
-        unreachable!()
+        ast::SelfKind::Value(mutability) => Some(format!("{}self", format_mutability(mutability))),
     }
 }
 
@@ -1923,7 +1902,7 @@ pub fn span_lo_for_arg(arg: &ast::Arg) -> BytePos {
     }
 }
 
-pub fn span_hi_for_arg(context: &RewriteContext, arg: &ast::Arg) -> BytePos {
+pub 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(),
@@ -1941,10 +1920,10 @@ pub fn is_named_arg(arg: &ast::Arg) -> bool {
 
 // Return type is (result, force_new_line_for_brace)
 fn rewrite_fn_base(
-    context: &RewriteContext,
+    context: &RewriteContext<'_>,
     indent: Indent,
     ident: ast::Ident,
-    fn_sig: &FnSig,
+    fn_sig: &FnSig<'_>,
     span: Span,
     newline_brace: bool,
     has_body: bool,
@@ -2048,14 +2027,12 @@ fn rewrite_fn_base(
     let arg_str = rewrite_args(
         context,
         &fd.inputs,
-        fd.get_self().as_ref(),
         one_line_budget,
         multi_line_budget,
         indent,
         arg_indent,
         args_span,
-        fd.variadic,
-        generics_str.contains('\n'),
+        fd.c_variadic,
     )?;
 
     let put_args_in_block = match context.config.indent_style() {
@@ -2113,7 +2090,7 @@ fn rewrite_fn_base(
                 // the closing parenthesis of the argument 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
+                // If there is no where-clause, take into account the space after the return type
                 // and the brace.
                 if where_clause.predicates.is_empty() {
                     sig_length += 2;
@@ -2130,7 +2107,7 @@ fn rewrite_fn_base(
             } 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.
+                // the where-clause indent.
                 arg_indent
             };
 
@@ -2206,7 +2183,7 @@ fn rewrite_fn_base(
         option,
         is_args_multi_lined,
     )?;
-    // If there are neither where clause nor return type, we may be missing comments between
+    // If there are neither where-clause nor return type, we may be missing comments between
     // args and `{`.
     if where_clause_str.is_empty() {
         if let ast::FunctionRetTy::Default(ret_span) = fd.output {
@@ -2236,7 +2213,7 @@ fn rewrite_fn_base(
 struct WhereClauseOption {
     suppress_comma: bool, // Force no trailing comma
     snuggle: bool,        // Do not insert newline before `where`
-    compress_where: bool, // Try single line where clause instead of vertical layout
+    compress_where: bool, // Try single line where-clause instead of vertical layout
 }
 
 impl WhereClauseOption {
@@ -2270,132 +2247,48 @@ pub fn snuggle(&mut self) {
 }
 
 fn rewrite_args(
-    context: &RewriteContext,
+    context: &RewriteContext<'_>,
     args: &[ast::Arg],
-    explicit_self: Option<&ast::ExplicitSelf>,
     one_line_budget: usize,
     multi_line_budget: usize,
     indent: Indent,
     arg_indent: Indent,
     span: Span,
     variadic: bool,
-    generics_str_contains_newline: bool,
 ) -> Option<String> {
-    let mut arg_item_strs = args
-        .iter()
-        .map(|arg| {
-            arg.rewrite(context, Shape::legacy(multi_line_budget, arg_indent))
-                .unwrap_or_else(|| context.snippet(arg.span()).to_owned())
-        })
-        .collect::<Vec<_>>();
-
-    // Account for sugary self.
-    // FIXME: the comment for the self argument is dropped. This is blocked
-    // on rust issue #27522.
-    let min_args = explicit_self
-        .and_then(|explicit_self| rewrite_explicit_self(explicit_self, args, context))
-        .map_or(1, |self_str| {
-            arg_item_strs[0] = self_str;
-            2
-        });
-
-    // Comments between args.
-    let mut arg_items = Vec::new();
-    if min_args == 2 {
-        arg_items.push(ListItem::from_str(""));
-    }
-
-    // FIXME(#21): if there are no args, there might still be a comment, but
-    // without spans for the comment or parens, there is no chance of
-    // getting it right. You also don't get to put a comment on self, unless
-    // it is explicit.
-    if args.len() >= min_args || variadic {
-        let comment_span_start = if min_args == 2 {
-            let second_arg_start = if arg_has_pattern(&args[1]) {
-                args[1].pat.span.lo()
-            } else {
-                args[1].ty.span.lo()
-            };
-            let reduced_span = mk_sp(span.lo(), second_arg_start);
-
-            context.snippet_provider.span_after_last(reduced_span, ",")
-        } else {
-            span.lo()
-        };
-
-        enum ArgumentKind<'a> {
-            Regular(&'a ast::Arg),
-            Variadic(BytePos),
-        }
-
-        let variadic_arg = if variadic {
-            let variadic_span = mk_sp(args.last().unwrap().ty.span.hi(), span.hi());
-            let variadic_start =
-                context.snippet_provider.span_after(variadic_span, "...") - BytePos(3);
-            Some(ArgumentKind::Variadic(variadic_start))
-        } else {
-            None
-        };
-
-        let more_items = itemize_list(
-            context.snippet_provider,
-            args[min_args - 1..]
-                .iter()
-                .map(ArgumentKind::Regular)
-                .chain(variadic_arg),
-            ")",
-            ",",
-            |arg| match *arg {
-                ArgumentKind::Regular(arg) => span_lo_for_arg(arg),
-                ArgumentKind::Variadic(start) => start,
-            },
-            |arg| match *arg {
-                ArgumentKind::Regular(arg) => arg.ty.span.hi(),
-                ArgumentKind::Variadic(start) => start + BytePos(3),
-            },
-            |arg| match *arg {
-                ArgumentKind::Regular(..) => None,
-                ArgumentKind::Variadic(..) => Some("...".to_owned()),
-            },
-            comment_span_start,
-            span.hi(),
-            false,
-        );
-
-        arg_items.extend(more_items);
-    }
-
-    let fits_in_one_line = !generics_str_contains_newline
-        && (arg_items.is_empty()
-            || arg_items.len() == 1 && arg_item_strs[0].len() <= one_line_budget);
-
-    for (item, arg) in arg_items.iter_mut().zip(arg_item_strs) {
-        item.item = Some(arg);
+    if args.len() == 0 {
+        let comment = context
+            .snippet(mk_sp(
+                span.lo(),
+                // to remove ')'
+                span.hi() - BytePos(1),
+            ))
+            .trim();
+        return Some(comment.to_owned());
     }
-
-    let last_line_ends_with_comment = arg_items
-        .iter()
-        .last()
-        .and_then(|item| item.post_comment.as_ref())
-        .map_or(false, |s| s.trim().starts_with("//"));
-
-    let (indent, trailing_comma) = match context.config.indent_style() {
-        IndentStyle::Block if fits_in_one_line => {
-            (indent.block_indent(context.config), SeparatorTactic::Never)
-        }
-        IndentStyle::Block => (
-            indent.block_indent(context.config),
-            context.config.trailing_comma(),
-        ),
-        IndentStyle::Visual if last_line_ends_with_comment => {
-            (arg_indent, context.config.trailing_comma())
-        }
-        IndentStyle::Visual => (arg_indent, SeparatorTactic::Never),
-    };
+    let arg_items: Vec<_> = itemize_list(
+        context.snippet_provider,
+        args.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()))
+        },
+        span.lo(),
+        span.hi(),
+        false,
+    )
+    .collect();
 
     let tactic = definitive_tactic(
         &arg_items,
-        context.config.fn_args_density().to_list_tactic(),
+        context
+            .config
+            .fn_args_density()
+            .to_list_tactic(arg_items.len()),
         Separator::Comma,
         one_line_budget,
     );
@@ -2403,13 +2296,17 @@ enum ArgumentKind<'a> {
         DefinitiveListTactic::Horizontal => one_line_budget,
         _ => multi_line_budget,
     };
-
-    debug!("rewrite_args: budget: {}, tactic: {:?}", budget, tactic);
-
+    let indent = match context.config.indent_style() {
+        IndentStyle::Block => indent.block_indent(context.config),
+        IndentStyle::Visual => arg_indent,
+    };
     let trailing_separator = if variadic {
         SeparatorTactic::Never
     } else {
-        trailing_comma
+        match context.config.indent_style() {
+            IndentStyle::Block => context.config.trailing_comma(),
+            IndentStyle::Visual => SeparatorTactic::Never,
+        }
     };
     let fmt = ListFormatting::new(Shape::legacy(budget, indent), context.config)
         .tactic(tactic)
@@ -2419,16 +2316,8 @@ enum ArgumentKind<'a> {
     write_list(&arg_items, &fmt)
 }
 
-fn arg_has_pattern(arg: &ast::Arg) -> bool {
-    if let ast::PatKind::Ident(_, ident, _) = arg.pat.node {
-        ident != symbol::keywords::Invalid.ident()
-    } else {
-        true
-    }
-}
-
 fn compute_budgets_for_args(
-    context: &RewriteContext,
+    context: &RewriteContext<'_>,
     result: &str,
     indent: Indent,
     ret_str_len: usize,
@@ -2501,13 +2390,13 @@ fn newline_for_brace(config: &Config, where_clause: &ast::WhereClause) -> bool {
 }
 
 fn rewrite_generics(
-    context: &RewriteContext,
+    context: &RewriteContext<'_>,
     ident: &str,
     generics: &ast::Generics,
     shape: Shape,
 ) -> Option<String> {
-    // FIXME: convert bounds to where clauses where they get too big or if
-    // there is a where clause at all.
+    // FIXME: convert bounds to where-clauses where they get too big or if
+    // there is a where-clause at all.
 
     if generics.params.is_empty() {
         return Some(ident.to_owned());
@@ -2532,7 +2421,7 @@ pub fn generics_shape_from_config(config: &Config, shape: Shape, offset: usize)
 }
 
 fn rewrite_where_clause_rfc_style(
-    context: &RewriteContext,
+    context: &RewriteContext<'_>,
     where_clause: &ast::WhereClause,
     shape: Shape,
     terminator: &str,
@@ -2584,7 +2473,7 @@ fn rewrite_where_clause_rfc_style(
     };
 
     // shape should be vertical only and only if we have `where_single_line` option enabled
-    // and the number of items of the where clause is equal to 1
+    // and the number of items of the where-clause is equal to 1
     let shape_tactic = if where_single_line {
         DefinitiveListTactic::Horizontal
     } else {
@@ -2632,7 +2521,7 @@ fn rewrite_where_clause_rfc_style(
 }
 
 fn rewrite_where_clause(
-    context: &RewriteContext,
+    context: &RewriteContext<'_>,
     where_clause: &ast::WhereClause,
     brace_style: BraceStyle,
     shape: Shape,
@@ -2694,7 +2583,7 @@ fn rewrite_where_clause(
     let tactic = definitive_tactic(&item_vec, ListTactic::Vertical, Separator::Comma, budget);
 
     let mut comma_tactic = context.config.trailing_comma();
-    // Kind of a hack because we don't usually have trailing commas in where clauses.
+    // Kind of a hack because we don't usually have trailing commas in where-clauses.
     if comma_tactic == SeparatorTactic::Vertical || where_clause_option.suppress_comma {
         comma_tactic = SeparatorTactic::Never;
     }
@@ -2744,7 +2633,7 @@ fn missing_span_before_after_where(
 }
 
 fn rewrite_comments_before_after_where(
-    context: &RewriteContext,
+    context: &RewriteContext<'_>,
     span_before_where: Span,
     span_after_where: Span,
     shape: Shape,
@@ -2759,7 +2648,7 @@ fn rewrite_comments_before_after_where(
 }
 
 fn format_header(
-    context: &RewriteContext,
+    context: &RewriteContext<'_>,
     item_name: &str,
     ident: ast::Ident,
     vis: &ast::Visibility,
@@ -2780,7 +2669,7 @@ enum BracePos {
 }
 
 fn format_generics(
-    context: &RewriteContext,
+    context: &RewriteContext<'_>,
     generics: &ast::Generics,
     brace_style: BraceStyle,
     brace_pos: BracePos,
@@ -2854,7 +2743,7 @@ fn format_generics(
 }
 
 impl Rewrite for ast::ForeignItem {
-    fn rewrite(&self, context: &RewriteContext, shape: Shape) -> Option<String> {
+    fn rewrite(&self, context: &RewriteContext<'_>, shape: Shape) -> Option<String> {
         let attrs_str = self.attrs.rewrite(context, shape)?;
         // Drop semicolon or it will be interpreted as comment.
         // FIXME: this may be a faulty span from libsyntax.
@@ -2915,7 +2804,7 @@ fn rewrite(&self, context: &RewriteContext, shape: Shape) -> Option<String> {
 }
 
 /// Rewrite an inline mod.
-pub fn rewrite_mod(context: &RewriteContext, item: &ast::Item) -> String {
+pub fn rewrite_mod(context: &RewriteContext<'_>, item: &ast::Item) -> String {
     let mut result = String::with_capacity(32);
     result.push_str(&*format_visibility(context, &item.vis));
     result.push_str("mod ");
@@ -2925,7 +2814,7 @@ pub fn rewrite_mod(context: &RewriteContext, item: &ast::Item) -> String {
 }
 
 /// Rewrite `extern crate foo;` WITHOUT attributes.
-pub fn rewrite_extern_crate(context: &RewriteContext, item: &ast::Item) -> Option<String> {
+pub fn rewrite_extern_crate(context: &RewriteContext<'_>, item: &ast::Item) -> Option<String> {
     assert!(is_extern_crate(item));
     let new_str = context.snippet(item.span);
     Some(if contains_comment(new_str) {
@@ -2936,7 +2825,7 @@ pub fn rewrite_extern_crate(context: &RewriteContext, item: &ast::Item) -> Optio
     })
 }
 
-/// Returns true for `mod foo;`, false for `mod foo { .. }`.
+/// Returns `true` for `mod foo;`, false for `mod foo { .. }`.
 pub fn is_mod_decl(item: &ast::Item) -> bool {
     match item.node {
         ast::ItemKind::Mod(ref m) => m.inner.hi() != item.span.hi(),