use std::iter::ExactSizeIterator;
use std::ops::Deref;
-use rustc_span::{symbol::kw, BytePos, Span};
-use syntax::ast::{self, FnRetTy, Mutability};
+use rustc_ast::ast::{self, FnRetTy, Mutability, Term};
+use rustc_ast::ptr;
+use rustc_span::{symbol::kw, BytePos, Pos, Span};
+use crate::comment::{combine_strs_with_missing_comments, contains_comment};
use crate::config::lists::*;
use crate::config::{IndentStyle, TypeDensity, Version};
-use crate::expr::{format_expr, rewrite_assign_rhs, rewrite_tuple, rewrite_unary_prefix, ExprType};
+use crate::expr::{
+ format_expr, rewrite_assign_rhs, rewrite_call, rewrite_tuple, rewrite_unary_prefix, ExprType,
+ RhsAssignKind,
+};
use crate::lists::{
definitive_tactic, itemize_list, write_list, ListFormatting, ListItem, Separator,
};
pub(crate) fn rewrite_path(
context: &RewriteContext<'_>,
path_context: PathContext,
- qself: Option<&ast::QSelf>,
+ qself: &Option<ptr::P<ast::QSelf>>,
path: &ast::Path,
shape: Shape,
) -> Option<String> {
- let skip_count = qself.map_or(0, |x| x.position);
+ let skip_count = qself.as_ref().map_or(0, |x| x.position);
let mut result = if path.is_global() && qself.is_none() && path_context != PathContext::Import {
"::".to_owned()
Const(&'a ast::AnonConst),
LifeTime(&'a ast::Lifetime),
Type(&'a ast::Ty),
- Binding(&'a ast::AssocTyConstraint),
+ Binding(&'a ast::AssocConstraint),
}
impl<'a> SegmentParam<'a> {
SegmentParam::Const(const_) => const_.rewrite(context, shape),
SegmentParam::LifeTime(lt) => lt.rewrite(context, shape),
SegmentParam::Type(ty) => ty.rewrite(context, shape),
- SegmentParam::Binding(assoc_ty_constraint) => {
- let mut result = match assoc_ty_constraint.kind {
- ast::AssocTyConstraintKind::Bound { .. } => {
- format!("{}: ", rewrite_ident(context, assoc_ty_constraint.ident))
- }
- ast::AssocTyConstraintKind::Equality { .. } => {
- match context.config.type_punctuation_density() {
- TypeDensity::Wide => {
- format!("{} = ", rewrite_ident(context, assoc_ty_constraint.ident))
- }
- TypeDensity::Compressed => {
- format!("{}=", rewrite_ident(context, assoc_ty_constraint.ident))
- }
- }
- }
- };
+ SegmentParam::Binding(atc) => atc.rewrite(context, shape),
+ }
+ }
+}
- let budget = shape.width.checked_sub(result.len())?;
- let rewrite = assoc_ty_constraint
- .kind
- .rewrite(context, Shape::legacy(budget, shape.indent + result.len()))?;
- result.push_str(&rewrite);
- Some(result)
- }
+impl Rewrite for ast::AssocConstraint {
+ fn rewrite(&self, context: &RewriteContext<'_>, shape: Shape) -> Option<String> {
+ use ast::AssocConstraintKind::{Bound, Equality};
+
+ let mut result = String::with_capacity(128);
+ result.push_str(rewrite_ident(context, self.ident));
+
+ if let Some(ref gen_args) = self.gen_args {
+ let budget = shape.width.checked_sub(result.len())?;
+ let shape = Shape::legacy(budget, shape.indent + result.len());
+ let gen_str = rewrite_generic_args(gen_args, context, shape, gen_args.span())?;
+ result.push_str(&gen_str);
}
+
+ let infix = match (&self.kind, context.config.type_punctuation_density()) {
+ (Bound { .. }, _) => ": ",
+ (Equality { .. }, TypeDensity::Wide) => " = ",
+ (Equality { .. }, TypeDensity::Compressed) => "=",
+ };
+ result.push_str(infix);
+
+ let budget = shape.width.checked_sub(result.len())?;
+ let shape = Shape::legacy(budget, shape.indent + result.len());
+ let rewrite = self.kind.rewrite(context, shape)?;
+ result.push_str(&rewrite);
+
+ Some(result)
}
}
-impl Rewrite for ast::AssocTyConstraintKind {
+impl Rewrite for ast::AssocConstraintKind {
fn rewrite(&self, context: &RewriteContext<'_>, shape: Shape) -> Option<String> {
match self {
- ast::AssocTyConstraintKind::Equality { ty } => ty.rewrite(context, shape),
- ast::AssocTyConstraintKind::Bound { bounds } => bounds.rewrite(context, shape),
+ ast::AssocConstraintKind::Equality { term } => match term {
+ Term::Ty(ty) => ty.rewrite(context, shape),
+ Term::Const(c) => c.rewrite(context, shape),
+ },
+ ast::AssocConstraintKind::Bound { bounds } => bounds.rewrite(context, shape),
}
}
}
};
if let Some(ref args) = segment.args {
+ let generics_str = rewrite_generic_args(args, context, shape, mk_sp(*span_lo, span_hi))?;
match **args {
- ast::GenericArgs::AngleBracketed(ref data)
- if !data.args.is_empty() || !data.constraints.is_empty() =>
- {
- let param_list = data
- .args
- .iter()
- .map(SegmentParam::from_generic_arg)
- .chain(data.constraints.iter().map(|x| SegmentParam::Binding(&*x)))
- .collect::<Vec<_>>();
-
+ ast::GenericArgs::AngleBracketed(ref data) if !data.args.is_empty() => {
// HACK: squeeze out the span between the identifier and the parameters.
- // The hack is requried so that we don't remove the separator inside macro calls.
+ // The hack is required so that we don't remove the separator inside macro calls.
// This does not work in the presence of comment, hoping that people are
// sane about where to put their comment.
let separator_snippet = context
};
result.push_str(separator);
- let generics_str = overflow::rewrite_with_angle_brackets(
- context,
- "",
- param_list.iter(),
- shape,
- mk_sp(*span_lo, span_hi),
- )?;
-
// Update position of last bracket.
*span_lo = context
.snippet_provider
.span_after(mk_sp(*span_lo, span_hi), "<");
-
- result.push_str(&generics_str)
- }
- ast::GenericArgs::Parenthesized(ref data) => {
- result.push_str(&format_function_type(
- data.inputs.iter().map(|x| &**x),
- &data.output,
- false,
- data.span,
- context,
- shape,
- )?);
}
_ => (),
}
+ result.push_str(&generics_str)
}
Some(result)
format!("{}{}", type_str, colon)
};
- rewrite_assign_rhs(context, lhs, bounds, shape)?
+ rewrite_assign_rhs(context, lhs, bounds, &RhsAssignKind::Bounds, shape)?
}
ast::WherePredicate::RegionPredicate(ast::WhereRegionPredicate {
ref lifetime,
..
}) => {
let lhs_ty_str = lhs_ty.rewrite(context, shape).map(|lhs| lhs + " =")?;
- rewrite_assign_rhs(context, lhs_ty_str, &**rhs_ty, shape)?
+ rewrite_assign_rhs(context, lhs_ty_str, &**rhs_ty, &RhsAssignKind::Ty, shape)?
}
};
}
}
+fn rewrite_generic_args(
+ gen_args: &ast::GenericArgs,
+ context: &RewriteContext<'_>,
+ shape: Shape,
+ span: Span,
+) -> Option<String> {
+ match gen_args {
+ ast::GenericArgs::AngleBracketed(ref data) if !data.args.is_empty() => {
+ let args = data
+ .args
+ .iter()
+ .map(|x| match x {
+ ast::AngleBracketedArg::Arg(generic_arg) => {
+ SegmentParam::from_generic_arg(generic_arg)
+ }
+ ast::AngleBracketedArg::Constraint(constraint) => {
+ SegmentParam::Binding(constraint)
+ }
+ })
+ .collect::<Vec<_>>();
+
+ overflow::rewrite_with_angle_brackets(context, "", args.iter(), shape, span)
+ }
+ ast::GenericArgs::Parenthesized(ref data) => format_function_type(
+ data.inputs.iter().map(|x| &**x),
+ &data.output,
+ false,
+ data.span,
+ context,
+ shape,
+ ),
+ _ => Some("".to_owned()),
+ }
+}
+
fn rewrite_bounded_lifetime(
lt: &ast::Lifetime,
bounds: &[ast::GenericBound],
ast::TraitBoundModifier::Maybe => poly_trait_ref
.rewrite(context, shape.offset_left(1)?)
.map(|s| format!("?{}", s)),
- _ => unimplemented!(),
+ ast::TraitBoundModifier::MaybeConst => poly_trait_ref
+ .rewrite(context, shape.offset_left(7)?)
+ .map(|s| format!("~const {}", s)),
+ ast::TraitBoundModifier::MaybeConstMaybe => poly_trait_ref
+ .rewrite(context, shape.offset_left(8)?)
+ .map(|s| format!("~const ?{}", s)),
};
rewrite.map(|s| if has_paren { format!("({})", s) } else { s })
}
let mut result = String::with_capacity(128);
// FIXME: If there are more than one attributes, this will force multiline.
match self.attrs.rewrite(context, shape) {
- Some(ref rw) if !rw.is_empty() => result.push_str(&format!("{} ", rw)),
+ Some(ref rw) if !rw.is_empty() => {
+ result.push_str(rw);
+ // When rewriting generic params, an extra newline should be put
+ // if the attributes end with a doc comment
+ if let Some(true) = self.attrs.last().map(|a| a.is_doc_comment()) {
+ result.push_str(&shape.indent.to_string_with_newline(context.config));
+ } else {
+ result.push(' ');
+ }
+ }
_ => (),
}
- if let syntax::ast::GenericParamKind::Const { ref ty } = &self.kind {
+ if let ast::GenericParamKind::Const {
+ ref ty,
+ kw_span: _,
+ default,
+ } = &self.kind
+ {
result.push_str("const ");
result.push_str(rewrite_ident(context, self.ident));
result.push_str(": ");
result.push_str(&ty.rewrite(context, shape)?);
+ if let Some(default) = default {
+ 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 = default.rewrite(context, Shape::legacy(budget, shape.indent))?;
+ result.push_str(&rewrite);
+ }
} else {
result.push_str(rewrite_ident(context, self.ident));
}
impl Rewrite for ast::TraitRef {
fn rewrite(&self, context: &RewriteContext<'_>, shape: Shape) -> Option<String> {
- rewrite_path(context, PathContext::Type, None, &self.path, shape)
+ rewrite_path(context, PathContext::Type, &None, &self.path, shape)
}
}
ast::TyKind::Rptr(ref lifetime, ref mt) => {
let mut_str = format_mutability(mt.mutbl);
let mut_len = mut_str.len();
- Some(match *lifetime {
- Some(ref lifetime) => {
- let lt_budget = shape.width.checked_sub(2 + mut_len)?;
- let lt_str = lifetime.rewrite(
+ let mut result = String::with_capacity(128);
+ result.push('&');
+ let ref_hi = context.snippet_provider.span_after(self.span(), "&");
+ let mut cmnt_lo = ref_hi;
+
+ if let Some(ref lifetime) = *lifetime {
+ let lt_budget = shape.width.checked_sub(2 + mut_len)?;
+ let lt_str = lifetime.rewrite(
+ context,
+ Shape::legacy(lt_budget, shape.indent + 2 + mut_len),
+ )?;
+ let before_lt_span = mk_sp(cmnt_lo, lifetime.ident.span.lo());
+ if contains_comment(context.snippet(before_lt_span)) {
+ result = combine_strs_with_missing_comments(
context,
- Shape::legacy(lt_budget, shape.indent + 2 + mut_len),
+ &result,
+ <_str,
+ before_lt_span,
+ shape,
+ true,
)?;
- let lt_len = lt_str.len();
- let budget = shape.width.checked_sub(2 + mut_len + lt_len)?;
- format!(
- "&{} {}{}",
- lt_str,
- mut_str,
- mt.ty.rewrite(
- context,
- Shape::legacy(budget, shape.indent + 2 + mut_len + lt_len)
- )?
- )
+ } else {
+ result.push_str(<_str);
}
- None => {
- let budget = shape.width.checked_sub(1 + mut_len)?;
- format!(
- "&{}{}",
+ result.push(' ');
+ cmnt_lo = lifetime.ident.span.hi();
+ }
+
+ if ast::Mutability::Mut == mt.mutbl {
+ let mut_hi = context.snippet_provider.span_after(self.span(), "mut");
+ let before_mut_span = mk_sp(cmnt_lo, mut_hi - BytePos::from_usize(3));
+ if contains_comment(context.snippet(before_mut_span)) {
+ result = combine_strs_with_missing_comments(
+ context,
+ result.trim_end(),
mut_str,
- mt.ty.rewrite(
- context,
- Shape::legacy(budget, shape.indent + 1 + mut_len)
- )?
- )
+ before_mut_span,
+ shape,
+ true,
+ )?;
+ } else {
+ result.push_str(mut_str);
}
- })
+ cmnt_lo = mut_hi;
+ }
+
+ let before_ty_span = mk_sp(cmnt_lo, mt.ty.span.lo());
+ if contains_comment(context.snippet(before_ty_span)) {
+ result = combine_strs_with_missing_comments(
+ context,
+ result.trim_end(),
+ &mt.ty.rewrite(context, shape)?,
+ before_ty_span,
+ shape,
+ true,
+ )?;
+ } else {
+ let used_width = last_line_width(&result);
+ let budget = shape.width.checked_sub(used_width)?;
+ let ty_str = mt
+ .ty
+ .rewrite(context, Shape::legacy(budget, shape.indent + used_width))?;
+ result.push_str(&ty_str);
+ }
+
+ Some(result)
}
// FIXME: we drop any comments here, even though it's a silly place to put
// comments.
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)
+ rewrite_path(context, PathContext::Type, q_self, path, shape)
}
ast::TyKind::Array(ref ty, ref repeats) => rewrite_pair(
&**ty,
}
ast::TyKind::BareFn(ref bare_fn) => rewrite_bare_fn(bare_fn, self.span, context, shape),
ast::TyKind::Never => Some(String::from("!")),
- ast::TyKind::Mac(ref mac) => {
+ ast::TyKind::MacCall(ref mac) => {
rewrite_macro(mac, None, context, shape, MacroPosition::Expression)
}
ast::TyKind::ImplicitSelf => Some(String::from("")),
})
}
ast::TyKind::CVarArgs => Some("...".to_owned()),
- ast::TyKind::Err | ast::TyKind::Typeof(..) => unreachable!(),
+ ast::TyKind::Err => Some(context.snippet(self.span).to_owned()),
+ ast::TyKind::Typeof(ref anon_const) => rewrite_call(
+ context,
+ "typeof",
+ &[anon_const.value.clone()],
+ self.span,
+ shape,
+ ),
}
}
}
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 => "+",
- TypeDensity::Wide => " + ",
- };
- let type_strs = items
- .iter()
- .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) {
- return Some(result);
- }
+ join_bounds_inner(context, shape, items, need_indent, false)
+}
- // 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())
- .with_max_width(context.config);
- let type_strs = items
- .iter()
- .map(|item| item.rewrite(context, nested_shape))
- .collect::<Option<Vec<_>>>()?;
- (type_strs, nested_shape.indent)
- } else {
- (type_strs, shape.indent)
- };
+fn join_bounds_inner(
+ context: &RewriteContext<'_>,
+ shape: Shape,
+ items: &[ast::GenericBound],
+ need_indent: bool,
+ force_newline: bool,
+) -> Option<String> {
+ debug_assert!(!items.is_empty());
+ let generic_bounds_in_order = is_generic_bounds_in_order(items);
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);
+
+ let result = items.iter().enumerate().try_fold(
+ (String::new(), None, false),
+ |(strs, prev_trailing_span, prev_extendable), (i, item)| {
+ let trailing_span = if i < items.len() - 1 {
+ let hi = context
+ .snippet_provider
+ .span_before(mk_sp(items[i + 1].span().lo(), item.span().hi()), "+");
+
+ Some(mk_sp(item.span().hi(), hi))
+ } else {
+ None
+ };
+ let (leading_span, has_leading_comment) = if i > 0 {
+ let lo = context
+ .snippet_provider
+ .span_after(mk_sp(items[i - 1].span().hi(), item.span().lo()), "+");
+
+ let span = mk_sp(lo, item.span().lo());
+
+ let has_comments = contains_comment(context.snippet(span));
+
+ (Some(mk_sp(lo, item.span().lo())), has_comments)
+ } else {
+ (None, false)
+ };
+ let prev_has_trailing_comment = match prev_trailing_span {
+ Some(ts) => contains_comment(context.snippet(ts)),
+ _ => false,
+ };
+
+ let shape = if need_indent && force_newline {
+ shape
+ .block_indent(context.config.tab_spaces())
+ .with_max_width(context.config)
+ } else {
+ shape
+ };
+ let whitespace = if force_newline && (!prev_extendable || !generic_bounds_in_order) {
+ shape
+ .indent
+ .to_string_with_newline(context.config)
+ .to_string()
+ } else {
+ String::from(" ")
+ };
+
+ let joiner = match context.config.type_punctuation_density() {
+ TypeDensity::Compressed => String::from("+"),
+ TypeDensity::Wide => whitespace + "+ ",
+ };
+ let joiner = if has_leading_comment {
+ joiner.trim_end()
+ } else {
+ &joiner
+ };
+ let joiner = if prev_has_trailing_comment {
+ joiner.trim_start()
+ } else {
+ joiner
+ };
+
+ let (extendable, trailing_str) = if i == 0 {
+ let bound_str = item.rewrite(context, shape)?;
+ (is_bound_extendable(&bound_str, item), bound_str)
+ } else {
+ let bound_str = &item.rewrite(context, shape)?;
+ match leading_span {
+ Some(ls) if has_leading_comment => (
+ is_bound_extendable(bound_str, item),
+ combine_strs_with_missing_comments(
+ context, joiner, bound_str, ls, shape, true,
+ )?,
+ ),
+ _ => (
+ is_bound_extendable(bound_str, item),
+ String::from(joiner) + bound_str,
+ ),
+ }
+ };
+ match prev_trailing_span {
+ Some(ts) if prev_has_trailing_comment => combine_strs_with_missing_comments(
+ context,
+ &strs,
+ &trailing_str,
+ ts,
+ shape,
+ true,
+ )
+ .map(|v| (v, trailing_span, extendable)),
+ _ => Some((strs + &trailing_str, trailing_span, extendable)),
+ }
+ },
+ )?;
+
+ if !force_newline
+ && items.len() > 1
+ && (result.0.contains('\n') || result.0.len() > shape.width)
+ {
+ join_bounds_inner(context, shape, items, need_indent, true)
+ } else {
+ Some(result.0)
}
+}
- Some(result)
+pub(crate) fn opaque_ty(ty: &Option<ptr::P<ast::Ty>>) -> Option<&ast::GenericBounds> {
+ ty.as_ref().and_then(|t| match &t.kind {
+ ast::TyKind::ImplTrait(_, bounds) => Some(bounds),
+ _ => None,
+ })
}
pub(crate) fn can_be_overflowed_type(
}
/// Returns `None` if there is no `LifetimeDef` in the given generic parameters.
-fn rewrite_lifetime_param(
+pub(crate) 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,
- })
+ .filter(|p| matches!(p.kind, ast::GenericParamKind::Lifetime))
.map(|lt| lt.rewrite(context, shape))
.collect::<Option<Vec<_>>>()?
.join(", ");