2 ast::{self, edit_in_place::GenericParamsOwnerEdit, make, AstNode, HasName, HasTypeBounds},
6 use crate::{AssistContext, AssistId, AssistKind, Assists};
8 // Assist: move_bounds_to_where_clause
10 // Moves inline type bounds to a where clause.
13 // fn apply<T, U, $0F: FnOnce(T) -> U>(f: F, x: T) -> U {
19 // fn apply<T, U, F>(f: F, x: T) -> U where F: FnOnce(T) -> U {
23 pub(crate) fn move_bounds_to_where_clause(acc: &mut Assists, ctx: &AssistContext) -> Option<()> {
24 let type_param_list = ctx.find_node_at_offset::<ast::GenericParamList>()?;
26 let mut type_params = type_param_list.type_params();
27 if type_params.all(|p| p.type_bound_list().is_none()) {
31 let parent = type_param_list.syntax().parent()?;
33 let target = type_param_list.syntax().text_range();
35 AssistId("move_bounds_to_where_clause", AssistKind::RefactorRewrite),
36 "Move to where clause",
39 let type_param_list = edit.make_mut(type_param_list);
40 let parent = edit.make_syntax_mut(parent);
42 let where_clause: ast::WhereClause = match_ast! {
44 ast::Fn(it) => it.get_or_create_where_clause(),
45 ast::Trait(it) => it.get_or_create_where_clause(),
46 ast::Impl(it) => it.get_or_create_where_clause(),
47 ast::Enum(it) => it.get_or_create_where_clause(),
48 ast::Struct(it) => it.get_or_create_where_clause(),
53 for type_param in type_param_list.type_params() {
54 if let Some(tbl) = type_param.type_bound_list() {
55 if let Some(predicate) = build_predicate(type_param) {
56 where_clause.add_predicate(predicate)
65 fn build_predicate(param: ast::TypeParam) -> Option<ast::WherePred> {
66 let path = make::ext::ident_path(¶m.name()?.syntax().to_string());
67 let predicate = make::where_pred(path, param.type_bound_list()?.bounds());
68 Some(predicate.clone_for_update())
75 use crate::tests::check_assist;
78 fn move_bounds_to_where_clause_fn() {
80 move_bounds_to_where_clause,
81 r#"fn foo<T: u32, $0F: FnOnce(T) -> T>() {}"#,
82 r#"fn foo<T, F>() where T: u32, F: FnOnce(T) -> T {}"#,
87 fn move_bounds_to_where_clause_impl() {
89 move_bounds_to_where_clause,
90 r#"impl<U: u32, $0T> A<U, T> {}"#,
91 r#"impl<U, T> A<U, T> where U: u32 {}"#,
96 fn move_bounds_to_where_clause_struct() {
98 move_bounds_to_where_clause,
99 r#"struct A<$0T: Iterator<Item = u32>> {}"#,
100 r#"struct A<T> where T: Iterator<Item = u32> {}"#,
105 fn move_bounds_to_where_clause_tuple_struct() {
107 move_bounds_to_where_clause,
108 r#"struct Pair<$0T: u32>(T, T);"#,
109 r#"struct Pair<T>(T, T) where T: u32;"#,