2 ast::{self, edit::AstNodeEdit, make, AstNode, NameOwner, TypeBoundsOwner},
8 use crate::{AssistContext, AssistId, AssistKind, Assists};
10 // Assist: move_bounds_to_where_clause
12 // Moves inline type bounds to a where clause.
15 // fn apply<T, U, $0F: FnOnce(T) -> U>(f: F, x: T) -> U {
21 // fn apply<T, U, F>(f: F, x: T) -> U where F: FnOnce(T) -> U {
25 pub(crate) fn move_bounds_to_where_clause(acc: &mut Assists, ctx: &AssistContext) -> Option<()> {
26 let type_param_list = ctx.find_node_at_offset::<ast::GenericParamList>()?;
28 let mut type_params = type_param_list.type_params();
29 if type_params.all(|p| p.type_bound_list().is_none()) {
33 let parent = type_param_list.syntax().parent()?;
34 if parent.children_with_tokens().any(|it| it.kind() == WHERE_CLAUSE) {
38 let anchor = match_ast! {
40 ast::Fn(it) => it.body()?.syntax().clone().into(),
41 ast::Trait(it) => it.assoc_item_list()?.syntax().clone().into(),
42 ast::Impl(it) => it.assoc_item_list()?.syntax().clone().into(),
43 ast::Enum(it) => it.variant_list()?.syntax().clone().into(),
45 it.syntax().children_with_tokens()
46 .find(|it| it.kind() == RECORD_FIELD_LIST || it.kind() == T![;])?
52 let target = type_param_list.syntax().text_range();
54 AssistId("move_bounds_to_where_clause", AssistKind::RefactorRewrite),
55 "Move to where clause",
58 let new_params = type_param_list
60 .filter(|it| it.type_bound_list().is_some())
62 let without_bounds = type_param.remove_bounds();
63 (type_param, without_bounds)
66 let new_type_param_list = type_param_list.replace_descendants(new_params);
67 edit.replace_ast(type_param_list.clone(), new_type_param_list);
70 let predicates = type_param_list.type_params().filter_map(build_predicate);
71 make::where_clause(predicates)
74 let to_insert = match anchor.prev_sibling_or_token() {
75 Some(ref elem) if elem.kind() == WHITESPACE => {
76 format!("{} ", where_clause.syntax())
78 _ => format!(" {}", where_clause.syntax()),
80 edit.insert(anchor.text_range().start(), to_insert);
85 fn build_predicate(param: ast::TypeParam) -> Option<ast::WherePred> {
87 let name_ref = make::name_ref(¶m.name()?.syntax().to_string());
88 let segment = make::path_segment(name_ref);
89 make::path_unqualified(segment)
91 let predicate = make::where_pred(path, param.type_bound_list()?.bounds());
99 use crate::tests::check_assist;
102 fn move_bounds_to_where_clause_fn() {
104 move_bounds_to_where_clause,
106 fn foo<T: u32, $0F: FnOnce(T) -> T>() {}
109 fn foo<T, F>() where T: u32, F: FnOnce(T) -> T {}
115 fn move_bounds_to_where_clause_impl() {
117 move_bounds_to_where_clause,
119 impl<U: u32, $0T> A<U, T> {}
122 impl<U, T> A<U, T> where U: u32 {}
128 fn move_bounds_to_where_clause_struct() {
130 move_bounds_to_where_clause,
132 struct A<$0T: Iterator<Item = u32>> {}
135 struct A<T> where T: Iterator<Item = u32> {}
141 fn move_bounds_to_where_clause_tuple_struct() {
143 move_bounds_to_where_clause,
145 struct Pair<$0T: u32>(T, T);
148 struct Pair<T>(T, T) where T: u32;