2 ast::{self, edit_in_place::GenericParamsOwnerEdit, make, AstNode, NameOwner, TypeBoundsOwner},
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_ast_mut(type_param_list);
40 let parent = edit.make_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> {
67 let name_ref = make::name_ref(¶m.name()?.syntax().to_string());
68 let segment = make::path_segment(name_ref);
69 make::path_unqualified(segment)
71 let predicate = make::where_pred(path, param.type_bound_list()?.bounds());
72 Some(predicate.clone_for_update())
79 use crate::tests::check_assist;
82 fn move_bounds_to_where_clause_fn() {
84 move_bounds_to_where_clause,
85 r#"fn foo<T: u32, $0F: FnOnce(T) -> T>() {}"#,
86 r#"fn foo<T, F>() where T: u32, F: FnOnce(T) -> T {}"#,
91 fn move_bounds_to_where_clause_impl() {
93 move_bounds_to_where_clause,
94 r#"impl<U: u32, $0T> A<U, T> {}"#,
95 r#"impl<U, T> A<U, T> where U: u32 {}"#,
100 fn move_bounds_to_where_clause_struct() {
102 move_bounds_to_where_clause,
103 r#"struct A<$0T: Iterator<Item = u32>> {}"#,
104 r#"struct A<T> where T: Iterator<Item = u32> {}"#,
109 fn move_bounds_to_where_clause_tuple_struct() {
111 move_bounds_to_where_clause,
112 r#"struct Pair<$0T: u32>(T, T);"#,
113 r#"struct Pair<T>(T, T) where T: u32;"#,