]> git.lizzy.rs Git - rust.git/blobdiff - src/types.rs
Merge pull request #3035 from topecongiro/issue-3006
[rust.git] / src / types.rs
index 20c6cebeefdbb21b874884608ddc804d8c02ca9e..07794030ba8deab90d5071fc1011e4c0b20c6a75 100644 (file)
 
 use config::lists::*;
 use syntax::ast::{self, FunctionRetTy, Mutability};
-use syntax::codemap::{self, BytePos, Span};
+use syntax::source_map::{self, BytePos, Span};
 use syntax::symbol::keywords;
 
-use codemap::SpanUtils;
 use config::{IndentStyle, TypeDensity};
-use expr::{
-    rewrite_assign_rhs, rewrite_pair, rewrite_tuple, rewrite_unary_prefix, PairParts, ToExpr,
-};
+use expr::{rewrite_assign_rhs, rewrite_tuple, rewrite_unary_prefix, ToExpr};
 use lists::{definitive_tactic, itemize_list, write_list, ListFormatting, Separator};
 use macros::{rewrite_macro, MacroPosition};
 use overflow;
+use pairs::{rewrite_pair, PairParts};
 use rewrite::{Rewrite, RewriteContext};
 use shape::Shape;
+use source_map::SpanUtils;
 use spanned::Spanned;
 use utils::{
-    colon_spaces, extra_offset, first_line_width, format_abi, format_mutability, last_line_width,
-    mk_sp,
+    colon_spaces, extra_offset, first_line_width, format_abi, format_mutability,
+    last_line_extendable, last_line_width, mk_sp, rewrite_ident,
 };
 
 #[derive(Copy, Clone, Debug, Eq, PartialEq)]
@@ -187,8 +186,10 @@ fn rewrite(&self, context: &RewriteContext, shape: Shape) -> Option<String> {
             SegmentParam::Type(ty) => ty.rewrite(context, shape),
             SegmentParam::Binding(binding) => {
                 let mut result = match context.config.type_punctuation_density() {
-                    TypeDensity::Wide => format!("{} = ", binding.ident),
-                    TypeDensity::Compressed => format!("{}=", binding.ident),
+                    TypeDensity::Wide => format!("{} = ", rewrite_ident(context, binding.ident)),
+                    TypeDensity::Compressed => {
+                        format!("{}=", rewrite_ident(context, binding.ident))
+                    }
                 };
                 let budget = shape.width.checked_sub(result.len())?;
                 let rewrite = binding
@@ -220,7 +221,7 @@ fn rewrite_segment(
     shape: Shape,
 ) -> Option<String> {
     let mut result = String::with_capacity(128);
-    result.push_str(&segment.ident.name.as_str());
+    result.push_str(rewrite_ident(context, segment.ident));
 
     let ident_len = result.len();
     let shape = if context.use_block_indent() {
@@ -266,7 +267,7 @@ fn rewrite_segment(
             ast::GenericArgs::Parenthesized(ref data) => {
                 let output = match data.output {
                     Some(ref ty) => FunctionRetTy::Ty(ty.clone()),
-                    None => FunctionRetTy::Default(codemap::DUMMY_SP),
+                    None => FunctionRetTy::Default(source_map::DUMMY_SP),
                 };
                 result.push_str(&format_function_type(
                     data.inputs.iter().map(|x| &**x),
@@ -297,6 +298,8 @@ fn format_function_type<'a, I>(
     <I as Iterator>::Item: Deref,
     <I::Item as Deref>::Target: Rewrite + Spanned + 'a,
 {
+    debug!("format_function_type {:#?}", shape);
+
     // Code for handling variadics is somewhat duplicated for items, but they
     // are different enough to need some serious refactoring to share code.
     enum ArgumentKind<T>
@@ -359,23 +362,17 @@ enum ArgumentKind<T>
         Separator::Comma,
         budget,
     );
-
-    let fmt = ListFormatting {
-        tactic,
-        separator: ",",
-        trailing_separator: if !context.use_block_indent() || variadic {
-            SeparatorTactic::Never
-        } else {
-            context.config.trailing_comma()
-        },
-        separator_place: SeparatorPlace::Back,
-        shape: list_shape,
-        ends_with_newline: tactic.ends_with_newline(context.config.indent_style()),
-        preserve_newline: true,
-        nested: false,
-        config: context.config,
+    let trailing_separator = if !context.use_block_indent() || variadic {
+        SeparatorTactic::Never
+    } else {
+        context.config.trailing_comma()
     };
 
+    let fmt = ListFormatting::new(list_shape, context.config)
+        .tactic(tactic)
+        .trailing_separator(trailing_separator)
+        .ends_with_newline(tactic.ends_with_newline(context.config.indent_style()))
+        .preserve_newline(true);
     let list_str = write_list(&item_vec, &fmt)?;
 
     let ty_shape = match context.config.indent_style() {
@@ -403,7 +400,7 @@ enum ArgumentKind<T>
             shape.block().indent.to_string_with_newline(context.config),
         )
     };
-    if last_line_width(&args) + first_line_width(&output) <= shape.width {
+    if output.is_empty() || last_line_width(&args) + first_line_width(&output) <= shape.width {
         Some(format!("{}{}", args, output))
     } else {
         Some(format!(
@@ -496,8 +493,8 @@ fn rewrite_bounded_lifetime(
 }
 
 impl Rewrite for ast::Lifetime {
-    fn rewrite(&self, _: &RewriteContext, _: Shape) -> Option<String> {
-        Some(self.ident.to_string())
+    fn rewrite(&self, context: &RewriteContext, _: Shape) -> Option<String> {
+        Some(rewrite_ident(context, self.ident).to_owned())
     }
 }
 
@@ -520,7 +517,24 @@ fn rewrite(&self, context: &RewriteContext, shape: Shape) -> Option<String> {
 
 impl Rewrite for ast::GenericBounds {
     fn rewrite(&self, context: &RewriteContext, shape: Shape) -> Option<String> {
-        join_bounds(context, shape, self, true)
+        if self.is_empty() {
+            return Some(String::new());
+        }
+
+        let span = mk_sp(self.get(0)?.span().lo(), self.last()?.span().hi());
+        let has_paren = context.snippet(span).starts_with('(');
+        let bounds_shape = if has_paren {
+            shape.offset_left(1)?.sub_width(1)?
+        } else {
+            shape
+        };
+        join_bounds(context, bounds_shape, self, true).map(|s| {
+            if has_paren {
+                format!("({})", s)
+            } else {
+                s
+            }
+        })
     }
 }
 
@@ -532,7 +546,7 @@ fn rewrite(&self, context: &RewriteContext, shape: Shape) -> Option<String> {
             Some(ref rw) if !rw.is_empty() => result.push_str(&format!("{} ", rw)),
             _ => (),
         }
-        result.push_str(&self.ident.to_string());
+        result.push_str(rewrite_ident(context, self.ident));
         if !self.bounds.is_empty() {
             result.push_str(type_bound_colon(context));
             result.push_str(&self.bounds.rewrite(context, shape)?)
@@ -547,7 +561,8 @@ fn rewrite(&self, context: &RewriteContext, shape: Shape) -> Option<String> {
             };
             result.push_str(eq_str);
             let budget = shape.width.checked_sub(result.len())?;
-            let rewrite = def.rewrite(context, Shape::legacy(budget, shape.indent + result.len()))?;
+            let rewrite =
+                def.rewrite(context, Shape::legacy(budget, shape.indent + result.len()))?;
             result.push_str(&rewrite);
         }
 
@@ -679,7 +694,7 @@ fn rewrite(&self, context: &RewriteContext, shape: Shape) -> Option<String> {
                 rewrite_macro(mac, None, context, shape, MacroPosition::Expression)
             }
             ast::TyKind::ImplicitSelf => Some(String::from("")),
-            ast::TyKind::ImplTrait(ref it) => it
+            ast::TyKind::ImplTrait(_, ref it) => it
                 .rewrite(context, shape)
                 .map(|it_str| format!("impl {}", it_str)),
             ast::TyKind::Err | ast::TyKind::Typeof(..) => unreachable!(),
@@ -693,6 +708,8 @@ fn rewrite_bare_fn(
     context: &RewriteContext,
     shape: Shape,
 ) -> Option<String> {
+    debug!("rewrite_bare_fn {:#?}", shape);
+
     let mut result = String::with_capacity(128);
 
     if let Some(ref lifetime_str) = rewrite_lifetime_param(context, shape, &bare_fn.generic_params)
@@ -715,7 +732,11 @@ fn rewrite_bare_fn(
 
     result.push_str("fn");
 
-    let func_ty_shape = shape.offset_left(result.len())?;
+    let func_ty_shape = if context.use_block_indent() {
+        shape.offset_left(result.len())?
+    } else {
+        shape.visual_indent(result.len()).sub_width(result.len())?
+    };
 
     let rewrite = format_function_type(
         bare_fn.decl.inputs.iter(),
@@ -731,15 +752,28 @@ fn rewrite_bare_fn(
     Some(result)
 }
 
-fn join_bounds<T>(
+fn is_generic_bounds_in_order(generic_bounds: &[ast::GenericBound]) -> bool {
+    let is_trait = |b: &ast::GenericBound| match b {
+        ast::GenericBound::Outlives(..) => false,
+        ast::GenericBound::Trait(..) => true,
+    };
+    let is_lifetime = |b: &ast::GenericBound| !is_trait(b);
+    let last_trait_index = generic_bounds.iter().rposition(is_trait);
+    let first_lifetime_index = generic_bounds.iter().position(is_lifetime);
+    match (last_trait_index, first_lifetime_index) {
+        (Some(last_trait_index), Some(first_lifetime_index)) => {
+            last_trait_index < first_lifetime_index
+        }
+        _ => true,
+    }
+}
+
+fn join_bounds(
     context: &RewriteContext,
     shape: Shape,
-    items: &[T],
+    items: &[ast::GenericBound],
     need_indent: bool,
-) -> Option<String>
-where
-    T: Rewrite,
-{
+) -> Option<String> {
     // Try to join types in a single line
     let joiner = match context.config.type_punctuation_density() {
         TypeDensity::Compressed => "+",
@@ -750,7 +784,7 @@ fn join_bounds<T>(
         .map(|item| item.rewrite(context, shape))
         .collect::<Option<Vec<_>>>()?;
     let result = type_strs.join(joiner);
-    if items.len() == 1 || (!result.contains('\n') && result.len() <= shape.width) {
+    if items.len() <= 1 || (!result.contains('\n') && result.len() <= shape.width) {
         return Some(result);
     }
 
@@ -767,8 +801,26 @@ fn join_bounds<T>(
         (type_strs, shape.indent)
     };
 
-    let joiner = format!("{}+ ", offset.to_string_with_newline(context.config));
-    Some(type_strs.join(&joiner))
+    let is_bound_extendable = |s: &str, b: &ast::GenericBound| match b {
+        ast::GenericBound::Outlives(..) => true,
+        ast::GenericBound::Trait(..) => last_line_extendable(s),
+    };
+    let mut result = String::with_capacity(128);
+    result.push_str(&type_strs[0]);
+    let mut can_be_put_on_the_same_line = is_bound_extendable(&result, &items[0]);
+    let generic_bounds_in_order = is_generic_bounds_in_order(items);
+    for (bound, bound_str) in items[1..].iter().zip(type_strs[1..].iter()) {
+        if generic_bounds_in_order && can_be_put_on_the_same_line {
+            result.push_str(joiner);
+        } else {
+            result.push_str(&offset.to_string_with_newline(context.config));
+            result.push_str("+ ");
+        }
+        result.push_str(bound_str);
+        can_be_put_on_the_same_line = is_bound_extendable(bound_str, bound);
+    }
+
+    Some(result)
 }
 
 pub fn can_be_overflowed_type(context: &RewriteContext, ty: &ast::Ty, len: usize) -> bool {
@@ -792,8 +844,7 @@ fn rewrite_lifetime_param(
         .filter(|p| match p.kind {
             ast::GenericParamKind::Lifetime => true,
             _ => false,
-        })
-        .map(|lt| lt.rewrite(context, shape))
+        }).map(|lt| lt.rewrite(context, shape))
         .collect::<Option<Vec<_>>>()?
         .join(", ");
     if result.is_empty() {