Skip to content

Commit

Permalink
impl rewrite_result for TraitAliasBounds, WherePredicate
Browse files Browse the repository at this point in the history
  • Loading branch information
ding-young committed Aug 28, 2024
1 parent 46cb7d3 commit e7038e7
Show file tree
Hide file tree
Showing 2 changed files with 63 additions and 40 deletions.
67 changes: 39 additions & 28 deletions src/items.rs
Original file line number Diff line number Diff line change
Expand Up @@ -841,7 +841,8 @@ pub(crate) fn format_impl(
where_span_end,
self_ty.span.hi(),
option,
)?;
)
.ok()?;

// If there is no where-clause, we may have missing comments between the trait name and
// the opening brace.
Expand Down Expand Up @@ -1231,7 +1232,8 @@ pub(crate) fn format_trait(
None,
pos_before_where,
option,
)?;
)
.ok()?;
// If the where-clause cannot fit on the same line,
// put the where-clause on a new line
if !where_clause_str.contains('\n')
Expand Down Expand Up @@ -1336,7 +1338,11 @@ pub(crate) struct TraitAliasBounds<'a> {

impl<'a> Rewrite for TraitAliasBounds<'a> {
fn rewrite(&self, context: &RewriteContext<'_>, shape: Shape) -> Option<String> {
let generic_bounds_str = self.generic_bounds.rewrite(context, shape)?;
self.rewrite_result(context, shape).ok()
}

fn rewrite_result(&self, context: &RewriteContext<'_>, shape: Shape) -> RewriteResult {
let generic_bounds_str = self.generic_bounds.rewrite_result(context, shape)?;

let mut option = WhereClauseOption::new(true, WhereClauseSpace::None);
option.allow_single_line();
Expand Down Expand Up @@ -1365,7 +1371,7 @@ impl<'a> Rewrite for TraitAliasBounds<'a> {
shape.indent.to_string_with_newline(context.config)
};

Some(format!("{generic_bounds_str}{space}{where_str}"))
Ok(format!("{generic_bounds_str}{space}{where_str}"))
}
}

Expand Down Expand Up @@ -1622,7 +1628,8 @@ fn format_tuple_struct(
None,
body_hi,
option,
)?
)
.ok()?
}
None => "".to_owned(),
};
Expand Down Expand Up @@ -1791,7 +1798,8 @@ fn rewrite_ty<R: Rewrite>(
None,
generics.span.hi(),
option,
)?;
)
.ok()?;
result.push_str(&where_clause_str);

if let Some(ty) = rhs {
Expand Down Expand Up @@ -2661,7 +2669,8 @@ fn rewrite_fn_base(
Some(span.hi()),
pos_before_where,
option,
)?;
)
.ok()?;
// If there are neither where-clause nor return type, we may be missing comments between
// params and `{`.
if where_clause_str.is_empty() {
Expand Down Expand Up @@ -2937,7 +2946,7 @@ fn rewrite_where_clause_rfc_style(
span_end: Option<BytePos>,
span_end_before_where: BytePos,
where_clause_option: WhereClauseOption,
) -> Option<String> {
) -> RewriteResult {
let (where_keyword, allow_single_line) = rewrite_where_keyword(
context,
predicates,
Expand All @@ -2951,8 +2960,9 @@ fn rewrite_where_clause_rfc_style(
let clause_shape = shape
.block()
.with_max_width(context.config)
.block_left(context.config.tab_spaces())?
.sub_width(1)?;
.block_left(context.config.tab_spaces())
.and_then(|s| s.sub_width(1))
.max_width_error(shape.width, where_span)?;
let force_single_line = context.config.where_single_line()
&& predicates.len() == 1
&& !where_clause_option.veto_single_line;
Expand All @@ -2977,7 +2987,7 @@ fn rewrite_where_clause_rfc_style(
clause_shape.indent.to_string_with_newline(context.config)
};

Some(format!("{where_keyword}{clause_sep}{preds_str}"))
Ok(format!("{where_keyword}{clause_sep}{preds_str}"))
}

/// Rewrite `where` and comment around it.
Expand All @@ -2988,12 +2998,13 @@ fn rewrite_where_keyword(
shape: Shape,
span_end_before_where: BytePos,
where_clause_option: WhereClauseOption,
) -> Option<(String, bool)> {
) -> Result<(String, bool), RewriteError> {
let block_shape = shape.block().with_max_width(context.config);
// 1 = `,`
let clause_shape = block_shape
.block_left(context.config.tab_spaces())?
.sub_width(1)?;
.block_left(context.config.tab_spaces())
.and_then(|s| s.sub_width(1))
.max_width_error(block_shape.width, where_span)?;

let comment_separator = |comment: &str, shape: Shape| {
if comment.is_empty() {
Expand Down Expand Up @@ -3024,7 +3035,7 @@ fn rewrite_where_keyword(
&& comment_before.is_empty()
&& comment_after.is_empty();

Some((result, allow_single_line))
Ok((result, allow_single_line))
}

/// Rewrite bounds on a where clause.
Expand All @@ -3036,7 +3047,7 @@ fn rewrite_bounds_on_where_clause(
span_end: Option<BytePos>,
where_clause_option: WhereClauseOption,
force_single_line: bool,
) -> Option<String> {
) -> RewriteResult {
let span_start = predicates[0].span().lo();
// If we don't have the start of the next span, then use the end of the
// predicates, but that means we miss comments.
Expand Down Expand Up @@ -3075,7 +3086,7 @@ fn rewrite_bounds_on_where_clause(
.tactic(shape_tactic)
.trailing_separator(comma_tactic)
.preserve_newline(preserve_newline);
write_list(&items.collect::<Vec<_>>(), &fmt).ok()
write_list(&items.collect::<Vec<_>>(), &fmt)
}

fn rewrite_where_clause(
Expand All @@ -3089,9 +3100,9 @@ fn rewrite_where_clause(
span_end: Option<BytePos>,
span_end_before_where: BytePos,
where_clause_option: WhereClauseOption,
) -> Option<String> {
) -> RewriteResult {
if predicates.is_empty() {
return Some(String::new());
return Ok(String::new());
}

if context.config.indent_style() == IndentStyle::Block {
Expand Down Expand Up @@ -3151,7 +3162,7 @@ fn rewrite_where_clause(
.trailing_separator(comma_tactic)
.ends_with_newline(tactic.ends_with_newline(context.config.indent_style()))
.preserve_newline(true);
let preds_str = write_list(&item_vec, &fmt).ok()?;
let preds_str = write_list(&item_vec, &fmt)?;

let end_length = if terminator == "{" {
// If the brace is on the next line we don't need to count it otherwise it needs two
Expand All @@ -3169,13 +3180,13 @@ fn rewrite_where_clause(
|| preds_str.contains('\n')
|| shape.indent.width() + " where ".len() + preds_str.len() + end_length > shape.width
{
Some(format!(
Ok(format!(
"\n{}where {}",
(shape.indent + extra_indent).to_string(context.config),
preds_str
))
} else {
Some(format!(" where {preds_str}"))
Ok(format!(" where {preds_str}"))
}
}

Expand All @@ -3196,15 +3207,14 @@ fn rewrite_comments_before_after_where(
span_before_where: Span,
span_after_where: Span,
shape: Shape,
) -> Option<(String, String)> {
let before_comment = rewrite_missing_comment(span_before_where, shape, context).ok()?;
) -> Result<(String, String), RewriteError> {
let before_comment = rewrite_missing_comment(span_before_where, shape, context)?;
let after_comment = rewrite_missing_comment(
span_after_where,
shape.block_indent(context.config.tab_spaces()),
context,
)
.ok()?;
Some((before_comment, after_comment))
)?;
Ok((before_comment, after_comment))
}

fn format_header(
Expand Down Expand Up @@ -3286,7 +3296,8 @@ fn format_generics(
Some(span.hi()),
span_end_before_where,
option,
)?;
)
.ok()?;
result.push_str(&where_clause_str);
(
brace_pos == BracePos::ForceSameLine || brace_style == BraceStyle::PreferSameLine,
Expand Down
36 changes: 24 additions & 12 deletions src/types.rs
Original file line number Diff line number Diff line change
Expand Up @@ -457,6 +457,10 @@ fn get_tactics(item_vec: &[ListItem], output: &str, shape: Shape) -> DefinitiveL

impl Rewrite for ast::WherePredicate {
fn rewrite(&self, context: &RewriteContext<'_>, shape: Shape) -> Option<String> {
self.rewrite_result(context, shape).ok()
}

fn rewrite_result(&self, context: &RewriteContext<'_>, shape: Shape) -> RewriteResult {
// FIXME: dead spans?
let result = match *self {
ast::WherePredicate::BoundPredicate(ast::WhereBoundPredicate {
Expand All @@ -465,7 +469,7 @@ impl Rewrite for ast::WherePredicate {
ref bounds,
..
}) => {
let type_str = bounded_ty.rewrite(context, shape)?;
let type_str = bounded_ty.rewrite_result(context, shape)?;
let colon = type_bound_colon(context).trim_end();
let lhs = if let Some(binder_str) =
rewrite_bound_params(context, shape, bound_generic_params)
Expand All @@ -475,24 +479,28 @@ impl Rewrite for ast::WherePredicate {
format!("{type_str}{colon}")
};

rewrite_assign_rhs(context, lhs, bounds, &RhsAssignKind::Bounds, shape)?
rewrite_assign_rhs(context, lhs, bounds, &RhsAssignKind::Bounds, shape)
.unknown_error()?
}
ast::WherePredicate::RegionPredicate(ast::WhereRegionPredicate {
ref lifetime,
ref bounds,
..
}) => rewrite_bounded_lifetime(lifetime, bounds, context, shape)?,
span,
}) => rewrite_bounded_lifetime(lifetime, bounds, span, context, shape)?,
ast::WherePredicate::EqPredicate(ast::WhereEqPredicate {
ref lhs_ty,
ref rhs_ty,
..
}) => {
let lhs_ty_str = lhs_ty.rewrite(context, shape).map(|lhs| lhs + " =")?;
rewrite_assign_rhs(context, lhs_ty_str, &**rhs_ty, &RhsAssignKind::Ty, shape)?
let lhs_ty_str = lhs_ty
.rewrite_result(context, shape)
.map(|lhs| lhs + " =")?;
rewrite_assign_rhs(context, lhs_ty_str, &**rhs_ty, &RhsAssignKind::Ty, shape)
.unknown_error()?
}
};

Some(result)
Ok(result)
}
}

Expand Down Expand Up @@ -552,23 +560,27 @@ fn rewrite_generic_args(
fn rewrite_bounded_lifetime(
lt: &ast::Lifetime,
bounds: &[ast::GenericBound],
span: Span,
context: &RewriteContext<'_>,
shape: Shape,
) -> Option<String> {
let result = lt.rewrite(context, shape)?;
) -> RewriteResult {
let result = lt.rewrite_result(context, shape)?;

if bounds.is_empty() {
Some(result)
Ok(result)
} else {
let colon = type_bound_colon(context);
let overhead = last_line_width(&result) + colon.len();
let shape = shape
.sub_width(overhead)
.max_width_error(shape.width, span)?;
let result = format!(
"{}{}{}",
result,
colon,
join_bounds(context, shape.sub_width(overhead)?, bounds, true).ok()?
join_bounds(context, shape, bounds, true)?
);
Some(result)
Ok(result)
}
}

Expand Down

0 comments on commit e7038e7

Please sign in to comment.