Skip to content
This repository was archived by the owner on May 28, 2025. It is now read-only.

Commit c1373b2

Browse files
committed
Format trait aliases with where clauses
1 parent 95c2ad3 commit c1373b2

File tree

1 file changed

+44
-1
lines changed

1 file changed

+44
-1
lines changed

src/items.rs

Lines changed: 44 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1154,6 +1154,45 @@ pub(crate) fn format_trait(
11541154
}
11551155
}
11561156

1157+
pub(crate) struct TraitAliasBounds<'a> {
1158+
generic_bounds: &'a ast::GenericBounds,
1159+
generics: &'a ast::Generics,
1160+
}
1161+
1162+
impl<'a> Rewrite for TraitAliasBounds<'a> {
1163+
fn rewrite(&self, context: &RewriteContext<'_>, shape: Shape) -> Option<String> {
1164+
let generic_bounds_str = self.generic_bounds.rewrite(context, shape)?;
1165+
1166+
let mut option = WhereClauseOption::new(true, WhereClauseSpace::None);
1167+
option.allow_single_line();
1168+
1169+
let where_str = rewrite_where_clause(
1170+
context,
1171+
&self.generics.where_clause,
1172+
context.config.brace_style(),
1173+
shape,
1174+
Density::Compressed,
1175+
";",
1176+
None,
1177+
self.generics.where_clause.span.lo(),
1178+
option,
1179+
)?;
1180+
1181+
let fits_single_line = !generic_bounds_str.contains('\n')
1182+
&& !where_str.contains('\n')
1183+
&& generic_bounds_str.len() + where_str.len() + 1 <= shape.width;
1184+
let space = if generic_bounds_str.is_empty() || where_str.is_empty() {
1185+
Cow::from("")
1186+
} else if fits_single_line {
1187+
Cow::from(" ")
1188+
} else {
1189+
shape.indent.to_string_with_newline(&context.config)
1190+
};
1191+
1192+
Some(format!("{}{}{}", generic_bounds_str, space, where_str))
1193+
}
1194+
}
1195+
11571196
pub(crate) fn format_trait_alias(
11581197
context: &RewriteContext<'_>,
11591198
ident: ast::Ident,
@@ -1169,7 +1208,11 @@ pub(crate) fn format_trait_alias(
11691208
let vis_str = format_visibility(context, vis);
11701209
let lhs = format!("{}trait {} =", vis_str, generics_str);
11711210
// 1 = ";"
1172-
rewrite_assign_rhs(context, lhs, generic_bounds, shape.sub_width(1)?).map(|s| s + ";")
1211+
let trait_alias_bounds = TraitAliasBounds {
1212+
generics,
1213+
generic_bounds,
1214+
};
1215+
rewrite_assign_rhs(context, lhs, &trait_alias_bounds, shape.sub_width(1)?).map(|s| s + ";")
11731216
}
11741217

11751218
fn format_unit_struct(

0 commit comments

Comments
 (0)