use std::iter::ExactSizeIterator;
use std::ops::Deref;
+use config::lists::*;
use syntax::ast::{self, FunctionRetTy, Mutability};
-use syntax::codemap::{self, BytePos, Span};
-use syntax::print::pprust;
+use syntax::source_map::{self, BytePos, Span};
use syntax::symbol::keywords;
-use spanned::Spanned;
-use codemap::SpanUtils;
use config::{IndentStyle, TypeDensity};
-use expr::{rewrite_pair, rewrite_tuple, rewrite_unary_prefix, wrap_args_with_parens, PairParts};
-use items::{format_generics_item_list, generics_shape_from_config};
-use lists::{definitive_tactic, itemize_list, write_list, ListFormatting, ListTactic, Separator,
- SeparatorPlace, SeparatorTactic};
+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 utils::{colon_spaces, extra_offset, first_line_width, format_abi, format_mutability,
- last_line_width, mk_sp};
+use source_map::SpanUtils;
+use spanned::Spanned;
+use utils::{
+ 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)]
pub enum PathContext {
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);
)?;
}
- if context.config.spaces_within_parens_and_brackets() {
- result.push_str(" ")
- }
-
result.push_str(">::");
span_lo = qself.ty.span.hi() + BytePos(1);
}
for segment in iter {
// Indicates a global path, shouldn't be rendered.
- if segment.identifier.name == keywords::CrateRoot.name() {
+ if segment.ident.name == keywords::CrateRoot.name() {
continue;
}
if first {
}
impl<'a> SegmentParam<'a> {
- fn get_span(&self) -> Span {
+ 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 {
- SegmentParam::LifeTime(lt) => lt.span,
+ SegmentParam::LifeTime(lt) => lt.ident.span,
SegmentParam::Type(ty) => ty.span,
SegmentParam::Binding(binding) => binding.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 {
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
context: &RewriteContext,
shape: Shape,
) -> Option<String> {
- let ident_len = segment.identifier.to_string().len();
- let shape = shape.shrink_left(ident_len)?;
-
- let params = 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() =>
+ let mut result = String::with_capacity(128);
+ result.push_str(rewrite_ident(context, segment.ident));
+
+ let ident_len = result.len();
+ let shape = if context.use_block_indent() {
+ shape.offset_left(ident_len)?
+ } else {
+ shape.shrink_left(ident_len)?
+ };
+
+ 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
+ let param_list = data
+ .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<_>>();
- let next_span_lo = param_list.last().unwrap().get_span().hi() + BytePos(1);
- let list_lo = context.codemap.span_after(mk_sp(*span_lo, span_hi), "<");
let separator = if path_context == PathContext::Expr {
"::"
} else {
""
};
+ result.push_str(separator);
- let generics_shape =
- generics_shape_from_config(context.config, shape, separator.len())?;
- let one_line_width = shape.width.checked_sub(separator.len() + 2)?;
- let items = itemize_list(
- context.codemap,
- param_list.into_iter(),
- ">",
- ",",
- |param| param.get_span().lo(),
- |param| param.get_span().hi(),
- |seg| seg.rewrite(context, generics_shape),
- list_lo,
- span_hi,
- false,
- );
- let generics_str =
- format_generics_item_list(context, items, generics_shape, one_line_width)?;
+ let generics_str = overflow::rewrite_with_angle_brackets(
+ context,
+ "",
+ ¶m_list.iter().map(|e| &*e).collect::<Vec<_>>(),
+ shape,
+ mk_sp(*span_lo, span_hi),
+ )?;
// Update position of last bracket.
- *span_lo = next_span_lo;
+ *span_lo = context
+ .snippet_provider
+ .span_after(mk_sp(*span_lo, span_hi), "<");
- format!("{}{}", separator, generics_str)
+ 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),
+ None => FunctionRetTy::Default(source_map::DUMMY_SP),
};
- format_function_type(
+ result.push_str(&format_function_type(
data.inputs.iter().map(|x| &**x),
&output,
false,
data.span,
context,
shape,
- )?
+ )?);
}
- _ => String::new(),
+ _ => (),
}
- } else {
- String::new()
- };
+ }
- Some(format!("{}{}", segment.identifier, params))
+ Some(result)
}
fn format_function_type<'a, I>(
T: Deref,
<T as Deref>::Target: Rewrite + Spanned,
{
- Regular(Box<T>),
+ Regular(T),
Variadic(BytePos),
}
let variadic_arg = if variadic {
- let variadic_start = context.codemap.span_before(span, "...");
+ let variadic_start = context.snippet_provider.span_before(span, "...");
Some(ArgumentKind::Variadic(variadic_start))
} else {
None
IndentStyle::Visual => shape.indent + 1,
};
let list_shape = Shape::legacy(budget, offset);
- let list_lo = context.codemap.span_after(span, "(");
+ let list_lo = context.snippet_provider.span_after(span, "(");
let items = itemize_list(
- context.codemap,
- // 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),
+ context.snippet_provider,
+ inputs.map(ArgumentKind::Regular).chain(variadic_arg),
")",
",",
|arg| match *arg {
Separator::Comma,
budget,
);
-
- let fmt = ListFormatting {
- tactic: 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,
- 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() {
FunctionRetTy::Default(..) => String::new(),
};
- let extendable = (!list_str.contains('\n') || list_str.is_empty()) && !output.contains('\n');
- let args = wrap_args_with_parens(
- context,
- &list_str,
- extendable,
- shape.sub_width(first_line_width(&output))?,
- Shape::indented(offset, context.config),
- );
+ let args = if (!list_str.contains('\n') || list_str.is_empty()) && !output.contains('\n')
+ || !context.use_block_indent()
+ {
+ format!("({})", list_str)
+ } else {
+ format!(
+ "({}{}{})",
+ offset.to_string_with_newline(context.config),
+ list_str,
+ shape.block().indent.to_string_with_newline(context.config),
+ )
+ };
if last_line_width(&args) + first_line_width(&output) <= shape.width {
Some(format!("{}{}", args, output))
} else {
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_lifetimes,
+ ref bound_generic_params,
ref bounded_ty,
ref bounds,
..
}) => {
let type_str = bounded_ty.rewrite(context, shape)?;
-
- let colon = type_bound_colon(context);
-
- if !bound_lifetimes.is_empty() {
- let lifetime_str: String = bound_lifetimes
- .iter()
- .map(|lt| lt.rewrite(context, shape))
- .collect::<Option<Vec<_>>>()?
- .join(", ");
-
- // 6 = "for<> ".len()
- let used_width = lifetime_str.len() + type_str.len() + colon.len() + 6;
- let ty_shape = shape.offset_left(used_width)?;
- let bounds = bounds
- .iter()
- .map(|ty_bound| ty_bound.rewrite(context, ty_shape))
- .collect::<Option<Vec<_>>>()?;
- let bounds_str = join_bounds(context, ty_shape, &bounds);
-
- if context.config.spaces_within_parens_and_brackets()
- && !lifetime_str.is_empty()
- {
- format!(
- "for< {} > {}{}{}",
- lifetime_str, type_str, colon, bounds_str
- )
- } else {
- format!("for<{}> {}{}{}", lifetime_str, type_str, colon, bounds_str)
- }
+ let colon = type_bound_colon(context).trim_right();
+ let lhs = if let Some(lifetime_str) =
+ rewrite_lifetime_param(context, shape, bound_generic_params)
+ {
+ format!("for<{}> {}{}", lifetime_str, type_str, colon)
} else {
- let used_width = type_str.len() + colon.len();
- let ty_shape = match context.config.indent_style() {
- IndentStyle::Visual => shape.block_left(used_width)?,
- IndentStyle::Block => shape,
- };
- let bounds = bounds
- .iter()
- .map(|ty_bound| ty_bound.rewrite(context, ty_shape))
- .collect::<Option<Vec<_>>>()?;
- let overhead = type_str.len() + colon.len();
- let bounds_str = join_bounds(context, ty_shape.sub_width(overhead)?, &bounds);
-
- format!("{}{}{}", type_str, colon, bounds_str)
- }
+ format!("{}{}", type_str, colon)
+ };
+
+ rewrite_assign_rhs(context, lhs, bounds, shape)?
}
ast::WherePredicate::RegionPredicate(ast::WhereRegionPredicate {
ref lifetime,
ref bounds,
..
- }) => rewrite_bounded_lifetime(lifetime, bounds.iter(), context, shape)?,
+ }) => rewrite_bounded_lifetime(lifetime, bounds, context, shape)?,
ast::WherePredicate::EqPredicate(ast::WhereEqPredicate {
ref lhs_ty,
ref rhs_ty,
..
}) => {
- let lhs_ty_str = lhs_ty.rewrite(context, shape)?;
- // 3 = " = ".len()
- let used_width = 3 + lhs_ty_str.len();
- let budget = shape.width.checked_sub(used_width)?;
- let rhs_ty_str =
- rhs_ty.rewrite(context, Shape::legacy(budget, shape.indent + used_width))?;
- format!("{} = {}", lhs_ty_str, rhs_ty_str)
+ let lhs_ty_str = lhs_ty.rewrite(context, shape).map(|lhs| lhs + " =")?;
+ rewrite_assign_rhs(context, lhs_ty_str, &**rhs_ty, shape)?
}
};
}
}
-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.iter(), 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<'b, I>(
+fn rewrite_bounded_lifetime(
lt: &ast::Lifetime,
- bounds: I,
+ bounds: &[ast::GenericBound],
context: &RewriteContext,
shape: Shape,
-) -> Option<String>
-where
- I: ExactSizeIterator<Item = &'b ast::Lifetime>,
-{
+) -> Option<String> {
let result = lt.rewrite(context, shape)?;
- if bounds.len() == 0 {
+ if bounds.is_empty() {
Some(result)
} else {
- let appendix = bounds
- .into_iter()
- .map(|b| b.rewrite(context, shape))
- .collect::<Option<Vec<_>>>()?;
let colon = type_bound_colon(context);
let overhead = last_line_width(&result) + colon.len();
let result = format!(
"{}{}{}",
result,
colon,
- join_bounds(context, shape.sub_width(overhead)?, &appendix)
+ join_bounds(context, shape.sub_width(overhead)?, bounds, true)?
);
Some(result)
}
}
-impl Rewrite for ast::TyParamBound {
+impl Rewrite for ast::Lifetime {
+ fn rewrite(&self, context: &RewriteContext, _: Shape) -> Option<String> {
+ Some(rewrite_ident(context, self.ident).to_owned())
+ }
+}
+
+impl Rewrite for ast::GenericBound {
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::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::TyParamBound::RegionTyParamBound(ref l) => l.rewrite(context, shape),
+ ast::GenericBound::Outlives(ref lifetime) => lifetime.rewrite(context, shape),
}
}
}
-impl Rewrite for ast::Lifetime {
- fn rewrite(&self, _: &RewriteContext, _: Shape) -> Option<String> {
- Some(pprust::lifetime_to_string(self))
- }
-}
-
-impl Rewrite for ast::TyParamBounds {
+impl Rewrite for ast::GenericBounds {
fn rewrite(&self, context: &RewriteContext, shape: Shape) -> Option<String> {
- let strs = self.iter()
- .map(|b| b.rewrite(context, shape))
- .collect::<Option<Vec<_>>>()?;
- Some(join_bounds(context, shape, &strs))
+ 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.
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));
- let strs = self.bounds
- .iter()
- .map(|ty_bound| ty_bound.rewrite(context, shape))
- .collect::<Option<Vec<_>>>()?;
- result.push_str(&join_bounds(context, shape, &strs));
+ 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);
}
impl Rewrite for ast::PolyTraitRef {
fn rewrite(&self, context: &RewriteContext, shape: Shape) -> Option<String> {
- if !self.bound_lifetimes.is_empty() {
- let lifetime_str: String = self.bound_lifetimes
- .iter()
- .map(|lt| lt.rewrite(context, shape))
- .collect::<Option<Vec<_>>>()?
- .join(", ");
-
+ if let Some(lifetime_str) =
+ rewrite_lifetime_param(context, shape, &self.bound_generic_params)
+ {
// 6 is "for<> ".len()
let extra_offset = lifetime_str.len() + 6;
- let path_str = self.trait_ref
+ let path_str = self
+ .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)
}
impl Rewrite for ast::Ty {
fn rewrite(&self, context: &RewriteContext, shape: Shape) -> Option<String> {
match self.node {
- ast::TyKind::TraitObject(ref bounds, ..) => bounds.rewrite(context, shape),
+ ast::TyKind::TraitObject(ref bounds, tobj_syntax) => {
+ // we have to consider 'dyn' keyword is used or not!!!
+ let is_dyn = tobj_syntax == ast::TraitObjectSyntax::Dyn;
+ // 4 is length of 'dyn '
+ let shape = if is_dyn { shape.offset_left(4)? } else { shape };
+ let res = bounds.rewrite(context, shape)?;
+ if is_dyn {
+ Some(format!("dyn {}", res))
+ } else {
+ Some(res)
+ }
+ }
ast::TyKind::Ptr(ref mt) => {
let prefix = match mt.mutbl {
Mutability::Mutable => "*mut ",
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,
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())
rewrite_macro(mac, None, context, shape, MacroPosition::Expression)
}
ast::TyKind::ImplicitSelf => Some(String::from("")),
- ast::TyKind::ImplTrait(ref it) => it.rewrite(context, shape)
+ ast::TyKind::ImplTrait(_, ref it) => it
+ .rewrite(context, shape)
.map(|it_str| format!("impl {}", it_str)),
ast::TyKind::Err | ast::TyKind::Typeof(..) => unreachable!(),
}
) -> Option<String> {
let mut result = String::with_capacity(128);
- if !bare_fn.lifetimes.is_empty() {
+ if let Some(ref lifetime_str) = rewrite_lifetime_param(context, shape, &bare_fn.generic_params)
+ {
result.push_str("for<");
// 6 = "for<> ".len(), 4 = "for<".
- // This doesn't work out so nicely for mutliline situation with lots of
+ // This doesn't work out so nicely for multiline situation with lots of
// rightward drift. If that is a problem, we could use the list stuff.
- result.push_str(&bare_fn
- .lifetimes
- .iter()
- .map(|l| {
- l.rewrite(
- context,
- Shape::legacy(shape.width.checked_sub(6)?, shape.indent + 4),
- )
- })
- .collect::<Option<Vec<_>>>()?
- .join(", "));
+ result.push_str(lifetime_str);
result.push_str("> ");
}
Some(result)
}
-pub fn join_bounds(context: &RewriteContext, shape: Shape, type_strs: &[String]) -> String {
+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: &[ast::GenericBound],
+ need_indent: bool,
+) -> Option<String> {
// Try to join types in a single line
let joiner = match context.config.type_punctuation_density() {
TypeDensity::Compressed => "+",
TypeDensity::Wide => " + ",
};
+ let type_strs = items
+ .iter()
+ .map(|item| item.rewrite(context, shape))
+ .collect::<Option<Vec<_>>>()?;
let result = type_strs.join(joiner);
- if result.contains('\n') || result.len() > shape.width {
- let joiner_indent = shape.indent.block_indent(context.config);
- let joiner = format!("\n{}+ ", joiner_indent.to_string(context.config));
- type_strs.join(&joiner)
+ if items.len() <= 1 || (!result.contains('\n') && result.len() <= shape.width) {
+ return Some(result);
+ }
+
+ // We need to use multiple lines.
+ let (type_strs, offset) = if need_indent {
+ // Rewrite with additional indentation.
+ let nested_shape = shape.block_indent(context.config.tab_spaces());
+ let type_strs = items
+ .iter()
+ .map(|item| item.rewrite(context, nested_shape))
+ .collect::<Option<Vec<_>>>()?;
+ (type_strs, nested_shape.indent)
} else {
- result
+ (type_strs, shape.indent)
+ };
+
+ 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 {
match ty.node {
- ast::TyKind::Path(..) | ast::TyKind::Tup(..) => context.use_block_indent() && len == 1,
+ ast::TyKind::Tup(..) => context.use_block_indent() && len == 1,
ast::TyKind::Rptr(_, ref mutty) | ast::TyKind::Ptr(ref mutty) => {
can_be_overflowed_type(context, &*mutty.ty, len)
}
_ => false,
}
}
+
+/// Returns `None` if there is no `LifetimeDef` in the given generic parameters.
+fn rewrite_lifetime_param(
+ context: &RewriteContext,
+ shape: Shape,
+ generic_params: &[ast::GenericParam],
+) -> Option<String> {
+ let result = generic_params
+ .iter()
+ .filter(|p| match p.kind {
+ ast::GenericParamKind::Lifetime => true,
+ _ => false,
+ }).map(|lt| lt.rewrite(context, shape))
+ .collect::<Option<Vec<_>>>()?
+ .join(", ");
+ if result.is_empty() {
+ None
+ } else {
+ Some(result)
+ }
+}