]> 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 04bef1cef5fd005e3385b55e638b64b593c24a3d..a11a02be2aeadff91c681691bb0df8528de1db7b 100644 (file)
@@ -4,9 +4,9 @@
 use std::cmp::{max, min, Ordering};
 
 use regex::Regex;
-use rustc_span::{source_map, symbol, BytePos, Span, DUMMY_SP};
-use syntax::visit;
-use syntax::{ast, ptr};
+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::{
 use crate::vertical::rewrite_with_alignment;
 use crate::visitor::FmtVisitor;
 
-const DEFAULT_VISIBILITY: ast::Visibility = source_map::Spanned {
-    node: ast::VisibilityKind::Inherited,
+const DEFAULT_VISIBILITY: ast::Visibility = ast::Visibility {
+    kind: ast::VisibilityKind::Inherited,
     span: DUMMY_SP,
+    tokens: None,
 };
 
 fn type_annotation_separator(config: &Config) -> &str {
@@ -125,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>>,
@@ -135,7 +136,7 @@ struct Item<'a> {
 impl<'a> Item<'a> {
     fn from_foreign_mod(fm: &'a ast::ForeignMod, span: Span, config: &Config) -> Item<'a> {
         Item {
-            keyword: "",
+            unsafety: fm.unsafety,
             abi: format_extern(
                 ast::Extern::from_abi(fm.abi),
                 config.force_explicit_abi(),
@@ -254,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);
@@ -266,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("}");
@@ -311,7 +310,7 @@ fn format_foreign_item(&mut self, item: &ast::ForeignItem) {
     pub(crate) fn rewrite_fn_before_block(
         &mut self,
         indent: Indent,
-        ident: ast::Ident,
+        ident: symbol::Ident,
         fn_sig: &FnSig<'_>,
         span: Span,
     ) -> Option<(String, FnBraceStyle)> {
@@ -335,7 +334,7 @@ pub(crate) fn rewrite_fn_before_block(
     pub(crate) fn rewrite_required_fn(
         &mut self,
         indent: Indent,
-        ident: ast::Ident,
+        ident: symbol::Ident,
         sig: &ast::FnSig,
         generics: &ast::Generics,
         span: Span,
@@ -411,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,
@@ -594,36 +593,29 @@ fn visit_impl_items(&mut self, items: &[ptr::P<ast::AssocItem>]) {
                 self.buffer.clear();
             }
 
-            fn is_type(ty: &Option<syntax::ptr::P<ast::Ty>>) -> bool {
-                match ty {
-                    None => true,
-                    Some(lty) => match lty.kind.opaque_top_hack() {
-                        None => true,
-                        Some(_) => false,
-                    },
+            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<syntax::ptr::P<ast::Ty>>) -> bool {
-                match ty {
-                    None => false,
-                    Some(lty) => match lty.kind.opaque_top_hack() {
-                        None => false,
-                        Some(_) => true,
-                    },
-                }
+            fn is_opaque(ty: &Option<rustc_ast::ptr::P<ast::Ty>>) -> bool {
+                !is_type(ty)
             }
 
             fn both_type(
-                a: &Option<syntax::ptr::P<ast::Ty>>,
-                b: &Option<syntax::ptr::P<ast::Ty>>,
+                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<syntax::ptr::P<ast::Ty>>,
-                b: &Option<syntax::ptr::P<ast::Ty>>,
+                a: &Option<rustc_ast::ptr::P<ast::Ty>>,
+                b: &Option<rustc_ast::ptr::P<ast::Ty>>,
             ) -> bool {
                 is_opaque(a) && is_opaque(b)
             }
@@ -967,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>,
@@ -1234,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,
@@ -1374,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(),
     }
@@ -1509,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)?;
@@ -1531,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,
@@ -1546,69 +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(
-    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_opaque_type(
     context: &RewriteContext<'_>,
     indent: Indent,
-    ident: ast::Ident,
+    ident: symbol::Ident,
     generic_bounds: &ast::GenericBounds,
     generics: &ast::Generics,
     vis: &ast::Visibility,
 ) -> Option<String> {
     let opaque_type_bounds = OpaqueTypeBounds { generic_bounds };
-    rewrite_type_item(
+    rewrite_type(
         context,
         indent,
-        "type",
-        " =",
         ident,
-        &opaque_type_bounds,
-        generics,
         vis,
+        generics,
+        Some(generic_bounds),
+        Some(&opaque_type_bounds),
     )
 }
 
@@ -1709,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>>,
@@ -1829,40 +1807,24 @@ 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);
-
-    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()
-    };
-
-    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))
-    }
+    rewrite_type(
+        context,
+        indent,
+        ident,
+        vis,
+        generics,
+        generic_bounds_opt,
+        ty_opt,
+    )
 }
 
 struct OpaqueType<'a> {
@@ -1880,7 +1842,7 @@ fn rewrite(&self, context: &RewriteContext<'_>, shape: Shape) -> Option<String>
 
 pub(crate) fn rewrite_opaque_impl_type(
     context: &RewriteContext<'_>,
-    ident: ast::Ident,
+    ident: symbol::Ident,
     generics: &ast::Generics,
     generic_bounds: &ast::GenericBounds,
     indent: Indent,
@@ -1904,14 +1866,15 @@ pub(crate) fn rewrite_opaque_impl_type(
 }
 
 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)),
@@ -2141,7 +2104,7 @@ pub(crate) enum FnBraceStyle {
 fn rewrite_fn_base(
     context: &RewriteContext<'_>,
     indent: Indent,
-    ident: ast::Ident,
+    ident: symbol::Ident,
     fn_sig: &FnSig<'_>,
     span: Span,
     fn_brace_style: FnBraceStyle,
@@ -2455,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_params_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))
 }
 
@@ -2969,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!(
@@ -3117,14 +3081,20 @@ 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::TyAlias(..) => {
-                let vis = format_visibility(context, &self.vis);
-                Some(format!(
-                    "{}type {};",
-                    vis,
-                    rewrite_ident(context, self.ident)
-                ))
-            }
+            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)
             }