]> git.lizzy.rs Git - rust.git/blobdiff - src/items.rs
Respect empty_item_single_line config option when formatting empty impls
[rust.git] / src / items.rs
index 729545139088506e6b3ee808654b4bc2326c068e..38311abcba0ce68e6cf9b487842a3eb784bab38f 100644 (file)
@@ -142,7 +142,8 @@ fn from_foreign_mod(fm: &'a ast::ForeignMod, span: Span, config: &Config) -> Ite
             keyword: "",
             abi: format_abi(fm.abi, config.force_explicit_abi(), true),
             vis: None,
-            body: fm.items
+            body: fm
+                .items
                 .iter()
                 .map(|i| BodyElement::ForeignItem(i))
                 .collect(),
@@ -571,7 +572,7 @@ fn format_variant(&self, field: &ast::Variant, one_line_width: usize) -> Option<
             ast::VariantData::Unit(..) => {
                 if let Some(ref expr) = field.node.disr_expr {
                     let lhs = format!("{} =", field.node.ident.name);
-                    rewrite_assign_rhs(&context, lhs, &**expr, shape)?
+                    rewrite_assign_rhs(&context, lhs, &*expr.value, shape)?
                 } else {
                     field.node.ident.name.to_string()
                 }
@@ -648,8 +649,21 @@ pub fn format_impl(
         } else {
             context.budget(last_line_width(&result))
         };
-        let option = WhereClauseOption::snuggled(&ref_and_type);
-        let where_clause_str = rewrite_where_clause(
+
+        let mut option = WhereClauseOption::snuggled(&ref_and_type);
+        let snippet = context.snippet(item.span);
+        let open_pos = snippet.find_uncommented("{")? + 1;
+        if !contains_comment(&snippet[open_pos..])
+            && items.is_empty()
+            && generics.where_clause.predicates.len() == 1
+            && !result.contains('\n')
+        {
+            option.suppress_comma();
+            option.snuggle();
+            option.compress_where();
+        }
+
+        let mut where_clause_str = rewrite_where_clause(
             context,
             &generics.where_clause,
             context.config.brace_style(),
@@ -683,6 +697,12 @@ pub fn format_impl(
         if is_impl_single_line(context, items, &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
+                // 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(",");
+                }
                 result.push_str(&format!("{}{{{}}}", &sep, &sep));
             } else {
                 result.push_str(" {}");
@@ -690,11 +710,6 @@ pub fn format_impl(
             return Some(result);
         }
 
-        if !where_clause_str.is_empty() && !where_clause_str.contains('\n') {
-            let width = offset.block_indent + context.config.tab_spaces() - 1;
-            let where_indent = Indent::new(0, width);
-            result.push_str(&where_indent.to_string_with_newline(context.config));
-        }
         result.push_str(&where_clause_str);
 
         let need_newline = last_line_contains_single_line_comment(&result) || result.contains('\n');
@@ -735,7 +750,7 @@ pub fn format_impl(
             result.push_str(&outer_indent_str);
         }
 
-        if result.ends_with('{') {
+        if result.ends_with('{') && !context.config.empty_item_single_line() {
             result.push_str(&sep);
         }
         result.push('}');
@@ -962,9 +977,9 @@ pub fn format_trait(context: &RewriteContext, item: &ast::Item, offset: Indent)
         let mut result = String::with_capacity(128);
         let header = format!(
             "{}{}{}trait ",
-            format_auto(is_auto),
             format_visibility(&item.vis),
             format_unsafety(unsafety),
+            format_auto(is_auto),
         );
         result.push_str(&header);
 
@@ -1379,9 +1394,9 @@ fn format_tuple_struct(
         // 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));
+        result.push_str(
+            &(offset.block_only() + (context.config.tab_spaces() - 1)).to_string(context.config),
+        );
     }
     result.push_str(&where_clause_str);
 
@@ -1502,7 +1517,7 @@ pub fn rewrite_struct_field(
         attrs_extendable,
     )?;
     let overhead = last_line_width(&attr_prefix);
-    let lhs_offset = lhs_max_width.checked_sub(overhead).unwrap_or(0);
+    let lhs_offset = lhs_max_width.saturating_sub(overhead);
     for _ in 0..lhs_offset {
         spacing.push(' ');
     }
@@ -1725,7 +1740,8 @@ fn is_empty_infer(context: &RewriteContext, ty: &ast::Ty) -> bool {
 impl Rewrite for ast::Arg {
     fn rewrite(&self, context: &RewriteContext, shape: Shape) -> Option<String> {
         if is_named_arg(self) {
-            let mut result = self.pat
+            let mut result = self
+                .pat
                 .rewrite(context, Shape::legacy(shape.width, shape.indent))?;
 
             if !is_empty_infer(context, &*self.ty) {
@@ -1738,7 +1754,8 @@ fn rewrite(&self, context: &RewriteContext, shape: Shape) -> Option<String> {
                 }
                 let overhead = last_line_width(&result);
                 let max_width = shape.width.checked_sub(overhead)?;
-                let ty_str = self.ty
+                let ty_str = self
+                    .ty
                     .rewrite(context, Shape::legacy(max_width, shape.indent))?;
                 result.push_str(&ty_str);
             }
@@ -1876,7 +1893,8 @@ fn rewrite_fn_base(
 
     // Note that the width and indent don't really matter, we'll re-layout the
     // return type later anyway.
-    let ret_str = fd.output
+    let ret_str = fd
+        .output
         .rewrite(context, Shape::indented(indent, context.config))?;
 
     let multi_line_ret_str = ret_str.contains('\n');
@@ -1911,12 +1929,6 @@ fn rewrite_fn_base(
     } else {
         result.push('(');
     }
-    if context.config.spaces_within_parens_and_brackets()
-        && !fd.inputs.is_empty()
-        && result.ends_with('(')
-    {
-        result.push(' ')
-    }
 
     // Skip `pub(crate)`.
     let lo_after_visibility = get_bytepos_after_visibility(&fn_sig.visibility, span);
@@ -1974,9 +1986,6 @@ fn rewrite_fn_base(
         if fd.inputs.is_empty() && used_width + 1 > context.config.max_width() {
             result.push('\n');
         }
-        if context.config.spaces_within_parens_and_brackets() && !fd.inputs.is_empty() {
-            result.push(' ')
-        }
         // If the last line of args contains comment, we cannot put the closing paren
         // on the same line.
         if arg_str
@@ -2034,7 +2043,8 @@ fn rewrite_fn_base(
         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
+            let ret_str = fd
+                .output
                 .rewrite(context, Shape::indented(ret_indent, context.config))?;
             result.push_str(&ret_str);
         } else {
@@ -2133,10 +2143,22 @@ pub fn new(suppress_comma: bool, snuggle: bool) -> WhereClauseOption {
     pub fn snuggled(current: &str) -> WhereClauseOption {
         WhereClauseOption {
             suppress_comma: false,
-            snuggle: trimmed_last_line_width(current) == 1,
+            snuggle: last_line_width(current) == 1,
             compress_where: false,
         }
     }
+
+    pub fn suppress_comma(&mut self) {
+        self.suppress_comma = true
+    }
+
+    pub fn compress_where(&mut self) {
+        self.compress_where = true
+    }
+
+    pub fn snuggle(&mut self) {
+        self.snuggle = true
+    }
 }
 
 fn rewrite_args(
@@ -2151,7 +2173,8 @@ fn rewrite_args(
     variadic: bool,
     generics_str_contains_newline: bool,
 ) -> Option<String> {
-    let mut arg_item_strs = args.iter()
+    let mut arg_item_strs = args
+        .iter()
         .map(|arg| arg.rewrite(context, Shape::legacy(multi_line_budget, arg_indent)))
         .collect::<Option<Vec<_>>>()?;