]> git.lizzy.rs Git - rust.git/blobdiff - src/types.rs
Simplify handling parens on generic bound trait
[rust.git] / src / types.rs
index 5d57b99d32d8d10855acf635668f8c3d80832582..20828429cb1f99b401356541b408c389f7b5fdf4 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_tuple, rewrite_unary_prefix, ToExpr};
+use expr::{rewrite_assign_rhs, rewrite_tuple, rewrite_unary_prefix};
 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,
@@ -141,7 +141,7 @@ fn rewrite_path_segments<'a, I>(
 }
 
 #[derive(Debug)]
-enum SegmentParam<'a> {
+pub enum SegmentParam<'a> {
     LifeTime(&'a ast::Lifetime),
     Type(&'a ast::Ty),
     Binding(&'a ast::TypeBinding),
@@ -166,19 +166,6 @@ fn span(&self) -> Span {
     }
 }
 
-impl<'a> ToExpr for SegmentParam<'a> {
-    fn to_expr(&self) -> Option<&ast::Expr> {
-        None
-    }
-
-    fn can_be_overflowed(&self, context: &RewriteContext, len: usize) -> bool {
-        match *self {
-            SegmentParam::Type(ty) => ty.can_be_overflowed(context, len),
-            _ => false,
-        }
-    }
-}
-
 impl<'a> Rewrite for SegmentParam<'a> {
     fn rewrite(&self, context: &RewriteContext, shape: Shape) -> Option<String> {
         match *self {
@@ -252,7 +239,7 @@ fn rewrite_segment(
                 let generics_str = overflow::rewrite_with_angle_brackets(
                     context,
                     "",
-                    &param_list.iter().map(|e| &*e).collect::<Vec<_>>(),
+                    param_list.iter(),
                     shape,
                     mk_sp(*span_lo, span_hi),
                 )?;
@@ -267,7 +254,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),
@@ -298,6 +285,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>
@@ -360,23 +349,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() {
@@ -404,7 +387,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!(
@@ -506,13 +489,15 @@ impl Rewrite for ast::GenericBound {
     fn rewrite(&self, context: &RewriteContext, shape: Shape) -> Option<String> {
         match *self {
             ast::GenericBound::Trait(ref poly_trait_ref, trait_bound_modifier) => {
-                match trait_bound_modifier {
+                let snippet = context.snippet(self.span());
+                let has_paren = snippet.starts_with("(") && snippet.ends_with(")");
+                let rewrite = 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::TraitBoundModifier::Maybe => poly_trait_ref
+                        .rewrite(context, shape.offset_left(1)?)
+                        .map(|s| format!("?{}", s)),
+                };
+                rewrite.map(|s| if has_paren { format!("({})", s) } else { s })
             }
             ast::GenericBound::Outlives(ref lifetime) => lifetime.rewrite(context, shape),
         }
@@ -525,20 +510,7 @@ fn rewrite(&self, context: &RewriteContext, shape: Shape) -> Option<String> {
             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
-            }
-        })
+        join_bounds(context, shape, self, true)
     }
 }
 
@@ -668,12 +640,9 @@ fn rewrite(&self, context: &RewriteContext, shape: Shape) -> Option<String> {
                 ty.rewrite(context, Shape::legacy(budget, shape.indent + 1))
                     .map(|ty_str| format!("[{}]", ty_str))
             }
-            ast::TyKind::Tup(ref items) => rewrite_tuple(
-                context,
-                &::utils::ptr_vec_to_ref_vec(items),
-                self.span,
-                shape,
-            ),
+            ast::TyKind::Tup(ref items) => {
+                rewrite_tuple(context, items.iter(), self.span, shape, items.len() == 1)
+            }
             ast::TyKind::Path(ref q_self, ref path) => {
                 rewrite_path(context, PathContext::Type, q_self.as_ref(), path, shape)
             }
@@ -712,6 +681,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)
@@ -734,7 +705,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(),
@@ -772,6 +747,8 @@ fn join_bounds(
     items: &[ast::GenericBound],
     need_indent: bool,
 ) -> Option<String> {
+    debug_assert!(!items.is_empty());
+
     // Try to join types in a single line
     let joiner = match context.config.type_punctuation_density() {
         TypeDensity::Compressed => "+",
@@ -842,7 +819,8 @@ 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() {