]> git.lizzy.rs Git - rust.git/blobdiff - src/types.rs
Make children list in-order
[rust.git] / src / types.rs
index 47a52281e28d061f3cf4adcc5796113c7e11d365..5d57b99d32d8d10855acf635668f8c3d80832582 100644 (file)
 
 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 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)]
@@ -59,9 +58,6 @@ pub fn rewrite_path(
 
     if let Some(qself) = qself {
         result.push('<');
-        if context.config.spaces_within_parens_and_brackets() {
-            result.push_str(" ")
-        }
 
         let fmt_ty = qself.ty.rewrite(context, shape)?;
         result.push_str(&fmt_ty);
@@ -86,10 +82,6 @@ pub fn rewrite_path(
             )?;
         }
 
-        if context.config.spaces_within_parens_and_brackets() {
-            result.push_str(" ")
-        }
-
         result.push_str(">::");
         span_lo = qself.ty.span.hi() + BytePos(1);
     }
@@ -155,6 +147,15 @@ enum SegmentParam<'a> {
     Binding(&'a ast::TypeBinding),
 }
 
+impl<'a> SegmentParam<'a> {
+    fn from_generic_arg(arg: &ast::GenericArg) -> SegmentParam {
+        match arg {
+            ast::GenericArg::Lifetime(ref lt) => SegmentParam::LifeTime(lt),
+            ast::GenericArg::Type(ref ty) => SegmentParam::Type(ty),
+        }
+    }
+}
+
 impl<'a> Spanned for SegmentParam<'a> {
     fn span(&self) -> Span {
         match *self {
@@ -185,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
@@ -218,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() {
@@ -227,18 +230,15 @@ fn rewrite_segment(
         shape.shrink_left(ident_len)?
     };
 
-    if let Some(ref params) = segment.parameters {
-        match **params {
-            ast::PathParameters::AngleBracketed(ref data)
-                if !data.lifetimes.is_empty()
-                    || !data.types.is_empty()
-                    || !data.bindings.is_empty() =>
+    if let Some(ref args) = segment.args {
+        match **args {
+            ast::GenericArgs::AngleBracketed(ref data)
+                if !data.args.is_empty() || !data.bindings.is_empty() =>
             {
                 let param_list = data
-                    .lifetimes
+                    .args
                     .iter()
-                    .map(SegmentParam::LifeTime)
-                    .chain(data.types.iter().map(|x| SegmentParam::Type(&*x)))
+                    .map(SegmentParam::from_generic_arg)
                     .chain(data.bindings.iter().map(|x| SegmentParam::Binding(&*x)))
                     .collect::<Vec<_>>();
 
@@ -264,7 +264,7 @@ fn rewrite_segment(
 
                 result.push_str(&generics_str)
             }
-            ast::PathParameters::Parenthesized(ref data) => {
+            ast::GenericArgs::Parenthesized(ref data) => {
                 let output = match data.output {
                     Some(ref ty) => FunctionRetTy::Ty(ty.clone()),
                     None => FunctionRetTy::Default(codemap::DUMMY_SP),
@@ -305,7 +305,7 @@ enum ArgumentKind<T>
         T: Deref,
         <T as Deref>::Target: Rewrite + Spanned,
     {
-        Regular(Box<T>),
+        Regular(T),
         Variadic(BytePos),
     }
 
@@ -332,11 +332,7 @@ enum ArgumentKind<T>
     let list_lo = context.snippet_provider.span_after(span, "(");
     let items = itemize_list(
         context.snippet_provider,
-        // FIXME Would be nice to avoid this allocation,
-        // but I couldn't get the types to work out.
-        inputs
-            .map(|i| ArgumentKind::Regular(Box::new(i)))
-            .chain(variadic_arg),
+        inputs.map(ArgumentKind::Regular).chain(variadic_arg),
         ")",
         ",",
         |arg| match *arg {
@@ -377,6 +373,7 @@ enum ArgumentKind<T>
         shape: list_shape,
         ends_with_newline: tactic.ends_with_newline(context.config.indent_style()),
         preserve_newline: true,
+        nested: false,
         config: context.config,
     };
 
@@ -428,7 +425,7 @@ fn type_bound_colon(context: &RewriteContext) -> &'static str {
 
 impl Rewrite for ast::WherePredicate {
     fn rewrite(&self, context: &RewriteContext, shape: Shape) -> Option<String> {
-        // TODO: dead spans?
+        // FIXME: dead spans?
         let result = match *self {
             ast::WherePredicate::BoundPredicate(ast::WhereBoundPredicate {
                 ref bound_generic_params,
@@ -441,13 +438,7 @@ fn rewrite(&self, context: &RewriteContext, shape: Shape) -> Option<String> {
                 let lhs = if let Some(lifetime_str) =
                     rewrite_lifetime_param(context, shape, bound_generic_params)
                 {
-                    if context.config.spaces_within_parens_and_brackets()
-                        && !lifetime_str.is_empty()
-                    {
-                        format!("for< {} > {}{}", lifetime_str, type_str, colon)
-                    } else {
-                        format!("for<{}> {}{}", lifetime_str, type_str, colon)
-                    }
+                    format!("for<{}> {}{}", lifetime_str, type_str, colon)
                 } else {
                     format!("{}{}", type_str, colon)
                 };
@@ -473,15 +464,18 @@ fn rewrite(&self, context: &RewriteContext, shape: Shape) -> Option<String> {
     }
 }
 
-impl Rewrite for ast::LifetimeDef {
+impl Rewrite for ast::GenericArg {
     fn rewrite(&self, context: &RewriteContext, shape: Shape) -> Option<String> {
-        rewrite_bounded_lifetime(&self.lifetime, &self.bounds, context, shape)
+        match *self {
+            ast::GenericArg::Lifetime(ref lt) => lt.rewrite(context, shape),
+            ast::GenericArg::Type(ref ty) => ty.rewrite(context, shape),
+        }
     }
 }
 
 fn rewrite_bounded_lifetime(
     lt: &ast::Lifetime,
-    bounds: &[ast::Lifetime],
+    bounds: &[ast::GenericBound],
     context: &RewriteContext,
     shape: Shape,
 ) -> Option<String> {
@@ -502,45 +496,53 @@ fn rewrite_bounded_lifetime(
     }
 }
 
-impl Rewrite for ast::TyParamBound {
-    fn rewrite(&self, context: &RewriteContext, shape: Shape) -> Option<String> {
-        match *self {
-            ast::TyParamBound::TraitTyParamBound(ref tref, ast::TraitBoundModifier::None) => {
-                tref.rewrite(context, shape)
-            }
-            ast::TyParamBound::TraitTyParamBound(ref tref, ast::TraitBoundModifier::Maybe) => Some(
-                format!("?{}", tref.rewrite(context, shape.offset_left(1)?)?),
-            ),
-            ast::TyParamBound::RegionTyParamBound(ref l) => l.rewrite(context, shape),
-        }
-    }
-}
-
 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())
     }
 }
 
-/// A simple wrapper over type param bounds in trait.
-#[derive(new)]
-pub struct TraitTyParamBounds<'a> {
-    inner: &'a ast::TyParamBounds,
-}
-
-impl<'a> Rewrite for TraitTyParamBounds<'a> {
+impl Rewrite for ast::GenericBound {
     fn rewrite(&self, context: &RewriteContext, shape: Shape) -> Option<String> {
-        join_bounds(context, shape, self.inner, false)
+        match *self {
+            ast::GenericBound::Trait(ref poly_trait_ref, trait_bound_modifier) => {
+                match trait_bound_modifier {
+                    ast::TraitBoundModifier::None => poly_trait_ref.rewrite(context, shape),
+                    ast::TraitBoundModifier::Maybe => {
+                        let rw = poly_trait_ref.rewrite(context, shape.offset_left(1)?)?;
+                        Some(format!("?{}", rw))
+                    }
+                }
+            }
+            ast::GenericBound::Outlives(ref lifetime) => lifetime.rewrite(context, shape),
+        }
     }
 }
 
-impl Rewrite for ast::TyParamBounds {
+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
+            }
+        })
     }
 }
 
-impl Rewrite for ast::TyParam {
+impl Rewrite for ast::GenericParam {
     fn rewrite(&self, context: &RewriteContext, shape: Shape) -> Option<String> {
         let mut result = String::with_capacity(128);
         // FIXME: If there are more than one attributes, this will force multiline.
@@ -548,19 +550,23 @@ 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)?)
         }
-        if let Some(ref def) = self.default {
+        if let ast::GenericParamKind::Type {
+            default: Some(ref def),
+        } = self.kind
+        {
             let eq_str = match context.config.type_punctuation_density() {
                 TypeDensity::Compressed => "=",
                 TypeDensity::Wide => " = ",
             };
             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);
         }
 
@@ -579,13 +585,7 @@ fn rewrite(&self, context: &RewriteContext, shape: Shape) -> Option<String> {
                 .trait_ref
                 .rewrite(context, shape.offset_left(extra_offset)?)?;
 
-            Some(
-                if context.config.spaces_within_parens_and_brackets() && !lifetime_str.is_empty() {
-                    format!("for< {} > {}", lifetime_str, path_str)
-                } else {
-                    format!("for<{}> {}", lifetime_str, path_str)
-                },
-            )
+            Some(format!("for<{}> {}", lifetime_str, path_str))
         } else {
             self.trait_ref.rewrite(context, shape)
         }
@@ -661,28 +661,12 @@ fn rewrite(&self, context: &RewriteContext, shape: Shape) -> Option<String> {
             ast::TyKind::Paren(ref ty) => {
                 let budget = shape.width.checked_sub(2)?;
                 ty.rewrite(context, Shape::legacy(budget, shape.indent + 1))
-                    .map(|ty_str| {
-                        if context.config.spaces_within_parens_and_brackets() {
-                            format!("( {} )", ty_str)
-                        } else {
-                            format!("({})", ty_str)
-                        }
-                    })
+                    .map(|ty_str| format!("({})", ty_str))
             }
             ast::TyKind::Slice(ref ty) => {
-                let budget = if context.config.spaces_within_parens_and_brackets() {
-                    shape.width.checked_sub(4)?
-                } else {
-                    shape.width.checked_sub(2)?
-                };
+                let budget = shape.width.checked_sub(4)?;
                 ty.rewrite(context, Shape::legacy(budget, shape.indent + 1))
-                    .map(|ty_str| {
-                        if context.config.spaces_within_parens_and_brackets() {
-                            format!("[ {} ]", ty_str)
-                        } else {
-                            format!("[{}]", ty_str)
-                        }
-                    })
+                    .map(|ty_str| format!("[{}]", ty_str))
             }
             ast::TyKind::Tup(ref items) => rewrite_tuple(
                 context,
@@ -693,19 +677,14 @@ fn rewrite(&self, context: &RewriteContext, shape: Shape) -> Option<String> {
             ast::TyKind::Path(ref q_self, ref path) => {
                 rewrite_path(context, PathContext::Type, q_self.as_ref(), path, shape)
             }
-            ast::TyKind::Array(ref ty, ref repeats) => {
-                let use_spaces = context.config.spaces_within_parens_and_brackets();
-                let lbr = if use_spaces { "[ " } else { "[" };
-                let rbr = if use_spaces { " ]" } else { "]" };
-                rewrite_pair(
-                    &**ty,
-                    &**repeats,
-                    PairParts::new(lbr, "; ", rbr),
-                    context,
-                    shape,
-                    SeparatorPlace::Back,
-                )
-            }
+            ast::TyKind::Array(ref ty, ref repeats) => rewrite_pair(
+                &**ty,
+                &*repeats.value,
+                PairParts::new("[", "; ", "]"),
+                context,
+                shape,
+                SeparatorPlace::Back,
+            ),
             ast::TyKind::Infer => {
                 if shape.width >= 1 {
                     Some("_".to_owned())
@@ -719,7 +698,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!(),
@@ -771,15 +750,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 => "+",
@@ -790,7 +782,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);
     }
 
@@ -807,8 +799,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 {
@@ -829,8 +839,10 @@ fn rewrite_lifetime_param(
 ) -> Option<String> {
     let result = generic_params
         .iter()
-        .filter(|p| p.is_lifetime_param())
-        .map(|lt| lt.rewrite(context, shape))
+        .filter(|p| match p.kind {
+            ast::GenericParamKind::Lifetime => true,
+            _ => false,
+        }).map(|lt| lt.rewrite(context, shape))
         .collect::<Option<Vec<_>>>()?
         .join(", ");
     if result.is_empty() {