aboutsummaryrefslogtreecommitdiff
path: root/crates/ra_assists/src/handlers
diff options
context:
space:
mode:
Diffstat (limited to 'crates/ra_assists/src/handlers')
-rw-r--r--crates/ra_assists/src/handlers/add_custom_impl.rs208
-rw-r--r--crates/ra_assists/src/handlers/add_explicit_type.rs211
-rw-r--r--crates/ra_assists/src/handlers/add_missing_impl_members.rs711
-rw-r--r--crates/ra_assists/src/handlers/add_turbo_fish.rs164
-rw-r--r--crates/ra_assists/src/handlers/apply_demorgan.rs93
-rw-r--r--crates/ra_assists/src/handlers/auto_import.rs1088
-rw-r--r--crates/ra_assists/src/handlers/change_return_type_to_result.rs998
-rw-r--r--crates/ra_assists/src/handlers/change_visibility.rs200
-rw-r--r--crates/ra_assists/src/handlers/early_return.rs515
-rw-r--r--crates/ra_assists/src/handlers/expand_glob_import.rs391
-rw-r--r--crates/ra_assists/src/handlers/extract_struct_from_enum_variant.rs317
-rw-r--r--crates/ra_assists/src/handlers/extract_variable.rs588
-rw-r--r--crates/ra_assists/src/handlers/fill_match_arms.rs747
-rw-r--r--crates/ra_assists/src/handlers/fix_visibility.rs607
-rw-r--r--crates/ra_assists/src/handlers/flip_binexpr.rs142
-rw-r--r--crates/ra_assists/src/handlers/flip_comma.rs84
-rw-r--r--crates/ra_assists/src/handlers/flip_trait_bound.rs121
-rw-r--r--crates/ra_assists/src/handlers/generate_derive.rs132
-rw-r--r--crates/ra_assists/src/handlers/generate_from_impl_for_enum.rs200
-rw-r--r--crates/ra_assists/src/handlers/generate_function.rs1058
-rw-r--r--crates/ra_assists/src/handlers/generate_impl.rs110
-rw-r--r--crates/ra_assists/src/handlers/generate_new.rs421
-rw-r--r--crates/ra_assists/src/handlers/inline_local_variable.rs695
-rw-r--r--crates/ra_assists/src/handlers/introduce_named_lifetime.rs318
-rw-r--r--crates/ra_assists/src/handlers/invert_if.rs109
-rw-r--r--crates/ra_assists/src/handlers/merge_imports.rs321
-rw-r--r--crates/ra_assists/src/handlers/merge_match_arms.rs248
-rw-r--r--crates/ra_assists/src/handlers/move_bounds.rs152
-rw-r--r--crates/ra_assists/src/handlers/move_guard.rs293
-rw-r--r--crates/ra_assists/src/handlers/raw_string.rs504
-rw-r--r--crates/ra_assists/src/handlers/remove_dbg.rs205
-rw-r--r--crates/ra_assists/src/handlers/remove_mut.rs37
-rw-r--r--crates/ra_assists/src/handlers/reorder_fields.rs220
-rw-r--r--crates/ra_assists/src/handlers/replace_if_let_with_match.rs257
-rw-r--r--crates/ra_assists/src/handlers/replace_let_with_if_let.rs100
-rw-r--r--crates/ra_assists/src/handlers/replace_qualified_name_with_use.rs688
-rw-r--r--crates/ra_assists/src/handlers/replace_unwrap_with_match.rs187
-rw-r--r--crates/ra_assists/src/handlers/split_import.rs79
-rw-r--r--crates/ra_assists/src/handlers/unwrap_block.rs517
39 files changed, 0 insertions, 14036 deletions
diff --git a/crates/ra_assists/src/handlers/add_custom_impl.rs b/crates/ra_assists/src/handlers/add_custom_impl.rs
deleted file mode 100644
index 8757fa33f..000000000
--- a/crates/ra_assists/src/handlers/add_custom_impl.rs
+++ /dev/null
@@ -1,208 +0,0 @@
1use itertools::Itertools;
2use syntax::{
3 ast::{self, AstNode},
4 Direction, SmolStr,
5 SyntaxKind::{IDENT, WHITESPACE},
6 TextRange, TextSize,
7};
8
9use crate::{
10 assist_context::{AssistContext, Assists},
11 AssistId, AssistKind,
12};
13
14// Assist: add_custom_impl
15//
16// Adds impl block for derived trait.
17//
18// ```
19// #[derive(Deb<|>ug, Display)]
20// struct S;
21// ```
22// ->
23// ```
24// #[derive(Display)]
25// struct S;
26//
27// impl Debug for S {
28// $0
29// }
30// ```
31pub(crate) fn add_custom_impl(acc: &mut Assists, ctx: &AssistContext) -> Option<()> {
32 let attr = ctx.find_node_at_offset::<ast::Attr>()?;
33 let input = attr.token_tree()?;
34
35 let attr_name = attr
36 .syntax()
37 .descendants_with_tokens()
38 .filter(|t| t.kind() == IDENT)
39 .find_map(|i| i.into_token())
40 .filter(|t| *t.text() == "derive")?
41 .text()
42 .clone();
43
44 let trait_token =
45 ctx.token_at_offset().find(|t| t.kind() == IDENT && *t.text() != attr_name)?;
46
47 let annotated = attr.syntax().siblings(Direction::Next).find_map(ast::Name::cast)?;
48 let annotated_name = annotated.syntax().text().to_string();
49 let start_offset = annotated.syntax().parent()?.text_range().end();
50
51 let label =
52 format!("Add custom impl `{}` for `{}`", trait_token.text().as_str(), annotated_name);
53
54 let target = attr.syntax().text_range();
55 acc.add(AssistId("add_custom_impl", AssistKind::Refactor), label, target, |builder| {
56 let new_attr_input = input
57 .syntax()
58 .descendants_with_tokens()
59 .filter(|t| t.kind() == IDENT)
60 .filter_map(|t| t.into_token().map(|t| t.text().clone()))
61 .filter(|t| t != trait_token.text())
62 .collect::<Vec<SmolStr>>();
63 let has_more_derives = !new_attr_input.is_empty();
64
65 if has_more_derives {
66 let new_attr_input = format!("({})", new_attr_input.iter().format(", "));
67 builder.replace(input.syntax().text_range(), new_attr_input);
68 } else {
69 let attr_range = attr.syntax().text_range();
70 builder.delete(attr_range);
71
72 let line_break_range = attr
73 .syntax()
74 .next_sibling_or_token()
75 .filter(|t| t.kind() == WHITESPACE)
76 .map(|t| t.text_range())
77 .unwrap_or_else(|| TextRange::new(TextSize::from(0), TextSize::from(0)));
78 builder.delete(line_break_range);
79 }
80
81 match ctx.config.snippet_cap {
82 Some(cap) => {
83 builder.insert_snippet(
84 cap,
85 start_offset,
86 format!("\n\nimpl {} for {} {{\n $0\n}}", trait_token, annotated_name),
87 );
88 }
89 None => {
90 builder.insert(
91 start_offset,
92 format!("\n\nimpl {} for {} {{\n\n}}", trait_token, annotated_name),
93 );
94 }
95 }
96 })
97}
98
99#[cfg(test)]
100mod tests {
101 use crate::tests::{check_assist, check_assist_not_applicable};
102
103 use super::*;
104
105 #[test]
106 fn add_custom_impl_for_unique_input() {
107 check_assist(
108 add_custom_impl,
109 "
110#[derive(Debu<|>g)]
111struct Foo {
112 bar: String,
113}
114 ",
115 "
116struct Foo {
117 bar: String,
118}
119
120impl Debug for Foo {
121 $0
122}
123 ",
124 )
125 }
126
127 #[test]
128 fn add_custom_impl_for_with_visibility_modifier() {
129 check_assist(
130 add_custom_impl,
131 "
132#[derive(Debug<|>)]
133pub struct Foo {
134 bar: String,
135}
136 ",
137 "
138pub struct Foo {
139 bar: String,
140}
141
142impl Debug for Foo {
143 $0
144}
145 ",
146 )
147 }
148
149 #[test]
150 fn add_custom_impl_when_multiple_inputs() {
151 check_assist(
152 add_custom_impl,
153 "
154#[derive(Display, Debug<|>, Serialize)]
155struct Foo {}
156 ",
157 "
158#[derive(Display, Serialize)]
159struct Foo {}
160
161impl Debug for Foo {
162 $0
163}
164 ",
165 )
166 }
167
168 #[test]
169 fn test_ignore_derive_macro_without_input() {
170 check_assist_not_applicable(
171 add_custom_impl,
172 "
173#[derive(<|>)]
174struct Foo {}
175 ",
176 )
177 }
178
179 #[test]
180 fn test_ignore_if_cursor_on_param() {
181 check_assist_not_applicable(
182 add_custom_impl,
183 "
184#[derive<|>(Debug)]
185struct Foo {}
186 ",
187 );
188
189 check_assist_not_applicable(
190 add_custom_impl,
191 "
192#[derive(Debug)<|>]
193struct Foo {}
194 ",
195 )
196 }
197
198 #[test]
199 fn test_ignore_if_not_derive() {
200 check_assist_not_applicable(
201 add_custom_impl,
202 "
203#[allow(non_camel_<|>case_types)]
204struct Foo {}
205 ",
206 )
207 }
208}
diff --git a/crates/ra_assists/src/handlers/add_explicit_type.rs b/crates/ra_assists/src/handlers/add_explicit_type.rs
deleted file mode 100644
index 563cbf505..000000000
--- a/crates/ra_assists/src/handlers/add_explicit_type.rs
+++ /dev/null
@@ -1,211 +0,0 @@
1use hir::HirDisplay;
2use syntax::{
3 ast::{self, AstNode, LetStmt, NameOwner},
4 TextRange,
5};
6
7use crate::{AssistContext, AssistId, AssistKind, Assists};
8
9// Assist: add_explicit_type
10//
11// Specify type for a let binding.
12//
13// ```
14// fn main() {
15// let x<|> = 92;
16// }
17// ```
18// ->
19// ```
20// fn main() {
21// let x: i32 = 92;
22// }
23// ```
24pub(crate) fn add_explicit_type(acc: &mut Assists, ctx: &AssistContext) -> Option<()> {
25 let let_stmt = ctx.find_node_at_offset::<LetStmt>()?;
26 let module = ctx.sema.scope(let_stmt.syntax()).module()?;
27 let expr = let_stmt.initializer()?;
28 // Must be a binding
29 let pat = match let_stmt.pat()? {
30 ast::Pat::IdentPat(bind_pat) => bind_pat,
31 _ => return None,
32 };
33 let pat_range = pat.syntax().text_range();
34 // The binding must have a name
35 let name = pat.name()?;
36 let name_range = name.syntax().text_range();
37 let stmt_range = let_stmt.syntax().text_range();
38 let eq_range = let_stmt.eq_token()?.text_range();
39 // Assist should only be applicable if cursor is between 'let' and '='
40 let let_range = TextRange::new(stmt_range.start(), eq_range.start());
41 let cursor_in_range = let_range.contains_range(ctx.frange.range);
42 if !cursor_in_range {
43 return None;
44 }
45 // Assist not applicable if the type has already been specified
46 // and it has no placeholders
47 let ascribed_ty = let_stmt.ty();
48 if let Some(ty) = &ascribed_ty {
49 if ty.syntax().descendants().find_map(ast::InferType::cast).is_none() {
50 return None;
51 }
52 }
53 // Infer type
54 let ty = ctx.sema.type_of_expr(&expr)?;
55
56 if ty.contains_unknown() || ty.is_closure() {
57 return None;
58 }
59
60 let inferred_type = ty.display_source_code(ctx.db(), module.into()).ok()?;
61 acc.add(
62 AssistId("add_explicit_type", AssistKind::RefactorRewrite),
63 format!("Insert explicit type `{}`", inferred_type),
64 pat_range,
65 |builder| match ascribed_ty {
66 Some(ascribed_ty) => {
67 builder.replace(ascribed_ty.syntax().text_range(), inferred_type);
68 }
69 None => {
70 builder.insert(name_range.end(), format!(": {}", inferred_type));
71 }
72 },
73 )
74}
75
76#[cfg(test)]
77mod tests {
78 use super::*;
79
80 use crate::tests::{check_assist, check_assist_not_applicable, check_assist_target};
81
82 #[test]
83 fn add_explicit_type_target() {
84 check_assist_target(add_explicit_type, "fn f() { let a<|> = 1; }", "a");
85 }
86
87 #[test]
88 fn add_explicit_type_works_for_simple_expr() {
89 check_assist(add_explicit_type, "fn f() { let a<|> = 1; }", "fn f() { let a: i32 = 1; }");
90 }
91
92 #[test]
93 fn add_explicit_type_works_for_underscore() {
94 check_assist(
95 add_explicit_type,
96 "fn f() { let a<|>: _ = 1; }",
97 "fn f() { let a: i32 = 1; }",
98 );
99 }
100
101 #[test]
102 fn add_explicit_type_works_for_nested_underscore() {
103 check_assist(
104 add_explicit_type,
105 r#"
106 enum Option<T> {
107 Some(T),
108 None
109 }
110
111 fn f() {
112 let a<|>: Option<_> = Option::Some(1);
113 }"#,
114 r#"
115 enum Option<T> {
116 Some(T),
117 None
118 }
119
120 fn f() {
121 let a: Option<i32> = Option::Some(1);
122 }"#,
123 );
124 }
125
126 #[test]
127 fn add_explicit_type_works_for_macro_call() {
128 check_assist(
129 add_explicit_type,
130 r"macro_rules! v { () => {0u64} } fn f() { let a<|> = v!(); }",
131 r"macro_rules! v { () => {0u64} } fn f() { let a: u64 = v!(); }",
132 );
133 }
134
135 #[test]
136 fn add_explicit_type_works_for_macro_call_recursive() {
137 check_assist(
138 add_explicit_type,
139 r#"macro_rules! u { () => {0u64} } macro_rules! v { () => {u!()} } fn f() { let a<|> = v!(); }"#,
140 r#"macro_rules! u { () => {0u64} } macro_rules! v { () => {u!()} } fn f() { let a: u64 = v!(); }"#,
141 );
142 }
143
144 #[test]
145 fn add_explicit_type_not_applicable_if_ty_not_inferred() {
146 check_assist_not_applicable(add_explicit_type, "fn f() { let a<|> = None; }");
147 }
148
149 #[test]
150 fn add_explicit_type_not_applicable_if_ty_already_specified() {
151 check_assist_not_applicable(add_explicit_type, "fn f() { let a<|>: i32 = 1; }");
152 }
153
154 #[test]
155 fn add_explicit_type_not_applicable_if_specified_ty_is_tuple() {
156 check_assist_not_applicable(add_explicit_type, "fn f() { let a<|>: (i32, i32) = (3, 4); }");
157 }
158
159 #[test]
160 fn add_explicit_type_not_applicable_if_cursor_after_equals() {
161 check_assist_not_applicable(
162 add_explicit_type,
163 "fn f() {let a =<|> match 1 {2 => 3, 3 => 5};}",
164 )
165 }
166
167 #[test]
168 fn add_explicit_type_not_applicable_if_cursor_before_let() {
169 check_assist_not_applicable(
170 add_explicit_type,
171 "fn f() <|>{let a = match 1 {2 => 3, 3 => 5};}",
172 )
173 }
174
175 #[test]
176 fn closure_parameters_are_not_added() {
177 check_assist_not_applicable(
178 add_explicit_type,
179 r#"
180fn main() {
181 let multiply_by_two<|> = |i| i * 3;
182 let six = multiply_by_two(2);
183}"#,
184 )
185 }
186
187 #[test]
188 fn default_generics_should_not_be_added() {
189 check_assist(
190 add_explicit_type,
191 r#"
192struct Test<K, T = u8> {
193 k: K,
194 t: T,
195}
196
197fn main() {
198 let test<|> = Test { t: 23u8, k: 33 };
199}"#,
200 r#"
201struct Test<K, T = u8> {
202 k: K,
203 t: T,
204}
205
206fn main() {
207 let test: Test<i32> = Test { t: 23u8, k: 33 };
208}"#,
209 );
210 }
211}
diff --git a/crates/ra_assists/src/handlers/add_missing_impl_members.rs b/crates/ra_assists/src/handlers/add_missing_impl_members.rs
deleted file mode 100644
index 81b61ebf8..000000000
--- a/crates/ra_assists/src/handlers/add_missing_impl_members.rs
+++ /dev/null
@@ -1,711 +0,0 @@
1use hir::HasSource;
2use syntax::{
3 ast::{
4 self,
5 edit::{self, AstNodeEdit, IndentLevel},
6 make, AstNode, NameOwner,
7 },
8 SmolStr,
9};
10
11use crate::{
12 assist_context::{AssistContext, Assists},
13 ast_transform::{self, AstTransform, QualifyPaths, SubstituteTypeParams},
14 utils::{get_missing_assoc_items, render_snippet, resolve_target_trait, Cursor},
15 AssistId, AssistKind,
16};
17
18#[derive(PartialEq)]
19enum AddMissingImplMembersMode {
20 DefaultMethodsOnly,
21 NoDefaultMethods,
22}
23
24// Assist: add_impl_missing_members
25//
26// Adds scaffold for required impl members.
27//
28// ```
29// trait Trait<T> {
30// Type X;
31// fn foo(&self) -> T;
32// fn bar(&self) {}
33// }
34//
35// impl Trait<u32> for () {<|>
36//
37// }
38// ```
39// ->
40// ```
41// trait Trait<T> {
42// Type X;
43// fn foo(&self) -> T;
44// fn bar(&self) {}
45// }
46//
47// impl Trait<u32> for () {
48// fn foo(&self) -> u32 {
49// ${0:todo!()}
50// }
51//
52// }
53// ```
54pub(crate) fn add_missing_impl_members(acc: &mut Assists, ctx: &AssistContext) -> Option<()> {
55 add_missing_impl_members_inner(
56 acc,
57 ctx,
58 AddMissingImplMembersMode::NoDefaultMethods,
59 "add_impl_missing_members",
60 "Implement missing members",
61 )
62}
63
64// Assist: add_impl_default_members
65//
66// Adds scaffold for overriding default impl members.
67//
68// ```
69// trait Trait {
70// Type X;
71// fn foo(&self);
72// fn bar(&self) {}
73// }
74//
75// impl Trait for () {
76// Type X = ();
77// fn foo(&self) {}<|>
78//
79// }
80// ```
81// ->
82// ```
83// trait Trait {
84// Type X;
85// fn foo(&self);
86// fn bar(&self) {}
87// }
88//
89// impl Trait for () {
90// Type X = ();
91// fn foo(&self) {}
92// $0fn bar(&self) {}
93//
94// }
95// ```
96pub(crate) fn add_missing_default_members(acc: &mut Assists, ctx: &AssistContext) -> Option<()> {
97 add_missing_impl_members_inner(
98 acc,
99 ctx,
100 AddMissingImplMembersMode::DefaultMethodsOnly,
101 "add_impl_default_members",
102 "Implement default members",
103 )
104}
105
106fn add_missing_impl_members_inner(
107 acc: &mut Assists,
108 ctx: &AssistContext,
109 mode: AddMissingImplMembersMode,
110 assist_id: &'static str,
111 label: &'static str,
112) -> Option<()> {
113 let _p = profile::span("add_missing_impl_members_inner");
114 let impl_def = ctx.find_node_at_offset::<ast::Impl>()?;
115 let impl_item_list = impl_def.assoc_item_list()?;
116
117 let trait_ = resolve_target_trait(&ctx.sema, &impl_def)?;
118
119 let def_name = |item: &ast::AssocItem| -> Option<SmolStr> {
120 match item {
121 ast::AssocItem::Fn(def) => def.name(),
122 ast::AssocItem::TypeAlias(def) => def.name(),
123 ast::AssocItem::Const(def) => def.name(),
124 ast::AssocItem::MacroCall(_) => None,
125 }
126 .map(|it| it.text().clone())
127 };
128
129 let missing_items = get_missing_assoc_items(&ctx.sema, &impl_def)
130 .iter()
131 .map(|i| match i {
132 hir::AssocItem::Function(i) => ast::AssocItem::Fn(i.source(ctx.db()).value),
133 hir::AssocItem::TypeAlias(i) => ast::AssocItem::TypeAlias(i.source(ctx.db()).value),
134 hir::AssocItem::Const(i) => ast::AssocItem::Const(i.source(ctx.db()).value),
135 })
136 .filter(|t| def_name(&t).is_some())
137 .filter(|t| match t {
138 ast::AssocItem::Fn(def) => match mode {
139 AddMissingImplMembersMode::DefaultMethodsOnly => def.body().is_some(),
140 AddMissingImplMembersMode::NoDefaultMethods => def.body().is_none(),
141 },
142 _ => mode == AddMissingImplMembersMode::NoDefaultMethods,
143 })
144 .collect::<Vec<_>>();
145
146 if missing_items.is_empty() {
147 return None;
148 }
149
150 let target = impl_def.syntax().text_range();
151 acc.add(AssistId(assist_id, AssistKind::QuickFix), label, target, |builder| {
152 let n_existing_items = impl_item_list.assoc_items().count();
153 let source_scope = ctx.sema.scope_for_def(trait_);
154 let target_scope = ctx.sema.scope(impl_item_list.syntax());
155 let ast_transform = QualifyPaths::new(&target_scope, &source_scope)
156 .or(SubstituteTypeParams::for_trait_impl(&source_scope, trait_, impl_def));
157 let items = missing_items
158 .into_iter()
159 .map(|it| ast_transform::apply(&*ast_transform, it))
160 .map(|it| match it {
161 ast::AssocItem::Fn(def) => ast::AssocItem::Fn(add_body(def)),
162 ast::AssocItem::TypeAlias(def) => ast::AssocItem::TypeAlias(def.remove_bounds()),
163 _ => it,
164 })
165 .map(|it| edit::remove_attrs_and_docs(&it));
166 let new_impl_item_list = impl_item_list.append_items(items);
167 let first_new_item = new_impl_item_list.assoc_items().nth(n_existing_items).unwrap();
168
169 let original_range = impl_item_list.syntax().text_range();
170 match ctx.config.snippet_cap {
171 None => builder.replace(original_range, new_impl_item_list.to_string()),
172 Some(cap) => {
173 let mut cursor = Cursor::Before(first_new_item.syntax());
174 let placeholder;
175 if let ast::AssocItem::Fn(func) = &first_new_item {
176 if let Some(m) = func.syntax().descendants().find_map(ast::MacroCall::cast) {
177 if m.syntax().text() == "todo!()" {
178 placeholder = m;
179 cursor = Cursor::Replace(placeholder.syntax());
180 }
181 }
182 }
183 builder.replace_snippet(
184 cap,
185 original_range,
186 render_snippet(cap, new_impl_item_list.syntax(), cursor),
187 )
188 }
189 };
190 })
191}
192
193fn add_body(fn_def: ast::Fn) -> ast::Fn {
194 if fn_def.body().is_some() {
195 return fn_def;
196 }
197 let body = make::block_expr(None, Some(make::expr_todo())).indent(IndentLevel(1));
198 fn_def.with_body(body)
199}
200
201#[cfg(test)]
202mod tests {
203 use crate::tests::{check_assist, check_assist_not_applicable};
204
205 use super::*;
206
207 #[test]
208 fn test_add_missing_impl_members() {
209 check_assist(
210 add_missing_impl_members,
211 r#"
212trait Foo {
213 type Output;
214
215 const CONST: usize = 42;
216
217 fn foo(&self);
218 fn bar(&self);
219 fn baz(&self);
220}
221
222struct S;
223
224impl Foo for S {
225 fn bar(&self) {}
226<|>
227}"#,
228 r#"
229trait Foo {
230 type Output;
231
232 const CONST: usize = 42;
233
234 fn foo(&self);
235 fn bar(&self);
236 fn baz(&self);
237}
238
239struct S;
240
241impl Foo for S {
242 fn bar(&self) {}
243 $0type Output;
244 const CONST: usize = 42;
245 fn foo(&self) {
246 todo!()
247 }
248 fn baz(&self) {
249 todo!()
250 }
251
252}"#,
253 );
254 }
255
256 #[test]
257 fn test_copied_overriden_members() {
258 check_assist(
259 add_missing_impl_members,
260 r#"
261trait Foo {
262 fn foo(&self);
263 fn bar(&self) -> bool { true }
264 fn baz(&self) -> u32 { 42 }
265}
266
267struct S;
268
269impl Foo for S {
270 fn bar(&self) {}
271<|>
272}"#,
273 r#"
274trait Foo {
275 fn foo(&self);
276 fn bar(&self) -> bool { true }
277 fn baz(&self) -> u32 { 42 }
278}
279
280struct S;
281
282impl Foo for S {
283 fn bar(&self) {}
284 fn foo(&self) {
285 ${0:todo!()}
286 }
287
288}"#,
289 );
290 }
291
292 #[test]
293 fn test_empty_impl_def() {
294 check_assist(
295 add_missing_impl_members,
296 r#"
297trait Foo { fn foo(&self); }
298struct S;
299impl Foo for S { <|> }"#,
300 r#"
301trait Foo { fn foo(&self); }
302struct S;
303impl Foo for S {
304 fn foo(&self) {
305 ${0:todo!()}
306 }
307}"#,
308 );
309 }
310
311 #[test]
312 fn fill_in_type_params_1() {
313 check_assist(
314 add_missing_impl_members,
315 r#"
316trait Foo<T> { fn foo(&self, t: T) -> &T; }
317struct S;
318impl Foo<u32> for S { <|> }"#,
319 r#"
320trait Foo<T> { fn foo(&self, t: T) -> &T; }
321struct S;
322impl Foo<u32> for S {
323 fn foo(&self, t: u32) -> &u32 {
324 ${0:todo!()}
325 }
326}"#,
327 );
328 }
329
330 #[test]
331 fn fill_in_type_params_2() {
332 check_assist(
333 add_missing_impl_members,
334 r#"
335trait Foo<T> { fn foo(&self, t: T) -> &T; }
336struct S;
337impl<U> Foo<U> for S { <|> }"#,
338 r#"
339trait Foo<T> { fn foo(&self, t: T) -> &T; }
340struct S;
341impl<U> Foo<U> for S {
342 fn foo(&self, t: U) -> &U {
343 ${0:todo!()}
344 }
345}"#,
346 );
347 }
348
349 #[test]
350 fn test_cursor_after_empty_impl_def() {
351 check_assist(
352 add_missing_impl_members,
353 r#"
354trait Foo { fn foo(&self); }
355struct S;
356impl Foo for S {}<|>"#,
357 r#"
358trait Foo { fn foo(&self); }
359struct S;
360impl Foo for S {
361 fn foo(&self) {
362 ${0:todo!()}
363 }
364}"#,
365 )
366 }
367
368 #[test]
369 fn test_qualify_path_1() {
370 check_assist(
371 add_missing_impl_members,
372 r#"
373mod foo {
374 pub struct Bar;
375 trait Foo { fn foo(&self, bar: Bar); }
376}
377struct S;
378impl foo::Foo for S { <|> }"#,
379 r#"
380mod foo {
381 pub struct Bar;
382 trait Foo { fn foo(&self, bar: Bar); }
383}
384struct S;
385impl foo::Foo for S {
386 fn foo(&self, bar: foo::Bar) {
387 ${0:todo!()}
388 }
389}"#,
390 );
391 }
392
393 #[test]
394 fn test_qualify_path_generic() {
395 check_assist(
396 add_missing_impl_members,
397 r#"
398mod foo {
399 pub struct Bar<T>;
400 trait Foo { fn foo(&self, bar: Bar<u32>); }
401}
402struct S;
403impl foo::Foo for S { <|> }"#,
404 r#"
405mod foo {
406 pub struct Bar<T>;
407 trait Foo { fn foo(&self, bar: Bar<u32>); }
408}
409struct S;
410impl foo::Foo for S {
411 fn foo(&self, bar: foo::Bar<u32>) {
412 ${0:todo!()}
413 }
414}"#,
415 );
416 }
417
418 #[test]
419 fn test_qualify_path_and_substitute_param() {
420 check_assist(
421 add_missing_impl_members,
422 r#"
423mod foo {
424 pub struct Bar<T>;
425 trait Foo<T> { fn foo(&self, bar: Bar<T>); }
426}
427struct S;
428impl foo::Foo<u32> for S { <|> }"#,
429 r#"
430mod foo {
431 pub struct Bar<T>;
432 trait Foo<T> { fn foo(&self, bar: Bar<T>); }
433}
434struct S;
435impl foo::Foo<u32> for S {
436 fn foo(&self, bar: foo::Bar<u32>) {
437 ${0:todo!()}
438 }
439}"#,
440 );
441 }
442
443 #[test]
444 fn test_substitute_param_no_qualify() {
445 // when substituting params, the substituted param should not be qualified!
446 check_assist(
447 add_missing_impl_members,
448 r#"
449mod foo {
450 trait Foo<T> { fn foo(&self, bar: T); }
451 pub struct Param;
452}
453struct Param;
454struct S;
455impl foo::Foo<Param> for S { <|> }"#,
456 r#"
457mod foo {
458 trait Foo<T> { fn foo(&self, bar: T); }
459 pub struct Param;
460}
461struct Param;
462struct S;
463impl foo::Foo<Param> for S {
464 fn foo(&self, bar: Param) {
465 ${0:todo!()}
466 }
467}"#,
468 );
469 }
470
471 #[test]
472 fn test_qualify_path_associated_item() {
473 check_assist(
474 add_missing_impl_members,
475 r#"
476mod foo {
477 pub struct Bar<T>;
478 impl Bar<T> { type Assoc = u32; }
479 trait Foo { fn foo(&self, bar: Bar<u32>::Assoc); }
480}
481struct S;
482impl foo::Foo for S { <|> }"#,
483 r#"
484mod foo {
485 pub struct Bar<T>;
486 impl Bar<T> { type Assoc = u32; }
487 trait Foo { fn foo(&self, bar: Bar<u32>::Assoc); }
488}
489struct S;
490impl foo::Foo for S {
491 fn foo(&self, bar: foo::Bar<u32>::Assoc) {
492 ${0:todo!()}
493 }
494}"#,
495 );
496 }
497
498 #[test]
499 fn test_qualify_path_nested() {
500 check_assist(
501 add_missing_impl_members,
502 r#"
503mod foo {
504 pub struct Bar<T>;
505 pub struct Baz;
506 trait Foo { fn foo(&self, bar: Bar<Baz>); }
507}
508struct S;
509impl foo::Foo for S { <|> }"#,
510 r#"
511mod foo {
512 pub struct Bar<T>;
513 pub struct Baz;
514 trait Foo { fn foo(&self, bar: Bar<Baz>); }
515}
516struct S;
517impl foo::Foo for S {
518 fn foo(&self, bar: foo::Bar<foo::Baz>) {
519 ${0:todo!()}
520 }
521}"#,
522 );
523 }
524
525 #[test]
526 fn test_qualify_path_fn_trait_notation() {
527 check_assist(
528 add_missing_impl_members,
529 r#"
530mod foo {
531 pub trait Fn<Args> { type Output; }
532 trait Foo { fn foo(&self, bar: dyn Fn(u32) -> i32); }
533}
534struct S;
535impl foo::Foo for S { <|> }"#,
536 r#"
537mod foo {
538 pub trait Fn<Args> { type Output; }
539 trait Foo { fn foo(&self, bar: dyn Fn(u32) -> i32); }
540}
541struct S;
542impl foo::Foo for S {
543 fn foo(&self, bar: dyn Fn(u32) -> i32) {
544 ${0:todo!()}
545 }
546}"#,
547 );
548 }
549
550 #[test]
551 fn test_empty_trait() {
552 check_assist_not_applicable(
553 add_missing_impl_members,
554 r#"
555trait Foo;
556struct S;
557impl Foo for S { <|> }"#,
558 )
559 }
560
561 #[test]
562 fn test_ignore_unnamed_trait_members_and_default_methods() {
563 check_assist_not_applicable(
564 add_missing_impl_members,
565 r#"
566trait Foo {
567 fn (arg: u32);
568 fn valid(some: u32) -> bool { false }
569}
570struct S;
571impl Foo for S { <|> }"#,
572 )
573 }
574
575 #[test]
576 fn test_with_docstring_and_attrs() {
577 check_assist(
578 add_missing_impl_members,
579 r#"
580#[doc(alias = "test alias")]
581trait Foo {
582 /// doc string
583 type Output;
584
585 #[must_use]
586 fn foo(&self);
587}
588struct S;
589impl Foo for S {}<|>"#,
590 r#"
591#[doc(alias = "test alias")]
592trait Foo {
593 /// doc string
594 type Output;
595
596 #[must_use]
597 fn foo(&self);
598}
599struct S;
600impl Foo for S {
601 $0type Output;
602 fn foo(&self) {
603 todo!()
604 }
605}"#,
606 )
607 }
608
609 #[test]
610 fn test_default_methods() {
611 check_assist(
612 add_missing_default_members,
613 r#"
614trait Foo {
615 type Output;
616
617 const CONST: usize = 42;
618
619 fn valid(some: u32) -> bool { false }
620 fn foo(some: u32) -> bool;
621}
622struct S;
623impl Foo for S { <|> }"#,
624 r#"
625trait Foo {
626 type Output;
627
628 const CONST: usize = 42;
629
630 fn valid(some: u32) -> bool { false }
631 fn foo(some: u32) -> bool;
632}
633struct S;
634impl Foo for S {
635 $0fn valid(some: u32) -> bool { false }
636}"#,
637 )
638 }
639
640 #[test]
641 fn test_generic_single_default_parameter() {
642 check_assist(
643 add_missing_impl_members,
644 r#"
645trait Foo<T = Self> {
646 fn bar(&self, other: &T);
647}
648
649struct S;
650impl Foo for S { <|> }"#,
651 r#"
652trait Foo<T = Self> {
653 fn bar(&self, other: &T);
654}
655
656struct S;
657impl Foo for S {
658 fn bar(&self, other: &Self) {
659 ${0:todo!()}
660 }
661}"#,
662 )
663 }
664
665 #[test]
666 fn test_generic_default_parameter_is_second() {
667 check_assist(
668 add_missing_impl_members,
669 r#"
670trait Foo<T1, T2 = Self> {
671 fn bar(&self, this: &T1, that: &T2);
672}
673
674struct S<T>;
675impl Foo<T> for S<T> { <|> }"#,
676 r#"
677trait Foo<T1, T2 = Self> {
678 fn bar(&self, this: &T1, that: &T2);
679}
680
681struct S<T>;
682impl Foo<T> for S<T> {
683 fn bar(&self, this: &T, that: &Self) {
684 ${0:todo!()}
685 }
686}"#,
687 )
688 }
689
690 #[test]
691 fn test_assoc_type_bounds_are_removed() {
692 check_assist(
693 add_missing_impl_members,
694 r#"
695trait Tr {
696 type Ty: Copy + 'static;
697}
698
699impl Tr for ()<|> {
700}"#,
701 r#"
702trait Tr {
703 type Ty: Copy + 'static;
704}
705
706impl Tr for () {
707 $0type Ty;
708}"#,
709 )
710 }
711}
diff --git a/crates/ra_assists/src/handlers/add_turbo_fish.rs b/crates/ra_assists/src/handlers/add_turbo_fish.rs
deleted file mode 100644
index f4f997d8e..000000000
--- a/crates/ra_assists/src/handlers/add_turbo_fish.rs
+++ /dev/null
@@ -1,164 +0,0 @@
1use ide_db::defs::{classify_name_ref, Definition, NameRefClass};
2use syntax::{ast, AstNode, SyntaxKind, T};
3use test_utils::mark;
4
5use crate::{
6 assist_context::{AssistContext, Assists},
7 AssistId, AssistKind,
8};
9
10// Assist: add_turbo_fish
11//
12// Adds `::<_>` to a call of a generic method or function.
13//
14// ```
15// fn make<T>() -> T { todo!() }
16// fn main() {
17// let x = make<|>();
18// }
19// ```
20// ->
21// ```
22// fn make<T>() -> T { todo!() }
23// fn main() {
24// let x = make::<${0:_}>();
25// }
26// ```
27pub(crate) fn add_turbo_fish(acc: &mut Assists, ctx: &AssistContext) -> Option<()> {
28 let ident = ctx.find_token_at_offset(SyntaxKind::IDENT).or_else(|| {
29 let arg_list = ctx.find_node_at_offset::<ast::ArgList>()?;
30 if arg_list.args().count() > 0 {
31 return None;
32 }
33 mark::hit!(add_turbo_fish_after_call);
34 arg_list.l_paren_token()?.prev_token().filter(|it| it.kind() == SyntaxKind::IDENT)
35 })?;
36 let next_token = ident.next_token()?;
37 if next_token.kind() == T![::] {
38 mark::hit!(add_turbo_fish_one_fish_is_enough);
39 return None;
40 }
41 let name_ref = ast::NameRef::cast(ident.parent())?;
42 let def = match classify_name_ref(&ctx.sema, &name_ref)? {
43 NameRefClass::Definition(def) => def,
44 NameRefClass::ExternCrate(_) | NameRefClass::FieldShorthand { .. } => return None,
45 };
46 let fun = match def {
47 Definition::ModuleDef(hir::ModuleDef::Function(it)) => it,
48 _ => return None,
49 };
50 let generics = hir::GenericDef::Function(fun).params(ctx.sema.db);
51 if generics.is_empty() {
52 mark::hit!(add_turbo_fish_non_generic);
53 return None;
54 }
55 acc.add(
56 AssistId("add_turbo_fish", AssistKind::RefactorRewrite),
57 "Add `::<>`",
58 ident.text_range(),
59 |builder| match ctx.config.snippet_cap {
60 Some(cap) => builder.insert_snippet(cap, ident.text_range().end(), "::<${0:_}>"),
61 None => builder.insert(ident.text_range().end(), "::<_>"),
62 },
63 )
64}
65
66#[cfg(test)]
67mod tests {
68 use crate::tests::{check_assist, check_assist_not_applicable};
69
70 use super::*;
71 use test_utils::mark;
72
73 #[test]
74 fn add_turbo_fish_function() {
75 check_assist(
76 add_turbo_fish,
77 r#"
78fn make<T>() -> T {}
79fn main() {
80 make<|>();
81}
82"#,
83 r#"
84fn make<T>() -> T {}
85fn main() {
86 make::<${0:_}>();
87}
88"#,
89 );
90 }
91
92 #[test]
93 fn add_turbo_fish_after_call() {
94 mark::check!(add_turbo_fish_after_call);
95 check_assist(
96 add_turbo_fish,
97 r#"
98fn make<T>() -> T {}
99fn main() {
100 make()<|>;
101}
102"#,
103 r#"
104fn make<T>() -> T {}
105fn main() {
106 make::<${0:_}>();
107}
108"#,
109 );
110 }
111
112 #[test]
113 fn add_turbo_fish_method() {
114 check_assist(
115 add_turbo_fish,
116 r#"
117struct S;
118impl S {
119 fn make<T>(&self) -> T {}
120}
121fn main() {
122 S.make<|>();
123}
124"#,
125 r#"
126struct S;
127impl S {
128 fn make<T>(&self) -> T {}
129}
130fn main() {
131 S.make::<${0:_}>();
132}
133"#,
134 );
135 }
136
137 #[test]
138 fn add_turbo_fish_one_fish_is_enough() {
139 mark::check!(add_turbo_fish_one_fish_is_enough);
140 check_assist_not_applicable(
141 add_turbo_fish,
142 r#"
143fn make<T>() -> T {}
144fn main() {
145 make<|>::<()>();
146}
147"#,
148 );
149 }
150
151 #[test]
152 fn add_turbo_fish_non_generic() {
153 mark::check!(add_turbo_fish_non_generic);
154 check_assist_not_applicable(
155 add_turbo_fish,
156 r#"
157fn make() -> () {}
158fn main() {
159 make<|>();
160}
161"#,
162 );
163 }
164}
diff --git a/crates/ra_assists/src/handlers/apply_demorgan.rs b/crates/ra_assists/src/handlers/apply_demorgan.rs
deleted file mode 100644
index 1a6fdafda..000000000
--- a/crates/ra_assists/src/handlers/apply_demorgan.rs
+++ /dev/null
@@ -1,93 +0,0 @@
1use syntax::ast::{self, AstNode};
2
3use crate::{utils::invert_boolean_expression, AssistContext, AssistId, AssistKind, Assists};
4
5// Assist: apply_demorgan
6//
7// Apply https://en.wikipedia.org/wiki/De_Morgan%27s_laws[De Morgan's law].
8// This transforms expressions of the form `!l || !r` into `!(l && r)`.
9// This also works with `&&`. This assist can only be applied with the cursor
10// on either `||` or `&&`, with both operands being a negation of some kind.
11// This means something of the form `!x` or `x != y`.
12//
13// ```
14// fn main() {
15// if x != 4 ||<|> !y {}
16// }
17// ```
18// ->
19// ```
20// fn main() {
21// if !(x == 4 && y) {}
22// }
23// ```
24pub(crate) fn apply_demorgan(acc: &mut Assists, ctx: &AssistContext) -> Option<()> {
25 let expr = ctx.find_node_at_offset::<ast::BinExpr>()?;
26 let op = expr.op_kind()?;
27 let op_range = expr.op_token()?.text_range();
28 let opposite_op = opposite_logic_op(op)?;
29 let cursor_in_range = op_range.contains_range(ctx.frange.range);
30 if !cursor_in_range {
31 return None;
32 }
33
34 let lhs = expr.lhs()?;
35 let lhs_range = lhs.syntax().text_range();
36 let not_lhs = invert_boolean_expression(lhs);
37
38 let rhs = expr.rhs()?;
39 let rhs_range = rhs.syntax().text_range();
40 let not_rhs = invert_boolean_expression(rhs);
41
42 acc.add(
43 AssistId("apply_demorgan", AssistKind::RefactorRewrite),
44 "Apply De Morgan's law",
45 op_range,
46 |edit| {
47 edit.replace(op_range, opposite_op);
48 edit.replace(lhs_range, format!("!({}", not_lhs.syntax().text()));
49 edit.replace(rhs_range, format!("{})", not_rhs.syntax().text()));
50 },
51 )
52}
53
54// Return the opposite text for a given logical operator, if it makes sense
55fn opposite_logic_op(kind: ast::BinOp) -> Option<&'static str> {
56 match kind {
57 ast::BinOp::BooleanOr => Some("&&"),
58 ast::BinOp::BooleanAnd => Some("||"),
59 _ => None,
60 }
61}
62
63#[cfg(test)]
64mod tests {
65 use super::*;
66
67 use crate::tests::{check_assist, check_assist_not_applicable};
68
69 #[test]
70 fn demorgan_turns_and_into_or() {
71 check_assist(apply_demorgan, "fn f() { !x &&<|> !x }", "fn f() { !(x || x) }")
72 }
73
74 #[test]
75 fn demorgan_turns_or_into_and() {
76 check_assist(apply_demorgan, "fn f() { !x ||<|> !x }", "fn f() { !(x && x) }")
77 }
78
79 #[test]
80 fn demorgan_removes_inequality() {
81 check_assist(apply_demorgan, "fn f() { x != x ||<|> !x }", "fn f() { !(x == x && x) }")
82 }
83
84 #[test]
85 fn demorgan_general_case() {
86 check_assist(apply_demorgan, "fn f() { x ||<|> x }", "fn f() { !(!x && !x) }")
87 }
88
89 #[test]
90 fn demorgan_doesnt_apply_with_cursor_not_on_op() {
91 check_assist_not_applicable(apply_demorgan, "fn f() { <|> !x || !x }")
92 }
93}
diff --git a/crates/ra_assists/src/handlers/auto_import.rs b/crates/ra_assists/src/handlers/auto_import.rs
deleted file mode 100644
index cce789972..000000000
--- a/crates/ra_assists/src/handlers/auto_import.rs
+++ /dev/null
@@ -1,1088 +0,0 @@
1use std::collections::BTreeSet;
2
3use either::Either;
4use hir::{
5 AsAssocItem, AssocItemContainer, ModPath, Module, ModuleDef, PathResolution, Semantics, Trait,
6 Type,
7};
8use ide_db::{imports_locator, RootDatabase};
9use rustc_hash::FxHashSet;
10use syntax::{
11 ast::{self, AstNode},
12 SyntaxNode,
13};
14
15use crate::{
16 utils::insert_use_statement, AssistContext, AssistId, AssistKind, Assists, GroupLabel,
17};
18
19// Assist: auto_import
20//
21// If the name is unresolved, provides all possible imports for it.
22//
23// ```
24// fn main() {
25// let map = HashMap<|>::new();
26// }
27// # pub mod std { pub mod collections { pub struct HashMap { } } }
28// ```
29// ->
30// ```
31// use std::collections::HashMap;
32//
33// fn main() {
34// let map = HashMap::new();
35// }
36// # pub mod std { pub mod collections { pub struct HashMap { } } }
37// ```
38pub(crate) fn auto_import(acc: &mut Assists, ctx: &AssistContext) -> Option<()> {
39 let auto_import_assets = AutoImportAssets::new(ctx)?;
40 let proposed_imports = auto_import_assets.search_for_imports(ctx);
41 if proposed_imports.is_empty() {
42 return None;
43 }
44
45 let range = ctx.sema.original_range(&auto_import_assets.syntax_under_caret).range;
46 let group = auto_import_assets.get_import_group_message();
47 for import in proposed_imports {
48 acc.add_group(
49 &group,
50 AssistId("auto_import", AssistKind::QuickFix),
51 format!("Import `{}`", &import),
52 range,
53 |builder| {
54 insert_use_statement(
55 &auto_import_assets.syntax_under_caret,
56 &import,
57 ctx,
58 builder.text_edit_builder(),
59 );
60 },
61 );
62 }
63 Some(())
64}
65
66#[derive(Debug)]
67struct AutoImportAssets {
68 import_candidate: ImportCandidate,
69 module_with_name_to_import: Module,
70 syntax_under_caret: SyntaxNode,
71}
72
73impl AutoImportAssets {
74 fn new(ctx: &AssistContext) -> Option<Self> {
75 if let Some(path_under_caret) = ctx.find_node_at_offset_with_descend::<ast::Path>() {
76 Self::for_regular_path(path_under_caret, &ctx)
77 } else {
78 Self::for_method_call(ctx.find_node_at_offset_with_descend()?, &ctx)
79 }
80 }
81
82 fn for_method_call(method_call: ast::MethodCallExpr, ctx: &AssistContext) -> Option<Self> {
83 let syntax_under_caret = method_call.syntax().to_owned();
84 let module_with_name_to_import = ctx.sema.scope(&syntax_under_caret).module()?;
85 Some(Self {
86 import_candidate: ImportCandidate::for_method_call(&ctx.sema, &method_call)?,
87 module_with_name_to_import,
88 syntax_under_caret,
89 })
90 }
91
92 fn for_regular_path(path_under_caret: ast::Path, ctx: &AssistContext) -> Option<Self> {
93 let syntax_under_caret = path_under_caret.syntax().to_owned();
94 if syntax_under_caret.ancestors().find_map(ast::Use::cast).is_some() {
95 return None;
96 }
97
98 let module_with_name_to_import = ctx.sema.scope(&syntax_under_caret).module()?;
99 Some(Self {
100 import_candidate: ImportCandidate::for_regular_path(&ctx.sema, &path_under_caret)?,
101 module_with_name_to_import,
102 syntax_under_caret,
103 })
104 }
105
106 fn get_search_query(&self) -> &str {
107 match &self.import_candidate {
108 ImportCandidate::UnqualifiedName(name) => name,
109 ImportCandidate::QualifierStart(qualifier_start) => qualifier_start,
110 ImportCandidate::TraitAssocItem(_, trait_assoc_item_name) => trait_assoc_item_name,
111 ImportCandidate::TraitMethod(_, trait_method_name) => trait_method_name,
112 }
113 }
114
115 fn get_import_group_message(&self) -> GroupLabel {
116 let name = match &self.import_candidate {
117 ImportCandidate::UnqualifiedName(name) => format!("Import {}", name),
118 ImportCandidate::QualifierStart(qualifier_start) => {
119 format!("Import {}", qualifier_start)
120 }
121 ImportCandidate::TraitAssocItem(_, trait_assoc_item_name) => {
122 format!("Import a trait for item {}", trait_assoc_item_name)
123 }
124 ImportCandidate::TraitMethod(_, trait_method_name) => {
125 format!("Import a trait for method {}", trait_method_name)
126 }
127 };
128 GroupLabel(name)
129 }
130
131 fn search_for_imports(&self, ctx: &AssistContext) -> BTreeSet<ModPath> {
132 let _p = profile::span("auto_import::search_for_imports");
133 let db = ctx.db();
134 let current_crate = self.module_with_name_to_import.krate();
135 imports_locator::find_imports(&ctx.sema, current_crate, &self.get_search_query())
136 .into_iter()
137 .filter_map(|candidate| match &self.import_candidate {
138 ImportCandidate::TraitAssocItem(assoc_item_type, _) => {
139 let located_assoc_item = match candidate {
140 Either::Left(ModuleDef::Function(located_function)) => located_function
141 .as_assoc_item(db)
142 .map(|assoc| assoc.container(db))
143 .and_then(Self::assoc_to_trait),
144 Either::Left(ModuleDef::Const(located_const)) => located_const
145 .as_assoc_item(db)
146 .map(|assoc| assoc.container(db))
147 .and_then(Self::assoc_to_trait),
148 _ => None,
149 }?;
150
151 let mut trait_candidates = FxHashSet::default();
152 trait_candidates.insert(located_assoc_item.into());
153
154 assoc_item_type
155 .iterate_path_candidates(
156 db,
157 current_crate,
158 &trait_candidates,
159 None,
160 |_, assoc| Self::assoc_to_trait(assoc.container(db)),
161 )
162 .map(ModuleDef::from)
163 .map(Either::Left)
164 }
165 ImportCandidate::TraitMethod(function_callee, _) => {
166 let located_assoc_item =
167 if let Either::Left(ModuleDef::Function(located_function)) = candidate {
168 located_function
169 .as_assoc_item(db)
170 .map(|assoc| assoc.container(db))
171 .and_then(Self::assoc_to_trait)
172 } else {
173 None
174 }?;
175
176 let mut trait_candidates = FxHashSet::default();
177 trait_candidates.insert(located_assoc_item.into());
178
179 function_callee
180 .iterate_method_candidates(
181 db,
182 current_crate,
183 &trait_candidates,
184 None,
185 |_, function| {
186 Self::assoc_to_trait(function.as_assoc_item(db)?.container(db))
187 },
188 )
189 .map(ModuleDef::from)
190 .map(Either::Left)
191 }
192 _ => Some(candidate),
193 })
194 .filter_map(|candidate| match candidate {
195 Either::Left(module_def) => {
196 self.module_with_name_to_import.find_use_path(db, module_def)
197 }
198 Either::Right(macro_def) => {
199 self.module_with_name_to_import.find_use_path(db, macro_def)
200 }
201 })
202 .filter(|use_path| !use_path.segments.is_empty())
203 .take(20)
204 .collect::<BTreeSet<_>>()
205 }
206
207 fn assoc_to_trait(assoc: AssocItemContainer) -> Option<Trait> {
208 if let AssocItemContainer::Trait(extracted_trait) = assoc {
209 Some(extracted_trait)
210 } else {
211 None
212 }
213 }
214}
215
216#[derive(Debug)]
217enum ImportCandidate {
218 /// Simple name like 'HashMap'
219 UnqualifiedName(String),
220 /// First part of the qualified name.
221 /// For 'std::collections::HashMap', that will be 'std'.
222 QualifierStart(String),
223 /// A trait associated function (with no self parameter) or associated constant.
224 /// For 'test_mod::TestEnum::test_function', `Type` is the `test_mod::TestEnum` expression type
225 /// and `String` is the `test_function`
226 TraitAssocItem(Type, String),
227 /// A trait method with self parameter.
228 /// For 'test_enum.test_method()', `Type` is the `test_enum` expression type
229 /// and `String` is the `test_method`
230 TraitMethod(Type, String),
231}
232
233impl ImportCandidate {
234 fn for_method_call(
235 sema: &Semantics<RootDatabase>,
236 method_call: &ast::MethodCallExpr,
237 ) -> Option<Self> {
238 if sema.resolve_method_call(method_call).is_some() {
239 return None;
240 }
241 Some(Self::TraitMethod(
242 sema.type_of_expr(&method_call.expr()?)?,
243 method_call.name_ref()?.syntax().to_string(),
244 ))
245 }
246
247 fn for_regular_path(
248 sema: &Semantics<RootDatabase>,
249 path_under_caret: &ast::Path,
250 ) -> Option<Self> {
251 if sema.resolve_path(path_under_caret).is_some() {
252 return None;
253 }
254
255 let segment = path_under_caret.segment()?;
256 if let Some(qualifier) = path_under_caret.qualifier() {
257 let qualifier_start = qualifier.syntax().descendants().find_map(ast::NameRef::cast)?;
258 let qualifier_start_path =
259 qualifier_start.syntax().ancestors().find_map(ast::Path::cast)?;
260 if let Some(qualifier_start_resolution) = sema.resolve_path(&qualifier_start_path) {
261 let qualifier_resolution = if qualifier_start_path == qualifier {
262 qualifier_start_resolution
263 } else {
264 sema.resolve_path(&qualifier)?
265 };
266 if let PathResolution::Def(ModuleDef::Adt(assoc_item_path)) = qualifier_resolution {
267 Some(ImportCandidate::TraitAssocItem(
268 assoc_item_path.ty(sema.db),
269 segment.syntax().to_string(),
270 ))
271 } else {
272 None
273 }
274 } else {
275 Some(ImportCandidate::QualifierStart(qualifier_start.syntax().to_string()))
276 }
277 } else {
278 Some(ImportCandidate::UnqualifiedName(
279 segment.syntax().descendants().find_map(ast::NameRef::cast)?.syntax().to_string(),
280 ))
281 }
282 }
283}
284
285#[cfg(test)]
286mod tests {
287 use super::*;
288 use crate::tests::{check_assist, check_assist_not_applicable, check_assist_target};
289
290 #[test]
291 fn applicable_when_found_an_import() {
292 check_assist(
293 auto_import,
294 r"
295 <|>PubStruct
296
297 pub mod PubMod {
298 pub struct PubStruct;
299 }
300 ",
301 r"
302 use PubMod::PubStruct;
303
304 PubStruct
305
306 pub mod PubMod {
307 pub struct PubStruct;
308 }
309 ",
310 );
311 }
312
313 #[test]
314 fn applicable_when_found_an_import_in_macros() {
315 check_assist(
316 auto_import,
317 r"
318 macro_rules! foo {
319 ($i:ident) => { fn foo(a: $i) {} }
320 }
321 foo!(Pub<|>Struct);
322
323 pub mod PubMod {
324 pub struct PubStruct;
325 }
326 ",
327 r"
328 use PubMod::PubStruct;
329
330 macro_rules! foo {
331 ($i:ident) => { fn foo(a: $i) {} }
332 }
333 foo!(PubStruct);
334
335 pub mod PubMod {
336 pub struct PubStruct;
337 }
338 ",
339 );
340 }
341
342 #[test]
343 fn auto_imports_are_merged() {
344 check_assist(
345 auto_import,
346 r"
347 use PubMod::PubStruct1;
348
349 struct Test {
350 test: Pub<|>Struct2<u8>,
351 }
352
353 pub mod PubMod {
354 pub struct PubStruct1;
355 pub struct PubStruct2<T> {
356 _t: T,
357 }
358 }
359 ",
360 r"
361 use PubMod::{PubStruct2, PubStruct1};
362
363 struct Test {
364 test: PubStruct2<u8>,
365 }
366
367 pub mod PubMod {
368 pub struct PubStruct1;
369 pub struct PubStruct2<T> {
370 _t: T,
371 }
372 }
373 ",
374 );
375 }
376
377 #[test]
378 fn applicable_when_found_multiple_imports() {
379 check_assist(
380 auto_import,
381 r"
382 PubSt<|>ruct
383
384 pub mod PubMod1 {
385 pub struct PubStruct;
386 }
387 pub mod PubMod2 {
388 pub struct PubStruct;
389 }
390 pub mod PubMod3 {
391 pub struct PubStruct;
392 }
393 ",
394 r"
395 use PubMod3::PubStruct;
396
397 PubStruct
398
399 pub mod PubMod1 {
400 pub struct PubStruct;
401 }
402 pub mod PubMod2 {
403 pub struct PubStruct;
404 }
405 pub mod PubMod3 {
406 pub struct PubStruct;
407 }
408 ",
409 );
410 }
411
412 #[test]
413 fn not_applicable_for_already_imported_types() {
414 check_assist_not_applicable(
415 auto_import,
416 r"
417 use PubMod::PubStruct;
418
419 PubStruct<|>
420
421 pub mod PubMod {
422 pub struct PubStruct;
423 }
424 ",
425 );
426 }
427
428 #[test]
429 fn not_applicable_for_types_with_private_paths() {
430 check_assist_not_applicable(
431 auto_import,
432 r"
433 PrivateStruct<|>
434
435 pub mod PubMod {
436 struct PrivateStruct;
437 }
438 ",
439 );
440 }
441
442 #[test]
443 fn not_applicable_when_no_imports_found() {
444 check_assist_not_applicable(
445 auto_import,
446 "
447 PubStruct<|>",
448 );
449 }
450
451 #[test]
452 fn not_applicable_in_import_statements() {
453 check_assist_not_applicable(
454 auto_import,
455 r"
456 use PubStruct<|>;
457
458 pub mod PubMod {
459 pub struct PubStruct;
460 }",
461 );
462 }
463
464 #[test]
465 fn function_import() {
466 check_assist(
467 auto_import,
468 r"
469 test_function<|>
470
471 pub mod PubMod {
472 pub fn test_function() {};
473 }
474 ",
475 r"
476 use PubMod::test_function;
477
478 test_function
479
480 pub mod PubMod {
481 pub fn test_function() {};
482 }
483 ",
484 );
485 }
486
487 #[test]
488 fn macro_import() {
489 check_assist(
490 auto_import,
491 r"
492//- /lib.rs crate:crate_with_macro
493#[macro_export]
494macro_rules! foo {
495 () => ()
496}
497
498//- /main.rs crate:main deps:crate_with_macro
499fn main() {
500 foo<|>
501}
502",
503 r"use crate_with_macro::foo;
504
505fn main() {
506 foo
507}
508",
509 );
510 }
511
512 #[test]
513 fn auto_import_target() {
514 check_assist_target(
515 auto_import,
516 r"
517 struct AssistInfo {
518 group_label: Option<<|>GroupLabel>,
519 }
520
521 mod m { pub struct GroupLabel; }
522 ",
523 "GroupLabel",
524 )
525 }
526
527 #[test]
528 fn not_applicable_when_path_start_is_imported() {
529 check_assist_not_applicable(
530 auto_import,
531 r"
532 pub mod mod1 {
533 pub mod mod2 {
534 pub mod mod3 {
535 pub struct TestStruct;
536 }
537 }
538 }
539
540 use mod1::mod2;
541 fn main() {
542 mod2::mod3::TestStruct<|>
543 }
544 ",
545 );
546 }
547
548 #[test]
549 fn not_applicable_for_imported_function() {
550 check_assist_not_applicable(
551 auto_import,
552 r"
553 pub mod test_mod {
554 pub fn test_function() {}
555 }
556
557 use test_mod::test_function;
558 fn main() {
559 test_function<|>
560 }
561 ",
562 );
563 }
564
565 #[test]
566 fn associated_struct_function() {
567 check_assist(
568 auto_import,
569 r"
570 mod test_mod {
571 pub struct TestStruct {}
572 impl TestStruct {
573 pub fn test_function() {}
574 }
575 }
576
577 fn main() {
578 TestStruct::test_function<|>
579 }
580 ",
581 r"
582 use test_mod::TestStruct;
583
584 mod test_mod {
585 pub struct TestStruct {}
586 impl TestStruct {
587 pub fn test_function() {}
588 }
589 }
590
591 fn main() {
592 TestStruct::test_function
593 }
594 ",
595 );
596 }
597
598 #[test]
599 fn associated_struct_const() {
600 check_assist(
601 auto_import,
602 r"
603 mod test_mod {
604 pub struct TestStruct {}
605 impl TestStruct {
606 const TEST_CONST: u8 = 42;
607 }
608 }
609
610 fn main() {
611 TestStruct::TEST_CONST<|>
612 }
613 ",
614 r"
615 use test_mod::TestStruct;
616
617 mod test_mod {
618 pub struct TestStruct {}
619 impl TestStruct {
620 const TEST_CONST: u8 = 42;
621 }
622 }
623
624 fn main() {
625 TestStruct::TEST_CONST
626 }
627 ",
628 );
629 }
630
631 #[test]
632 fn associated_trait_function() {
633 check_assist(
634 auto_import,
635 r"
636 mod test_mod {
637 pub trait TestTrait {
638 fn test_function();
639 }
640 pub struct TestStruct {}
641 impl TestTrait for TestStruct {
642 fn test_function() {}
643 }
644 }
645
646 fn main() {
647 test_mod::TestStruct::test_function<|>
648 }
649 ",
650 r"
651 use test_mod::TestTrait;
652
653 mod test_mod {
654 pub trait TestTrait {
655 fn test_function();
656 }
657 pub struct TestStruct {}
658 impl TestTrait for TestStruct {
659 fn test_function() {}
660 }
661 }
662
663 fn main() {
664 test_mod::TestStruct::test_function
665 }
666 ",
667 );
668 }
669
670 #[test]
671 fn not_applicable_for_imported_trait_for_function() {
672 check_assist_not_applicable(
673 auto_import,
674 r"
675 mod test_mod {
676 pub trait TestTrait {
677 fn test_function();
678 }
679 pub trait TestTrait2 {
680 fn test_function();
681 }
682 pub enum TestEnum {
683 One,
684 Two,
685 }
686 impl TestTrait2 for TestEnum {
687 fn test_function() {}
688 }
689 impl TestTrait for TestEnum {
690 fn test_function() {}
691 }
692 }
693
694 use test_mod::TestTrait2;
695 fn main() {
696 test_mod::TestEnum::test_function<|>;
697 }
698 ",
699 )
700 }
701
702 #[test]
703 fn associated_trait_const() {
704 check_assist(
705 auto_import,
706 r"
707 mod test_mod {
708 pub trait TestTrait {
709 const TEST_CONST: u8;
710 }
711 pub struct TestStruct {}
712 impl TestTrait for TestStruct {
713 const TEST_CONST: u8 = 42;
714 }
715 }
716
717 fn main() {
718 test_mod::TestStruct::TEST_CONST<|>
719 }
720 ",
721 r"
722 use test_mod::TestTrait;
723
724 mod test_mod {
725 pub trait TestTrait {
726 const TEST_CONST: u8;
727 }
728 pub struct TestStruct {}
729 impl TestTrait for TestStruct {
730 const TEST_CONST: u8 = 42;
731 }
732 }
733
734 fn main() {
735 test_mod::TestStruct::TEST_CONST
736 }
737 ",
738 );
739 }
740
741 #[test]
742 fn not_applicable_for_imported_trait_for_const() {
743 check_assist_not_applicable(
744 auto_import,
745 r"
746 mod test_mod {
747 pub trait TestTrait {
748 const TEST_CONST: u8;
749 }
750 pub trait TestTrait2 {
751 const TEST_CONST: f64;
752 }
753 pub enum TestEnum {
754 One,
755 Two,
756 }
757 impl TestTrait2 for TestEnum {
758 const TEST_CONST: f64 = 42.0;
759 }
760 impl TestTrait for TestEnum {
761 const TEST_CONST: u8 = 42;
762 }
763 }
764
765 use test_mod::TestTrait2;
766 fn main() {
767 test_mod::TestEnum::TEST_CONST<|>;
768 }
769 ",
770 )
771 }
772
773 #[test]
774 fn trait_method() {
775 check_assist(
776 auto_import,
777 r"
778 mod test_mod {
779 pub trait TestTrait {
780 fn test_method(&self);
781 }
782 pub struct TestStruct {}
783 impl TestTrait for TestStruct {
784 fn test_method(&self) {}
785 }
786 }
787
788 fn main() {
789 let test_struct = test_mod::TestStruct {};
790 test_struct.test_meth<|>od()
791 }
792 ",
793 r"
794 use test_mod::TestTrait;
795
796 mod test_mod {
797 pub trait TestTrait {
798 fn test_method(&self);
799 }
800 pub struct TestStruct {}
801 impl TestTrait for TestStruct {
802 fn test_method(&self) {}
803 }
804 }
805
806 fn main() {
807 let test_struct = test_mod::TestStruct {};
808 test_struct.test_method()
809 }
810 ",
811 );
812 }
813
814 #[test]
815 fn trait_method_cross_crate() {
816 check_assist(
817 auto_import,
818 r"
819 //- /main.rs crate:main deps:dep
820 fn main() {
821 let test_struct = dep::test_mod::TestStruct {};
822 test_struct.test_meth<|>od()
823 }
824 //- /dep.rs crate:dep
825 pub mod test_mod {
826 pub trait TestTrait {
827 fn test_method(&self);
828 }
829 pub struct TestStruct {}
830 impl TestTrait for TestStruct {
831 fn test_method(&self) {}
832 }
833 }
834 ",
835 r"
836 use dep::test_mod::TestTrait;
837
838 fn main() {
839 let test_struct = dep::test_mod::TestStruct {};
840 test_struct.test_method()
841 }
842 ",
843 );
844 }
845
846 #[test]
847 fn assoc_fn_cross_crate() {
848 check_assist(
849 auto_import,
850 r"
851 //- /main.rs crate:main deps:dep
852 fn main() {
853 dep::test_mod::TestStruct::test_func<|>tion
854 }
855 //- /dep.rs crate:dep
856 pub mod test_mod {
857 pub trait TestTrait {
858 fn test_function();
859 }
860 pub struct TestStruct {}
861 impl TestTrait for TestStruct {
862 fn test_function() {}
863 }
864 }
865 ",
866 r"
867 use dep::test_mod::TestTrait;
868
869 fn main() {
870 dep::test_mod::TestStruct::test_function
871 }
872 ",
873 );
874 }
875
876 #[test]
877 fn assoc_const_cross_crate() {
878 check_assist(
879 auto_import,
880 r"
881 //- /main.rs crate:main deps:dep
882 fn main() {
883 dep::test_mod::TestStruct::CONST<|>
884 }
885 //- /dep.rs crate:dep
886 pub mod test_mod {
887 pub trait TestTrait {
888 const CONST: bool;
889 }
890 pub struct TestStruct {}
891 impl TestTrait for TestStruct {
892 const CONST: bool = true;
893 }
894 }
895 ",
896 r"
897 use dep::test_mod::TestTrait;
898
899 fn main() {
900 dep::test_mod::TestStruct::CONST
901 }
902 ",
903 );
904 }
905
906 #[test]
907 fn assoc_fn_as_method_cross_crate() {
908 check_assist_not_applicable(
909 auto_import,
910 r"
911 //- /main.rs crate:main deps:dep
912 fn main() {
913 let test_struct = dep::test_mod::TestStruct {};
914 test_struct.test_func<|>tion()
915 }
916 //- /dep.rs crate:dep
917 pub mod test_mod {
918 pub trait TestTrait {
919 fn test_function();
920 }
921 pub struct TestStruct {}
922 impl TestTrait for TestStruct {
923 fn test_function() {}
924 }
925 }
926 ",
927 );
928 }
929
930 #[test]
931 fn private_trait_cross_crate() {
932 check_assist_not_applicable(
933 auto_import,
934 r"
935 //- /main.rs crate:main deps:dep
936 fn main() {
937 let test_struct = dep::test_mod::TestStruct {};
938 test_struct.test_meth<|>od()
939 }
940 //- /dep.rs crate:dep
941 pub mod test_mod {
942 trait TestTrait {
943 fn test_method(&self);
944 }
945 pub struct TestStruct {}
946 impl TestTrait for TestStruct {
947 fn test_method(&self) {}
948 }
949 }
950 ",
951 );
952 }
953
954 #[test]
955 fn not_applicable_for_imported_trait_for_method() {
956 check_assist_not_applicable(
957 auto_import,
958 r"
959 mod test_mod {
960 pub trait TestTrait {
961 fn test_method(&self);
962 }
963 pub trait TestTrait2 {
964 fn test_method(&self);
965 }
966 pub enum TestEnum {
967 One,
968 Two,
969 }
970 impl TestTrait2 for TestEnum {
971 fn test_method(&self) {}
972 }
973 impl TestTrait for TestEnum {
974 fn test_method(&self) {}
975 }
976 }
977
978 use test_mod::TestTrait2;
979 fn main() {
980 let one = test_mod::TestEnum::One;
981 one.test<|>_method();
982 }
983 ",
984 )
985 }
986
987 #[test]
988 fn dep_import() {
989 check_assist(
990 auto_import,
991 r"
992//- /lib.rs crate:dep
993pub struct Struct;
994
995//- /main.rs crate:main deps:dep
996fn main() {
997 Struct<|>
998}
999",
1000 r"use dep::Struct;
1001
1002fn main() {
1003 Struct
1004}
1005",
1006 );
1007 }
1008
1009 #[test]
1010 fn whole_segment() {
1011 // Tests that only imports whose last segment matches the identifier get suggested.
1012 check_assist(
1013 auto_import,
1014 r"
1015//- /lib.rs crate:dep
1016pub mod fmt {
1017 pub trait Display {}
1018}
1019
1020pub fn panic_fmt() {}
1021
1022//- /main.rs crate:main deps:dep
1023struct S;
1024
1025impl f<|>mt::Display for S {}
1026",
1027 r"use dep::fmt;
1028
1029struct S;
1030
1031impl fmt::Display for S {}
1032",
1033 );
1034 }
1035
1036 #[test]
1037 fn macro_generated() {
1038 // Tests that macro-generated items are suggested from external crates.
1039 check_assist(
1040 auto_import,
1041 r"
1042//- /lib.rs crate:dep
1043macro_rules! mac {
1044 () => {
1045 pub struct Cheese;
1046 };
1047}
1048
1049mac!();
1050
1051//- /main.rs crate:main deps:dep
1052fn main() {
1053 Cheese<|>;
1054}
1055",
1056 r"use dep::Cheese;
1057
1058fn main() {
1059 Cheese;
1060}
1061",
1062 );
1063 }
1064
1065 #[test]
1066 fn casing() {
1067 // Tests that differently cased names don't interfere and we only suggest the matching one.
1068 check_assist(
1069 auto_import,
1070 r"
1071//- /lib.rs crate:dep
1072pub struct FMT;
1073pub struct fmt;
1074
1075//- /main.rs crate:main deps:dep
1076fn main() {
1077 FMT<|>;
1078}
1079",
1080 r"use dep::FMT;
1081
1082fn main() {
1083 FMT;
1084}
1085",
1086 );
1087 }
1088}
diff --git a/crates/ra_assists/src/handlers/change_return_type_to_result.rs b/crates/ra_assists/src/handlers/change_return_type_to_result.rs
deleted file mode 100644
index be480943c..000000000
--- a/crates/ra_assists/src/handlers/change_return_type_to_result.rs
+++ /dev/null
@@ -1,998 +0,0 @@
1use std::iter;
2
3use syntax::{
4 ast::{self, make, BlockExpr, Expr, LoopBodyOwner},
5 AstNode, SyntaxNode,
6};
7use test_utils::mark;
8
9use crate::{AssistContext, AssistId, AssistKind, Assists};
10
11// Assist: change_return_type_to_result
12//
13// Change the function's return type to Result.
14//
15// ```
16// fn foo() -> i32<|> { 42i32 }
17// ```
18// ->
19// ```
20// fn foo() -> Result<i32, ${0:_}> { Ok(42i32) }
21// ```
22pub(crate) fn change_return_type_to_result(acc: &mut Assists, ctx: &AssistContext) -> Option<()> {
23 let ret_type = ctx.find_node_at_offset::<ast::RetType>()?;
24 // FIXME: extend to lambdas as well
25 let fn_def = ret_type.syntax().parent().and_then(ast::Fn::cast)?;
26
27 let type_ref = &ret_type.ty()?;
28 let ret_type_str = type_ref.syntax().text().to_string();
29 let first_part_ret_type = ret_type_str.splitn(2, '<').next();
30 if let Some(ret_type_first_part) = first_part_ret_type {
31 if ret_type_first_part.ends_with("Result") {
32 mark::hit!(change_return_type_to_result_simple_return_type_already_result);
33 return None;
34 }
35 }
36
37 let block_expr = &fn_def.body()?;
38
39 acc.add(
40 AssistId("change_return_type_to_result", AssistKind::RefactorRewrite),
41 "Wrap return type in Result",
42 type_ref.syntax().text_range(),
43 |builder| {
44 let mut tail_return_expr_collector = TailReturnCollector::new();
45 tail_return_expr_collector.collect_jump_exprs(block_expr, false);
46 tail_return_expr_collector.collect_tail_exprs(block_expr);
47
48 for ret_expr_arg in tail_return_expr_collector.exprs_to_wrap {
49 let ok_wrapped = make::expr_call(
50 make::expr_path(make::path_unqualified(make::path_segment(make::name_ref(
51 "Ok",
52 )))),
53 make::arg_list(iter::once(ret_expr_arg.clone())),
54 );
55 builder.replace_ast(ret_expr_arg, ok_wrapped);
56 }
57
58 match ctx.config.snippet_cap {
59 Some(cap) => {
60 let snippet = format!("Result<{}, ${{0:_}}>", type_ref);
61 builder.replace_snippet(cap, type_ref.syntax().text_range(), snippet)
62 }
63 None => builder
64 .replace(type_ref.syntax().text_range(), format!("Result<{}, _>", type_ref)),
65 }
66 },
67 )
68}
69
70struct TailReturnCollector {
71 exprs_to_wrap: Vec<ast::Expr>,
72}
73
74impl TailReturnCollector {
75 fn new() -> Self {
76 Self { exprs_to_wrap: vec![] }
77 }
78 /// Collect all`return` expression
79 fn collect_jump_exprs(&mut self, block_expr: &BlockExpr, collect_break: bool) {
80 let statements = block_expr.statements();
81 for stmt in statements {
82 let expr = match &stmt {
83 ast::Stmt::ExprStmt(stmt) => stmt.expr(),
84 ast::Stmt::LetStmt(stmt) => stmt.initializer(),
85 ast::Stmt::Item(_) => continue,
86 };
87 if let Some(expr) = &expr {
88 self.handle_exprs(expr, collect_break);
89 }
90 }
91
92 // Browse tail expressions for each block
93 if let Some(expr) = block_expr.expr() {
94 if let Some(last_exprs) = get_tail_expr_from_block(&expr) {
95 for last_expr in last_exprs {
96 let last_expr = match last_expr {
97 NodeType::Node(expr) => expr,
98 NodeType::Leaf(expr) => expr.syntax().clone(),
99 };
100
101 if let Some(last_expr) = Expr::cast(last_expr.clone()) {
102 self.handle_exprs(&last_expr, collect_break);
103 } else if let Some(expr_stmt) = ast::Stmt::cast(last_expr) {
104 let expr_stmt = match &expr_stmt {
105 ast::Stmt::ExprStmt(stmt) => stmt.expr(),
106 ast::Stmt::LetStmt(stmt) => stmt.initializer(),
107 ast::Stmt::Item(_) => None,
108 };
109 if let Some(expr) = &expr_stmt {
110 self.handle_exprs(expr, collect_break);
111 }
112 }
113 }
114 }
115 }
116 }
117
118 fn handle_exprs(&mut self, expr: &Expr, collect_break: bool) {
119 match expr {
120 Expr::BlockExpr(block_expr) => {
121 self.collect_jump_exprs(&block_expr, collect_break);
122 }
123 Expr::ReturnExpr(ret_expr) => {
124 if let Some(ret_expr_arg) = &ret_expr.expr() {
125 self.exprs_to_wrap.push(ret_expr_arg.clone());
126 }
127 }
128 Expr::BreakExpr(break_expr) if collect_break => {
129 if let Some(break_expr_arg) = &break_expr.expr() {
130 self.exprs_to_wrap.push(break_expr_arg.clone());
131 }
132 }
133 Expr::IfExpr(if_expr) => {
134 for block in if_expr.blocks() {
135 self.collect_jump_exprs(&block, collect_break);
136 }
137 }
138 Expr::LoopExpr(loop_expr) => {
139 if let Some(block_expr) = loop_expr.loop_body() {
140 self.collect_jump_exprs(&block_expr, collect_break);
141 }
142 }
143 Expr::ForExpr(for_expr) => {
144 if let Some(block_expr) = for_expr.loop_body() {
145 self.collect_jump_exprs(&block_expr, collect_break);
146 }
147 }
148 Expr::WhileExpr(while_expr) => {
149 if let Some(block_expr) = while_expr.loop_body() {
150 self.collect_jump_exprs(&block_expr, collect_break);
151 }
152 }
153 Expr::MatchExpr(match_expr) => {
154 if let Some(arm_list) = match_expr.match_arm_list() {
155 arm_list.arms().filter_map(|match_arm| match_arm.expr()).for_each(|expr| {
156 self.handle_exprs(&expr, collect_break);
157 });
158 }
159 }
160 _ => {}
161 }
162 }
163
164 fn collect_tail_exprs(&mut self, block: &BlockExpr) {
165 if let Some(expr) = block.expr() {
166 self.handle_exprs(&expr, true);
167 self.fetch_tail_exprs(&expr);
168 }
169 }
170
171 fn fetch_tail_exprs(&mut self, expr: &Expr) {
172 if let Some(exprs) = get_tail_expr_from_block(expr) {
173 for node_type in &exprs {
174 match node_type {
175 NodeType::Leaf(expr) => {
176 self.exprs_to_wrap.push(expr.clone());
177 }
178 NodeType::Node(expr) => {
179 if let Some(last_expr) = Expr::cast(expr.clone()) {
180 self.fetch_tail_exprs(&last_expr);
181 }
182 }
183 }
184 }
185 }
186 }
187}
188
189#[derive(Debug)]
190enum NodeType {
191 Leaf(ast::Expr),
192 Node(SyntaxNode),
193}
194
195/// Get a tail expression inside a block
196fn get_tail_expr_from_block(expr: &Expr) -> Option<Vec<NodeType>> {
197 match expr {
198 Expr::IfExpr(if_expr) => {
199 let mut nodes = vec![];
200 for block in if_expr.blocks() {
201 if let Some(block_expr) = block.expr() {
202 if let Some(tail_exprs) = get_tail_expr_from_block(&block_expr) {
203 nodes.extend(tail_exprs);
204 }
205 } else if let Some(last_expr) = block.syntax().last_child() {
206 nodes.push(NodeType::Node(last_expr));
207 } else {
208 nodes.push(NodeType::Node(block.syntax().clone()));
209 }
210 }
211 Some(nodes)
212 }
213 Expr::LoopExpr(loop_expr) => {
214 loop_expr.syntax().last_child().map(|lc| vec![NodeType::Node(lc)])
215 }
216 Expr::ForExpr(for_expr) => {
217 for_expr.syntax().last_child().map(|lc| vec![NodeType::Node(lc)])
218 }
219 Expr::WhileExpr(while_expr) => {
220 while_expr.syntax().last_child().map(|lc| vec![NodeType::Node(lc)])
221 }
222 Expr::BlockExpr(block_expr) => {
223 block_expr.expr().map(|lc| vec![NodeType::Node(lc.syntax().clone())])
224 }
225 Expr::MatchExpr(match_expr) => {
226 let arm_list = match_expr.match_arm_list()?;
227 let arms: Vec<NodeType> = arm_list
228 .arms()
229 .filter_map(|match_arm| match_arm.expr())
230 .map(|expr| match expr {
231 Expr::ReturnExpr(ret_expr) => NodeType::Node(ret_expr.syntax().clone()),
232 Expr::BreakExpr(break_expr) => NodeType::Node(break_expr.syntax().clone()),
233 _ => match expr.syntax().last_child() {
234 Some(last_expr) => NodeType::Node(last_expr),
235 None => NodeType::Node(expr.syntax().clone()),
236 },
237 })
238 .collect();
239
240 Some(arms)
241 }
242 Expr::BreakExpr(expr) => expr.expr().map(|e| vec![NodeType::Leaf(e)]),
243 Expr::ReturnExpr(ret_expr) => Some(vec![NodeType::Node(ret_expr.syntax().clone())]),
244
245 Expr::CallExpr(_)
246 | Expr::Literal(_)
247 | Expr::TupleExpr(_)
248 | Expr::ArrayExpr(_)
249 | Expr::ParenExpr(_)
250 | Expr::PathExpr(_)
251 | Expr::RecordExpr(_)
252 | Expr::IndexExpr(_)
253 | Expr::MethodCallExpr(_)
254 | Expr::AwaitExpr(_)
255 | Expr::CastExpr(_)
256 | Expr::RefExpr(_)
257 | Expr::PrefixExpr(_)
258 | Expr::RangeExpr(_)
259 | Expr::BinExpr(_)
260 | Expr::MacroCall(_)
261 | Expr::BoxExpr(_) => Some(vec![NodeType::Leaf(expr.clone())]),
262 _ => None,
263 }
264}
265
266#[cfg(test)]
267mod tests {
268 use crate::tests::{check_assist, check_assist_not_applicable};
269
270 use super::*;
271
272 #[test]
273 fn change_return_type_to_result_simple() {
274 check_assist(
275 change_return_type_to_result,
276 r#"fn foo() -> i3<|>2 {
277 let test = "test";
278 return 42i32;
279 }"#,
280 r#"fn foo() -> Result<i32, ${0:_}> {
281 let test = "test";
282 return Ok(42i32);
283 }"#,
284 );
285 }
286
287 #[test]
288 fn change_return_type_to_result_simple_return_type() {
289 check_assist(
290 change_return_type_to_result,
291 r#"fn foo() -> i32<|> {
292 let test = "test";
293 return 42i32;
294 }"#,
295 r#"fn foo() -> Result<i32, ${0:_}> {
296 let test = "test";
297 return Ok(42i32);
298 }"#,
299 );
300 }
301
302 #[test]
303 fn change_return_type_to_result_simple_return_type_bad_cursor() {
304 check_assist_not_applicable(
305 change_return_type_to_result,
306 r#"fn foo() -> i32 {
307 let test = "test";<|>
308 return 42i32;
309 }"#,
310 );
311 }
312
313 #[test]
314 fn change_return_type_to_result_simple_return_type_already_result_std() {
315 check_assist_not_applicable(
316 change_return_type_to_result,
317 r#"fn foo() -> std::result::Result<i32<|>, String> {
318 let test = "test";
319 return 42i32;
320 }"#,
321 );
322 }
323
324 #[test]
325 fn change_return_type_to_result_simple_return_type_already_result() {
326 mark::check!(change_return_type_to_result_simple_return_type_already_result);
327 check_assist_not_applicable(
328 change_return_type_to_result,
329 r#"fn foo() -> Result<i32<|>, String> {
330 let test = "test";
331 return 42i32;
332 }"#,
333 );
334 }
335
336 #[test]
337 fn change_return_type_to_result_simple_with_cursor() {
338 check_assist(
339 change_return_type_to_result,
340 r#"fn foo() -> <|>i32 {
341 let test = "test";
342 return 42i32;
343 }"#,
344 r#"fn foo() -> Result<i32, ${0:_}> {
345 let test = "test";
346 return Ok(42i32);
347 }"#,
348 );
349 }
350
351 #[test]
352 fn change_return_type_to_result_simple_with_tail() {
353 check_assist(
354 change_return_type_to_result,
355 r#"fn foo() -><|> i32 {
356 let test = "test";
357 42i32
358 }"#,
359 r#"fn foo() -> Result<i32, ${0:_}> {
360 let test = "test";
361 Ok(42i32)
362 }"#,
363 );
364 }
365
366 #[test]
367 fn change_return_type_to_result_simple_with_tail_only() {
368 check_assist(
369 change_return_type_to_result,
370 r#"fn foo() -> i32<|> {
371 42i32
372 }"#,
373 r#"fn foo() -> Result<i32, ${0:_}> {
374 Ok(42i32)
375 }"#,
376 );
377 }
378 #[test]
379 fn change_return_type_to_result_simple_with_tail_block_like() {
380 check_assist(
381 change_return_type_to_result,
382 r#"fn foo() -> i32<|> {
383 if true {
384 42i32
385 } else {
386 24i32
387 }
388 }"#,
389 r#"fn foo() -> Result<i32, ${0:_}> {
390 if true {
391 Ok(42i32)
392 } else {
393 Ok(24i32)
394 }
395 }"#,
396 );
397 }
398
399 #[test]
400 fn change_return_type_to_result_simple_with_nested_if() {
401 check_assist(
402 change_return_type_to_result,
403 r#"fn foo() -> i32<|> {
404 if true {
405 if false {
406 1
407 } else {
408 2
409 }
410 } else {
411 24i32
412 }
413 }"#,
414 r#"fn foo() -> Result<i32, ${0:_}> {
415 if true {
416 if false {
417 Ok(1)
418 } else {
419 Ok(2)
420 }
421 } else {
422 Ok(24i32)
423 }
424 }"#,
425 );
426 }
427
428 #[test]
429 fn change_return_type_to_result_simple_with_await() {
430 check_assist(
431 change_return_type_to_result,
432 r#"async fn foo() -> i<|>32 {
433 if true {
434 if false {
435 1.await
436 } else {
437 2.await
438 }
439 } else {
440 24i32.await
441 }
442 }"#,
443 r#"async fn foo() -> Result<i32, ${0:_}> {
444 if true {
445 if false {
446 Ok(1.await)
447 } else {
448 Ok(2.await)
449 }
450 } else {
451 Ok(24i32.await)
452 }
453 }"#,
454 );
455 }
456
457 #[test]
458 fn change_return_type_to_result_simple_with_array() {
459 check_assist(
460 change_return_type_to_result,
461 r#"fn foo() -> [i32;<|> 3] {
462 [1, 2, 3]
463 }"#,
464 r#"fn foo() -> Result<[i32; 3], ${0:_}> {
465 Ok([1, 2, 3])
466 }"#,
467 );
468 }
469
470 #[test]
471 fn change_return_type_to_result_simple_with_cast() {
472 check_assist(
473 change_return_type_to_result,
474 r#"fn foo() -<|>> i32 {
475 if true {
476 if false {
477 1 as i32
478 } else {
479 2 as i32
480 }
481 } else {
482 24 as i32
483 }
484 }"#,
485 r#"fn foo() -> Result<i32, ${0:_}> {
486 if true {
487 if false {
488 Ok(1 as i32)
489 } else {
490 Ok(2 as i32)
491 }
492 } else {
493 Ok(24 as i32)
494 }
495 }"#,
496 );
497 }
498
499 #[test]
500 fn change_return_type_to_result_simple_with_tail_block_like_match() {
501 check_assist(
502 change_return_type_to_result,
503 r#"fn foo() -> i32<|> {
504 let my_var = 5;
505 match my_var {
506 5 => 42i32,
507 _ => 24i32,
508 }
509 }"#,
510 r#"fn foo() -> Result<i32, ${0:_}> {
511 let my_var = 5;
512 match my_var {
513 5 => Ok(42i32),
514 _ => Ok(24i32),
515 }
516 }"#,
517 );
518 }
519
520 #[test]
521 fn change_return_type_to_result_simple_with_loop_with_tail() {
522 check_assist(
523 change_return_type_to_result,
524 r#"fn foo() -> i32<|> {
525 let my_var = 5;
526 loop {
527 println!("test");
528 5
529 }
530
531 my_var
532 }"#,
533 r#"fn foo() -> Result<i32, ${0:_}> {
534 let my_var = 5;
535 loop {
536 println!("test");
537 5
538 }
539
540 Ok(my_var)
541 }"#,
542 );
543 }
544
545 #[test]
546 fn change_return_type_to_result_simple_with_loop_in_let_stmt() {
547 check_assist(
548 change_return_type_to_result,
549 r#"fn foo() -> i32<|> {
550 let my_var = let x = loop {
551 break 1;
552 };
553
554 my_var
555 }"#,
556 r#"fn foo() -> Result<i32, ${0:_}> {
557 let my_var = let x = loop {
558 break 1;
559 };
560
561 Ok(my_var)
562 }"#,
563 );
564 }
565
566 #[test]
567 fn change_return_type_to_result_simple_with_tail_block_like_match_return_expr() {
568 check_assist(
569 change_return_type_to_result,
570 r#"fn foo() -> i32<|> {
571 let my_var = 5;
572 let res = match my_var {
573 5 => 42i32,
574 _ => return 24i32,
575 };
576
577 res
578 }"#,
579 r#"fn foo() -> Result<i32, ${0:_}> {
580 let my_var = 5;
581 let res = match my_var {
582 5 => 42i32,
583 _ => return Ok(24i32),
584 };
585
586 Ok(res)
587 }"#,
588 );
589
590 check_assist(
591 change_return_type_to_result,
592 r#"fn foo() -> i32<|> {
593 let my_var = 5;
594 let res = if my_var == 5 {
595 42i32
596 } else {
597 return 24i32;
598 };
599
600 res
601 }"#,
602 r#"fn foo() -> Result<i32, ${0:_}> {
603 let my_var = 5;
604 let res = if my_var == 5 {
605 42i32
606 } else {
607 return Ok(24i32);
608 };
609
610 Ok(res)
611 }"#,
612 );
613 }
614
615 #[test]
616 fn change_return_type_to_result_simple_with_tail_block_like_match_deeper() {
617 check_assist(
618 change_return_type_to_result,
619 r#"fn foo() -> i32<|> {
620 let my_var = 5;
621 match my_var {
622 5 => {
623 if true {
624 42i32
625 } else {
626 25i32
627 }
628 },
629 _ => {
630 let test = "test";
631 if test == "test" {
632 return bar();
633 }
634 53i32
635 },
636 }
637 }"#,
638 r#"fn foo() -> Result<i32, ${0:_}> {
639 let my_var = 5;
640 match my_var {
641 5 => {
642 if true {
643 Ok(42i32)
644 } else {
645 Ok(25i32)
646 }
647 },
648 _ => {
649 let test = "test";
650 if test == "test" {
651 return Ok(bar());
652 }
653 Ok(53i32)
654 },
655 }
656 }"#,
657 );
658 }
659
660 #[test]
661 fn change_return_type_to_result_simple_with_tail_block_like_early_return() {
662 check_assist(
663 change_return_type_to_result,
664 r#"fn foo() -> i<|>32 {
665 let test = "test";
666 if test == "test" {
667 return 24i32;
668 }
669 53i32
670 }"#,
671 r#"fn foo() -> Result<i32, ${0:_}> {
672 let test = "test";
673 if test == "test" {
674 return Ok(24i32);
675 }
676 Ok(53i32)
677 }"#,
678 );
679 }
680
681 #[test]
682 fn change_return_type_to_result_simple_with_closure() {
683 check_assist(
684 change_return_type_to_result,
685 r#"fn foo(the_field: u32) -><|> u32 {
686 let true_closure = || {
687 return true;
688 };
689 if the_field < 5 {
690 let mut i = 0;
691
692
693 if true_closure() {
694 return 99;
695 } else {
696 return 0;
697 }
698 }
699
700 the_field
701 }"#,
702 r#"fn foo(the_field: u32) -> Result<u32, ${0:_}> {
703 let true_closure = || {
704 return true;
705 };
706 if the_field < 5 {
707 let mut i = 0;
708
709
710 if true_closure() {
711 return Ok(99);
712 } else {
713 return Ok(0);
714 }
715 }
716
717 Ok(the_field)
718 }"#,
719 );
720
721 check_assist(
722 change_return_type_to_result,
723 r#"fn foo(the_field: u32) -> u32<|> {
724 let true_closure = || {
725 return true;
726 };
727 if the_field < 5 {
728 let mut i = 0;
729
730
731 if true_closure() {
732 return 99;
733 } else {
734 return 0;
735 }
736 }
737 let t = None;
738
739 t.unwrap_or_else(|| the_field)
740 }"#,
741 r#"fn foo(the_field: u32) -> Result<u32, ${0:_}> {
742 let true_closure = || {
743 return true;
744 };
745 if the_field < 5 {
746 let mut i = 0;
747
748
749 if true_closure() {
750 return Ok(99);
751 } else {
752 return Ok(0);
753 }
754 }
755 let t = None;
756
757 Ok(t.unwrap_or_else(|| the_field))
758 }"#,
759 );
760 }
761
762 #[test]
763 fn change_return_type_to_result_simple_with_weird_forms() {
764 check_assist(
765 change_return_type_to_result,
766 r#"fn foo() -> i32<|> {
767 let test = "test";
768 if test == "test" {
769 return 24i32;
770 }
771 let mut i = 0;
772 loop {
773 if i == 1 {
774 break 55;
775 }
776 i += 1;
777 }
778 }"#,
779 r#"fn foo() -> Result<i32, ${0:_}> {
780 let test = "test";
781 if test == "test" {
782 return Ok(24i32);
783 }
784 let mut i = 0;
785 loop {
786 if i == 1 {
787 break Ok(55);
788 }
789 i += 1;
790 }
791 }"#,
792 );
793
794 check_assist(
795 change_return_type_to_result,
796 r#"fn foo() -> i32<|> {
797 let test = "test";
798 if test == "test" {
799 return 24i32;
800 }
801 let mut i = 0;
802 loop {
803 loop {
804 if i == 1 {
805 break 55;
806 }
807 i += 1;
808 }
809 }
810 }"#,
811 r#"fn foo() -> Result<i32, ${0:_}> {
812 let test = "test";
813 if test == "test" {
814 return Ok(24i32);
815 }
816 let mut i = 0;
817 loop {
818 loop {
819 if i == 1 {
820 break Ok(55);
821 }
822 i += 1;
823 }
824 }
825 }"#,
826 );
827
828 check_assist(
829 change_return_type_to_result,
830 r#"fn foo() -> i3<|>2 {
831 let test = "test";
832 let other = 5;
833 if test == "test" {
834 let res = match other {
835 5 => 43,
836 _ => return 56,
837 };
838 }
839 let mut i = 0;
840 loop {
841 loop {
842 if i == 1 {
843 break 55;
844 }
845 i += 1;
846 }
847 }
848 }"#,
849 r#"fn foo() -> Result<i32, ${0:_}> {
850 let test = "test";
851 let other = 5;
852 if test == "test" {
853 let res = match other {
854 5 => 43,
855 _ => return Ok(56),
856 };
857 }
858 let mut i = 0;
859 loop {
860 loop {
861 if i == 1 {
862 break Ok(55);
863 }
864 i += 1;
865 }
866 }
867 }"#,
868 );
869
870 check_assist(
871 change_return_type_to_result,
872 r#"fn foo(the_field: u32) -> u32<|> {
873 if the_field < 5 {
874 let mut i = 0;
875 loop {
876 if i > 5 {
877 return 55u32;
878 }
879 i += 3;
880 }
881
882 match i {
883 5 => return 99,
884 _ => return 0,
885 };
886 }
887
888 the_field
889 }"#,
890 r#"fn foo(the_field: u32) -> Result<u32, ${0:_}> {
891 if the_field < 5 {
892 let mut i = 0;
893 loop {
894 if i > 5 {
895 return Ok(55u32);
896 }
897 i += 3;
898 }
899
900 match i {
901 5 => return Ok(99),
902 _ => return Ok(0),
903 };
904 }
905
906 Ok(the_field)
907 }"#,
908 );
909
910 check_assist(
911 change_return_type_to_result,
912 r#"fn foo(the_field: u32) -> u3<|>2 {
913 if the_field < 5 {
914 let mut i = 0;
915
916 match i {
917 5 => return 99,
918 _ => return 0,
919 }
920 }
921
922 the_field
923 }"#,
924 r#"fn foo(the_field: u32) -> Result<u32, ${0:_}> {
925 if the_field < 5 {
926 let mut i = 0;
927
928 match i {
929 5 => return Ok(99),
930 _ => return Ok(0),
931 }
932 }
933
934 Ok(the_field)
935 }"#,
936 );
937
938 check_assist(
939 change_return_type_to_result,
940 r#"fn foo(the_field: u32) -> u32<|> {
941 if the_field < 5 {
942 let mut i = 0;
943
944 if i == 5 {
945 return 99
946 } else {
947 return 0
948 }
949 }
950
951 the_field
952 }"#,
953 r#"fn foo(the_field: u32) -> Result<u32, ${0:_}> {
954 if the_field < 5 {
955 let mut i = 0;
956
957 if i == 5 {
958 return Ok(99)
959 } else {
960 return Ok(0)
961 }
962 }
963
964 Ok(the_field)
965 }"#,
966 );
967
968 check_assist(
969 change_return_type_to_result,
970 r#"fn foo(the_field: u32) -> <|>u32 {
971 if the_field < 5 {
972 let mut i = 0;
973
974 if i == 5 {
975 return 99;
976 } else {
977 return 0;
978 }
979 }
980
981 the_field
982 }"#,
983 r#"fn foo(the_field: u32) -> Result<u32, ${0:_}> {
984 if the_field < 5 {
985 let mut i = 0;
986
987 if i == 5 {
988 return Ok(99);
989 } else {
990 return Ok(0);
991 }
992 }
993
994 Ok(the_field)
995 }"#,
996 );
997 }
998}
diff --git a/crates/ra_assists/src/handlers/change_visibility.rs b/crates/ra_assists/src/handlers/change_visibility.rs
deleted file mode 100644
index 32dc05378..000000000
--- a/crates/ra_assists/src/handlers/change_visibility.rs
+++ /dev/null
@@ -1,200 +0,0 @@
1use syntax::{
2 ast::{self, NameOwner, VisibilityOwner},
3 AstNode,
4 SyntaxKind::{CONST, ENUM, FN, MODULE, STATIC, STRUCT, TRAIT, VISIBILITY},
5 T,
6};
7use test_utils::mark;
8
9use crate::{utils::vis_offset, AssistContext, AssistId, AssistKind, Assists};
10
11// Assist: change_visibility
12//
13// Adds or changes existing visibility specifier.
14//
15// ```
16// <|>fn frobnicate() {}
17// ```
18// ->
19// ```
20// pub(crate) fn frobnicate() {}
21// ```
22pub(crate) fn change_visibility(acc: &mut Assists, ctx: &AssistContext) -> Option<()> {
23 if let Some(vis) = ctx.find_node_at_offset::<ast::Visibility>() {
24 return change_vis(acc, vis);
25 }
26 add_vis(acc, ctx)
27}
28
29fn add_vis(acc: &mut Assists, ctx: &AssistContext) -> Option<()> {
30 let item_keyword = ctx.token_at_offset().find(|leaf| {
31 matches!(
32 leaf.kind(),
33 T![const] | T![static] | T![fn] | T![mod] | T![struct] | T![enum] | T![trait]
34 )
35 });
36
37 let (offset, target) = if let Some(keyword) = item_keyword {
38 let parent = keyword.parent();
39 let def_kws = vec![CONST, STATIC, FN, MODULE, STRUCT, ENUM, TRAIT];
40 // Parent is not a definition, can't add visibility
41 if !def_kws.iter().any(|&def_kw| def_kw == parent.kind()) {
42 return None;
43 }
44 // Already have visibility, do nothing
45 if parent.children().any(|child| child.kind() == VISIBILITY) {
46 return None;
47 }
48 (vis_offset(&parent), keyword.text_range())
49 } else if let Some(field_name) = ctx.find_node_at_offset::<ast::Name>() {
50 let field = field_name.syntax().ancestors().find_map(ast::RecordField::cast)?;
51 if field.name()? != field_name {
52 mark::hit!(change_visibility_field_false_positive);
53 return None;
54 }
55 if field.visibility().is_some() {
56 return None;
57 }
58 (vis_offset(field.syntax()), field_name.syntax().text_range())
59 } else if let Some(field) = ctx.find_node_at_offset::<ast::TupleField>() {
60 if field.visibility().is_some() {
61 return None;
62 }
63 (vis_offset(field.syntax()), field.syntax().text_range())
64 } else {
65 return None;
66 };
67
68 acc.add(
69 AssistId("change_visibility", AssistKind::RefactorRewrite),
70 "Change visibility to pub(crate)",
71 target,
72 |edit| {
73 edit.insert(offset, "pub(crate) ");
74 },
75 )
76}
77
78fn change_vis(acc: &mut Assists, vis: ast::Visibility) -> Option<()> {
79 if vis.syntax().text() == "pub" {
80 let target = vis.syntax().text_range();
81 return acc.add(
82 AssistId("change_visibility", AssistKind::RefactorRewrite),
83 "Change Visibility to pub(crate)",
84 target,
85 |edit| {
86 edit.replace(vis.syntax().text_range(), "pub(crate)");
87 },
88 );
89 }
90 if vis.syntax().text() == "pub(crate)" {
91 let target = vis.syntax().text_range();
92 return acc.add(
93 AssistId("change_visibility", AssistKind::RefactorRewrite),
94 "Change visibility to pub",
95 target,
96 |edit| {
97 edit.replace(vis.syntax().text_range(), "pub");
98 },
99 );
100 }
101 None
102}
103
104#[cfg(test)]
105mod tests {
106 use test_utils::mark;
107
108 use crate::tests::{check_assist, check_assist_not_applicable, check_assist_target};
109
110 use super::*;
111
112 #[test]
113 fn change_visibility_adds_pub_crate_to_items() {
114 check_assist(change_visibility, "<|>fn foo() {}", "pub(crate) fn foo() {}");
115 check_assist(change_visibility, "f<|>n foo() {}", "pub(crate) fn foo() {}");
116 check_assist(change_visibility, "<|>struct Foo {}", "pub(crate) struct Foo {}");
117 check_assist(change_visibility, "<|>mod foo {}", "pub(crate) mod foo {}");
118 check_assist(change_visibility, "<|>trait Foo {}", "pub(crate) trait Foo {}");
119 check_assist(change_visibility, "m<|>od {}", "pub(crate) mod {}");
120 check_assist(change_visibility, "unsafe f<|>n foo() {}", "pub(crate) unsafe fn foo() {}");
121 }
122
123 #[test]
124 fn change_visibility_works_with_struct_fields() {
125 check_assist(
126 change_visibility,
127 r"struct S { <|>field: u32 }",
128 r"struct S { pub(crate) field: u32 }",
129 );
130 check_assist(change_visibility, r"struct S ( <|>u32 )", r"struct S ( pub(crate) u32 )");
131 }
132
133 #[test]
134 fn change_visibility_field_false_positive() {
135 mark::check!(change_visibility_field_false_positive);
136 check_assist_not_applicable(
137 change_visibility,
138 r"struct S { field: [(); { let <|>x = ();}] }",
139 )
140 }
141
142 #[test]
143 fn change_visibility_pub_to_pub_crate() {
144 check_assist(change_visibility, "<|>pub fn foo() {}", "pub(crate) fn foo() {}")
145 }
146
147 #[test]
148 fn change_visibility_pub_crate_to_pub() {
149 check_assist(change_visibility, "<|>pub(crate) fn foo() {}", "pub fn foo() {}")
150 }
151
152 #[test]
153 fn change_visibility_const() {
154 check_assist(change_visibility, "<|>const FOO = 3u8;", "pub(crate) const FOO = 3u8;");
155 }
156
157 #[test]
158 fn change_visibility_static() {
159 check_assist(change_visibility, "<|>static FOO = 3u8;", "pub(crate) static FOO = 3u8;");
160 }
161
162 #[test]
163 fn change_visibility_handles_comment_attrs() {
164 check_assist(
165 change_visibility,
166 r"
167 /// docs
168
169 // comments
170
171 #[derive(Debug)]
172 <|>struct Foo;
173 ",
174 r"
175 /// docs
176
177 // comments
178
179 #[derive(Debug)]
180 pub(crate) struct Foo;
181 ",
182 )
183 }
184
185 #[test]
186 fn not_applicable_for_enum_variants() {
187 check_assist_not_applicable(
188 change_visibility,
189 r"mod foo { pub enum Foo {Foo1} }
190 fn main() { foo::Foo::Foo1<|> } ",
191 );
192 }
193
194 #[test]
195 fn change_visibility_target() {
196 check_assist_target(change_visibility, "<|>fn foo() {}", "fn");
197 check_assist_target(change_visibility, "pub(crate)<|> fn foo() {}", "pub(crate)");
198 check_assist_target(change_visibility, "struct S { <|>field: u32 }", "field");
199 }
200}
diff --git a/crates/ra_assists/src/handlers/early_return.rs b/crates/ra_assists/src/handlers/early_return.rs
deleted file mode 100644
index 7fd78e9d4..000000000
--- a/crates/ra_assists/src/handlers/early_return.rs
+++ /dev/null
@@ -1,515 +0,0 @@
1use std::{iter::once, ops::RangeInclusive};
2
3use syntax::{
4 algo::replace_children,
5 ast::{
6 self,
7 edit::{AstNodeEdit, IndentLevel},
8 make,
9 },
10 AstNode,
11 SyntaxKind::{FN, LOOP_EXPR, L_CURLY, R_CURLY, WHILE_EXPR, WHITESPACE},
12 SyntaxNode,
13};
14
15use crate::{
16 assist_context::{AssistContext, Assists},
17 utils::invert_boolean_expression,
18 AssistId, AssistKind,
19};
20
21// Assist: convert_to_guarded_return
22//
23// Replace a large conditional with a guarded return.
24//
25// ```
26// fn main() {
27// <|>if cond {
28// foo();
29// bar();
30// }
31// }
32// ```
33// ->
34// ```
35// fn main() {
36// if !cond {
37// return;
38// }
39// foo();
40// bar();
41// }
42// ```
43pub(crate) fn convert_to_guarded_return(acc: &mut Assists, ctx: &AssistContext) -> Option<()> {
44 let if_expr: ast::IfExpr = ctx.find_node_at_offset()?;
45 if if_expr.else_branch().is_some() {
46 return None;
47 }
48
49 let cond = if_expr.condition()?;
50
51 // Check if there is an IfLet that we can handle.
52 let if_let_pat = match cond.pat() {
53 None => None, // No IfLet, supported.
54 Some(ast::Pat::TupleStructPat(pat)) if pat.fields().count() == 1 => {
55 let path = pat.path()?;
56 match path.qualifier() {
57 None => {
58 let bound_ident = pat.fields().next().unwrap();
59 Some((path, bound_ident))
60 }
61 Some(_) => return None,
62 }
63 }
64 Some(_) => return None, // Unsupported IfLet.
65 };
66
67 let cond_expr = cond.expr()?;
68 let then_block = if_expr.then_branch()?;
69
70 let parent_block = if_expr.syntax().parent()?.ancestors().find_map(ast::BlockExpr::cast)?;
71
72 if parent_block.expr()? != if_expr.clone().into() {
73 return None;
74 }
75
76 // check for early return and continue
77 let first_in_then_block = then_block.syntax().first_child()?;
78 if ast::ReturnExpr::can_cast(first_in_then_block.kind())
79 || ast::ContinueExpr::can_cast(first_in_then_block.kind())
80 || first_in_then_block
81 .children()
82 .any(|x| ast::ReturnExpr::can_cast(x.kind()) || ast::ContinueExpr::can_cast(x.kind()))
83 {
84 return None;
85 }
86
87 let parent_container = parent_block.syntax().parent()?;
88
89 let early_expression: ast::Expr = match parent_container.kind() {
90 WHILE_EXPR | LOOP_EXPR => make::expr_continue(),
91 FN => make::expr_return(),
92 _ => return None,
93 };
94
95 if then_block.syntax().first_child_or_token().map(|t| t.kind() == L_CURLY).is_none() {
96 return None;
97 }
98
99 then_block.syntax().last_child_or_token().filter(|t| t.kind() == R_CURLY)?;
100
101 let target = if_expr.syntax().text_range();
102 acc.add(
103 AssistId("convert_to_guarded_return", AssistKind::RefactorRewrite),
104 "Convert to guarded return",
105 target,
106 |edit| {
107 let if_indent_level = IndentLevel::from_node(&if_expr.syntax());
108 let new_block = match if_let_pat {
109 None => {
110 // If.
111 let new_expr = {
112 let then_branch =
113 make::block_expr(once(make::expr_stmt(early_expression).into()), None);
114 let cond = invert_boolean_expression(cond_expr);
115 make::expr_if(make::condition(cond, None), then_branch)
116 .indent(if_indent_level)
117 };
118 replace(new_expr.syntax(), &then_block, &parent_block, &if_expr)
119 }
120 Some((path, bound_ident)) => {
121 // If-let.
122 let match_expr = {
123 let happy_arm = {
124 let pat = make::tuple_struct_pat(
125 path,
126 once(make::ident_pat(make::name("it")).into()),
127 );
128 let expr = {
129 let name_ref = make::name_ref("it");
130 let segment = make::path_segment(name_ref);
131 let path = make::path_unqualified(segment);
132 make::expr_path(path)
133 };
134 make::match_arm(once(pat.into()), expr)
135 };
136
137 let sad_arm = make::match_arm(
138 // FIXME: would be cool to use `None` or `Err(_)` if appropriate
139 once(make::wildcard_pat().into()),
140 early_expression,
141 );
142
143 make::expr_match(cond_expr, make::match_arm_list(vec![happy_arm, sad_arm]))
144 };
145
146 let let_stmt = make::let_stmt(
147 make::ident_pat(make::name(&bound_ident.syntax().to_string())).into(),
148 Some(match_expr),
149 );
150 let let_stmt = let_stmt.indent(if_indent_level);
151 replace(let_stmt.syntax(), &then_block, &parent_block, &if_expr)
152 }
153 };
154 edit.replace_ast(parent_block, ast::BlockExpr::cast(new_block).unwrap());
155
156 fn replace(
157 new_expr: &SyntaxNode,
158 then_block: &ast::BlockExpr,
159 parent_block: &ast::BlockExpr,
160 if_expr: &ast::IfExpr,
161 ) -> SyntaxNode {
162 let then_block_items = then_block.dedent(IndentLevel(1));
163 let end_of_then = then_block_items.syntax().last_child_or_token().unwrap();
164 let end_of_then =
165 if end_of_then.prev_sibling_or_token().map(|n| n.kind()) == Some(WHITESPACE) {
166 end_of_then.prev_sibling_or_token().unwrap()
167 } else {
168 end_of_then
169 };
170 let mut then_statements = new_expr.children_with_tokens().chain(
171 then_block_items
172 .syntax()
173 .children_with_tokens()
174 .skip(1)
175 .take_while(|i| *i != end_of_then),
176 );
177 replace_children(
178 &parent_block.syntax(),
179 RangeInclusive::new(
180 if_expr.clone().syntax().clone().into(),
181 if_expr.syntax().clone().into(),
182 ),
183 &mut then_statements,
184 )
185 }
186 },
187 )
188}
189
190#[cfg(test)]
191mod tests {
192 use crate::tests::{check_assist, check_assist_not_applicable};
193
194 use super::*;
195
196 #[test]
197 fn convert_inside_fn() {
198 check_assist(
199 convert_to_guarded_return,
200 r#"
201 fn main() {
202 bar();
203 if<|> true {
204 foo();
205
206 //comment
207 bar();
208 }
209 }
210 "#,
211 r#"
212 fn main() {
213 bar();
214 if !true {
215 return;
216 }
217 foo();
218
219 //comment
220 bar();
221 }
222 "#,
223 );
224 }
225
226 #[test]
227 fn convert_let_inside_fn() {
228 check_assist(
229 convert_to_guarded_return,
230 r#"
231 fn main(n: Option<String>) {
232 bar();
233 if<|> let Some(n) = n {
234 foo(n);
235
236 //comment
237 bar();
238 }
239 }
240 "#,
241 r#"
242 fn main(n: Option<String>) {
243 bar();
244 let n = match n {
245 Some(it) => it,
246 _ => return,
247 };
248 foo(n);
249
250 //comment
251 bar();
252 }
253 "#,
254 );
255 }
256
257 #[test]
258 fn convert_if_let_result() {
259 check_assist(
260 convert_to_guarded_return,
261 r#"
262 fn main() {
263 if<|> let Ok(x) = Err(92) {
264 foo(x);
265 }
266 }
267 "#,
268 r#"
269 fn main() {
270 let x = match Err(92) {
271 Ok(it) => it,
272 _ => return,
273 };
274 foo(x);
275 }
276 "#,
277 );
278 }
279
280 #[test]
281 fn convert_let_ok_inside_fn() {
282 check_assist(
283 convert_to_guarded_return,
284 r#"
285 fn main(n: Option<String>) {
286 bar();
287 if<|> let Ok(n) = n {
288 foo(n);
289
290 //comment
291 bar();
292 }
293 }
294 "#,
295 r#"
296 fn main(n: Option<String>) {
297 bar();
298 let n = match n {
299 Ok(it) => it,
300 _ => return,
301 };
302 foo(n);
303
304 //comment
305 bar();
306 }
307 "#,
308 );
309 }
310
311 #[test]
312 fn convert_inside_while() {
313 check_assist(
314 convert_to_guarded_return,
315 r#"
316 fn main() {
317 while true {
318 if<|> true {
319 foo();
320 bar();
321 }
322 }
323 }
324 "#,
325 r#"
326 fn main() {
327 while true {
328 if !true {
329 continue;
330 }
331 foo();
332 bar();
333 }
334 }
335 "#,
336 );
337 }
338
339 #[test]
340 fn convert_let_inside_while() {
341 check_assist(
342 convert_to_guarded_return,
343 r#"
344 fn main() {
345 while true {
346 if<|> let Some(n) = n {
347 foo(n);
348 bar();
349 }
350 }
351 }
352 "#,
353 r#"
354 fn main() {
355 while true {
356 let n = match n {
357 Some(it) => it,
358 _ => continue,
359 };
360 foo(n);
361 bar();
362 }
363 }
364 "#,
365 );
366 }
367
368 #[test]
369 fn convert_inside_loop() {
370 check_assist(
371 convert_to_guarded_return,
372 r#"
373 fn main() {
374 loop {
375 if<|> true {
376 foo();
377 bar();
378 }
379 }
380 }
381 "#,
382 r#"
383 fn main() {
384 loop {
385 if !true {
386 continue;
387 }
388 foo();
389 bar();
390 }
391 }
392 "#,
393 );
394 }
395
396 #[test]
397 fn convert_let_inside_loop() {
398 check_assist(
399 convert_to_guarded_return,
400 r#"
401 fn main() {
402 loop {
403 if<|> let Some(n) = n {
404 foo(n);
405 bar();
406 }
407 }
408 }
409 "#,
410 r#"
411 fn main() {
412 loop {
413 let n = match n {
414 Some(it) => it,
415 _ => continue,
416 };
417 foo(n);
418 bar();
419 }
420 }
421 "#,
422 );
423 }
424
425 #[test]
426 fn ignore_already_converted_if() {
427 check_assist_not_applicable(
428 convert_to_guarded_return,
429 r#"
430 fn main() {
431 if<|> true {
432 return;
433 }
434 }
435 "#,
436 );
437 }
438
439 #[test]
440 fn ignore_already_converted_loop() {
441 check_assist_not_applicable(
442 convert_to_guarded_return,
443 r#"
444 fn main() {
445 loop {
446 if<|> true {
447 continue;
448 }
449 }
450 }
451 "#,
452 );
453 }
454
455 #[test]
456 fn ignore_return() {
457 check_assist_not_applicable(
458 convert_to_guarded_return,
459 r#"
460 fn main() {
461 if<|> true {
462 return
463 }
464 }
465 "#,
466 );
467 }
468
469 #[test]
470 fn ignore_else_branch() {
471 check_assist_not_applicable(
472 convert_to_guarded_return,
473 r#"
474 fn main() {
475 if<|> true {
476 foo();
477 } else {
478 bar()
479 }
480 }
481 "#,
482 );
483 }
484
485 #[test]
486 fn ignore_statements_aftert_if() {
487 check_assist_not_applicable(
488 convert_to_guarded_return,
489 r#"
490 fn main() {
491 if<|> true {
492 foo();
493 }
494 bar();
495 }
496 "#,
497 );
498 }
499
500 #[test]
501 fn ignore_statements_inside_if() {
502 check_assist_not_applicable(
503 convert_to_guarded_return,
504 r#"
505 fn main() {
506 if false {
507 if<|> true {
508 foo();
509 }
510 }
511 }
512 "#,
513 );
514 }
515}
diff --git a/crates/ra_assists/src/handlers/expand_glob_import.rs b/crates/ra_assists/src/handlers/expand_glob_import.rs
deleted file mode 100644
index f690ec343..000000000
--- a/crates/ra_assists/src/handlers/expand_glob_import.rs
+++ /dev/null
@@ -1,391 +0,0 @@
1use hir::{AssocItem, MacroDef, ModuleDef, Name, PathResolution, ScopeDef, SemanticsScope};
2use ide_db::{
3 defs::{classify_name_ref, Definition, NameRefClass},
4 RootDatabase,
5};
6use syntax::{algo, ast, match_ast, AstNode, SyntaxNode, SyntaxToken, T};
7
8use crate::{
9 assist_context::{AssistBuilder, AssistContext, Assists},
10 AssistId, AssistKind,
11};
12
13use either::Either;
14
15// Assist: expand_glob_import
16//
17// Expands glob imports.
18//
19// ```
20// mod foo {
21// pub struct Bar;
22// pub struct Baz;
23// }
24//
25// use foo::*<|>;
26//
27// fn qux(bar: Bar, baz: Baz) {}
28// ```
29// ->
30// ```
31// mod foo {
32// pub struct Bar;
33// pub struct Baz;
34// }
35//
36// use foo::{Baz, Bar};
37//
38// fn qux(bar: Bar, baz: Baz) {}
39// ```
40pub(crate) fn expand_glob_import(acc: &mut Assists, ctx: &AssistContext) -> Option<()> {
41 let star = ctx.find_token_at_offset(T![*])?;
42 let mod_path = find_mod_path(&star)?;
43
44 let source_file = ctx.source_file();
45 let scope = ctx.sema.scope_at_offset(source_file.syntax(), ctx.offset());
46
47 let defs_in_mod = find_defs_in_mod(ctx, scope, &mod_path)?;
48 let name_refs_in_source_file =
49 source_file.syntax().descendants().filter_map(ast::NameRef::cast).collect();
50 let used_names = find_used_names(ctx, defs_in_mod, name_refs_in_source_file);
51
52 let parent = star.parent().parent()?;
53 acc.add(
54 AssistId("expand_glob_import", AssistKind::RefactorRewrite),
55 "Expand glob import",
56 parent.text_range(),
57 |builder| {
58 replace_ast(builder, &parent, mod_path, used_names);
59 },
60 )
61}
62
63fn find_mod_path(star: &SyntaxToken) -> Option<ast::Path> {
64 star.ancestors().find_map(|n| ast::UseTree::cast(n).and_then(|u| u.path()))
65}
66
67#[derive(PartialEq)]
68enum Def {
69 ModuleDef(ModuleDef),
70 MacroDef(MacroDef),
71}
72
73impl Def {
74 fn name(&self, db: &RootDatabase) -> Option<Name> {
75 match self {
76 Def::ModuleDef(def) => def.name(db),
77 Def::MacroDef(def) => def.name(db),
78 }
79 }
80}
81
82fn find_defs_in_mod(
83 ctx: &AssistContext,
84 from: SemanticsScope<'_>,
85 path: &ast::Path,
86) -> Option<Vec<Def>> {
87 let hir_path = ctx.sema.lower_path(&path)?;
88 let module = if let Some(PathResolution::Def(ModuleDef::Module(module))) =
89 from.resolve_hir_path_qualifier(&hir_path)
90 {
91 module
92 } else {
93 return None;
94 };
95
96 let module_scope = module.scope(ctx.db(), from.module());
97
98 let mut defs = vec![];
99 for (_, def) in module_scope {
100 match def {
101 ScopeDef::ModuleDef(def) => defs.push(Def::ModuleDef(def)),
102 ScopeDef::MacroDef(def) => defs.push(Def::MacroDef(def)),
103 _ => continue,
104 }
105 }
106
107 Some(defs)
108}
109
110fn find_used_names(
111 ctx: &AssistContext,
112 defs_in_mod: Vec<Def>,
113 name_refs_in_source_file: Vec<ast::NameRef>,
114) -> Vec<Name> {
115 let defs_in_source_file = name_refs_in_source_file
116 .iter()
117 .filter_map(|r| classify_name_ref(&ctx.sema, r))
118 .filter_map(|rc| match rc {
119 NameRefClass::Definition(Definition::ModuleDef(def)) => Some(Def::ModuleDef(def)),
120 NameRefClass::Definition(Definition::Macro(def)) => Some(Def::MacroDef(def)),
121 _ => None,
122 })
123 .collect::<Vec<Def>>();
124
125 defs_in_mod
126 .iter()
127 .filter(|def| {
128 if let Def::ModuleDef(ModuleDef::Trait(tr)) = def {
129 for item in tr.items(ctx.db()) {
130 if let AssocItem::Function(f) = item {
131 if defs_in_source_file.contains(&Def::ModuleDef(ModuleDef::Function(f))) {
132 return true;
133 }
134 }
135 }
136 }
137
138 defs_in_source_file.contains(def)
139 })
140 .filter_map(|d| d.name(ctx.db()))
141 .collect()
142}
143
144fn replace_ast(
145 builder: &mut AssistBuilder,
146 node: &SyntaxNode,
147 path: ast::Path,
148 used_names: Vec<Name>,
149) {
150 let replacement: Either<ast::UseTree, ast::UseTreeList> = match used_names.as_slice() {
151 [name] => Either::Left(ast::make::use_tree(
152 ast::make::path_from_text(&format!("{}::{}", path, name)),
153 None,
154 None,
155 false,
156 )),
157 names => Either::Right(ast::make::use_tree_list(names.iter().map(|n| {
158 ast::make::use_tree(ast::make::path_from_text(&n.to_string()), None, None, false)
159 }))),
160 };
161
162 let mut replace_node = |replacement: Either<ast::UseTree, ast::UseTreeList>| {
163 algo::diff(node, &replacement.either(|u| u.syntax().clone(), |ut| ut.syntax().clone()))
164 .into_text_edit(builder.text_edit_builder());
165 };
166
167 match_ast! {
168 match node {
169 ast::UseTree(use_tree) => {
170 replace_node(replacement);
171 },
172 ast::UseTreeList(use_tree_list) => {
173 replace_node(replacement);
174 },
175 ast::Use(use_item) => {
176 builder.replace_ast(use_item, ast::make::use_(replacement.left_or_else(|ut| ast::make::use_tree(path, Some(ut), None, false))));
177 },
178 _ => {},
179 }
180 }
181}
182
183#[cfg(test)]
184mod tests {
185 use crate::tests::{check_assist, check_assist_not_applicable};
186
187 use super::*;
188
189 #[test]
190 fn expanding_glob_import() {
191 check_assist(
192 expand_glob_import,
193 r"
194mod foo {
195 pub struct Bar;
196 pub struct Baz;
197 pub struct Qux;
198
199 pub fn f() {}
200}
201
202use foo::*<|>;
203
204fn qux(bar: Bar, baz: Baz) {
205 f();
206}
207",
208 r"
209mod foo {
210 pub struct Bar;
211 pub struct Baz;
212 pub struct Qux;
213
214 pub fn f() {}
215}
216
217use foo::{Baz, Bar, f};
218
219fn qux(bar: Bar, baz: Baz) {
220 f();
221}
222",
223 )
224 }
225
226 #[test]
227 fn expanding_glob_import_with_existing_explicit_names() {
228 check_assist(
229 expand_glob_import,
230 r"
231mod foo {
232 pub struct Bar;
233 pub struct Baz;
234 pub struct Qux;
235
236 pub fn f() {}
237}
238
239use foo::{*<|>, f};
240
241fn qux(bar: Bar, baz: Baz) {
242 f();
243}
244",
245 r"
246mod foo {
247 pub struct Bar;
248 pub struct Baz;
249 pub struct Qux;
250
251 pub fn f() {}
252}
253
254use foo::{Baz, Bar, f};
255
256fn qux(bar: Bar, baz: Baz) {
257 f();
258}
259",
260 )
261 }
262
263 #[test]
264 fn expanding_nested_glob_import() {
265 check_assist(
266 expand_glob_import,
267 r"
268mod foo {
269 mod bar {
270 pub struct Bar;
271 pub struct Baz;
272 pub struct Qux;
273
274 pub fn f() {}
275 }
276
277 mod baz {
278 pub fn g() {}
279 }
280}
281
282use foo::{bar::{*<|>, f}, baz::*};
283
284fn qux(bar: Bar, baz: Baz) {
285 f();
286 g();
287}
288",
289 r"
290mod foo {
291 mod bar {
292 pub struct Bar;
293 pub struct Baz;
294 pub struct Qux;
295
296 pub fn f() {}
297 }
298
299 mod baz {
300 pub fn g() {}
301 }
302}
303
304use foo::{bar::{Baz, Bar, f}, baz::*};
305
306fn qux(bar: Bar, baz: Baz) {
307 f();
308 g();
309}
310",
311 )
312 }
313
314 #[test]
315 fn expanding_glob_import_with_macro_defs() {
316 check_assist(
317 expand_glob_import,
318 r"
319//- /lib.rs crate:foo
320#[macro_export]
321macro_rules! bar {
322 () => ()
323}
324
325pub fn baz() {}
326
327//- /main.rs crate:main deps:foo
328use foo::*<|>;
329
330fn main() {
331 bar!();
332 baz();
333}
334",
335 r"
336use foo::{bar, baz};
337
338fn main() {
339 bar!();
340 baz();
341}
342",
343 )
344 }
345
346 #[test]
347 fn expanding_glob_import_with_trait_method_uses() {
348 check_assist(
349 expand_glob_import,
350 r"
351//- /lib.rs crate:foo
352pub trait Tr {
353 fn method(&self) {}
354}
355impl Tr for () {}
356
357//- /main.rs crate:main deps:foo
358use foo::*<|>;
359
360fn main() {
361 ().method();
362}
363",
364 r"
365use foo::Tr;
366
367fn main() {
368 ().method();
369}
370",
371 )
372 }
373
374 #[test]
375 fn expanding_is_not_applicable_if_cursor_is_not_in_star_token() {
376 check_assist_not_applicable(
377 expand_glob_import,
378 r"
379 mod foo {
380 pub struct Bar;
381 pub struct Baz;
382 pub struct Qux;
383 }
384
385 use foo::Bar<|>;
386
387 fn qux(bar: Bar, baz: Baz) {}
388 ",
389 )
390 }
391}
diff --git a/crates/ra_assists/src/handlers/extract_struct_from_enum_variant.rs b/crates/ra_assists/src/handlers/extract_struct_from_enum_variant.rs
deleted file mode 100644
index 4bcdae7ba..000000000
--- a/crates/ra_assists/src/handlers/extract_struct_from_enum_variant.rs
+++ /dev/null
@@ -1,317 +0,0 @@
1use base_db::FileId;
2use hir::{EnumVariant, Module, ModuleDef, Name};
3use ide_db::{defs::Definition, search::Reference, RootDatabase};
4use rustc_hash::FxHashSet;
5use syntax::{
6 algo::find_node_at_offset,
7 ast::{self, edit::IndentLevel, ArgListOwner, AstNode, NameOwner, VisibilityOwner},
8 SourceFile, TextRange, TextSize,
9};
10
11use crate::{
12 assist_context::AssistBuilder, utils::insert_use_statement, AssistContext, AssistId,
13 AssistKind, Assists,
14};
15
16// Assist: extract_struct_from_enum_variant
17//
18// Extracts a struct from enum variant.
19//
20// ```
21// enum A { <|>One(u32, u32) }
22// ```
23// ->
24// ```
25// struct One(pub u32, pub u32);
26//
27// enum A { One(One) }
28// ```
29pub(crate) fn extract_struct_from_enum_variant(
30 acc: &mut Assists,
31 ctx: &AssistContext,
32) -> Option<()> {
33 let variant = ctx.find_node_at_offset::<ast::Variant>()?;
34 let field_list = match variant.kind() {
35 ast::StructKind::Tuple(field_list) => field_list,
36 _ => return None,
37 };
38 let variant_name = variant.name()?.to_string();
39 let variant_hir = ctx.sema.to_def(&variant)?;
40 if existing_struct_def(ctx.db(), &variant_name, &variant_hir) {
41 return None;
42 }
43 let enum_ast = variant.parent_enum();
44 let visibility = enum_ast.visibility();
45 let enum_hir = ctx.sema.to_def(&enum_ast)?;
46 let variant_hir_name = variant_hir.name(ctx.db());
47 let enum_module_def = ModuleDef::from(enum_hir);
48 let current_module = enum_hir.module(ctx.db());
49 let target = variant.syntax().text_range();
50 acc.add(
51 AssistId("extract_struct_from_enum_variant", AssistKind::RefactorRewrite),
52 "Extract struct from enum variant",
53 target,
54 |builder| {
55 let definition = Definition::ModuleDef(ModuleDef::EnumVariant(variant_hir));
56 let res = definition.find_usages(&ctx.sema, None);
57 let start_offset = variant.parent_enum().syntax().text_range().start();
58 let mut visited_modules_set = FxHashSet::default();
59 visited_modules_set.insert(current_module);
60 for reference in res {
61 let source_file = ctx.sema.parse(reference.file_range.file_id);
62 update_reference(
63 ctx,
64 builder,
65 reference,
66 &source_file,
67 &enum_module_def,
68 &variant_hir_name,
69 &mut visited_modules_set,
70 );
71 }
72 extract_struct_def(
73 builder,
74 &enum_ast,
75 &variant_name,
76 &field_list.to_string(),
77 start_offset,
78 ctx.frange.file_id,
79 &visibility,
80 );
81 let list_range = field_list.syntax().text_range();
82 update_variant(builder, &variant_name, ctx.frange.file_id, list_range);
83 },
84 )
85}
86
87fn existing_struct_def(db: &RootDatabase, variant_name: &str, variant: &EnumVariant) -> bool {
88 variant
89 .parent_enum(db)
90 .module(db)
91 .scope(db, None)
92 .into_iter()
93 .any(|(name, _)| name.to_string() == variant_name.to_string())
94}
95
96fn insert_import(
97 ctx: &AssistContext,
98 builder: &mut AssistBuilder,
99 path: &ast::PathExpr,
100 module: &Module,
101 enum_module_def: &ModuleDef,
102 variant_hir_name: &Name,
103) -> Option<()> {
104 let db = ctx.db();
105 let mod_path = module.find_use_path(db, enum_module_def.clone());
106 if let Some(mut mod_path) = mod_path {
107 mod_path.segments.pop();
108 mod_path.segments.push(variant_hir_name.clone());
109 insert_use_statement(path.syntax(), &mod_path, ctx, builder.text_edit_builder());
110 }
111 Some(())
112}
113
114// FIXME: this should use strongly-typed `make`, rather than string manipulation.
115fn extract_struct_def(
116 builder: &mut AssistBuilder,
117 enum_: &ast::Enum,
118 variant_name: &str,
119 variant_list: &str,
120 start_offset: TextSize,
121 file_id: FileId,
122 visibility: &Option<ast::Visibility>,
123) -> Option<()> {
124 let visibility_string = if let Some(visibility) = visibility {
125 format!("{} ", visibility.to_string())
126 } else {
127 "".to_string()
128 };
129 let indent = IndentLevel::from_node(enum_.syntax());
130 let struct_def = format!(
131 r#"{}struct {}{};
132
133{}"#,
134 visibility_string,
135 variant_name,
136 list_with_visibility(variant_list),
137 indent
138 );
139 builder.edit_file(file_id);
140 builder.insert(start_offset, struct_def);
141 Some(())
142}
143
144fn update_variant(
145 builder: &mut AssistBuilder,
146 variant_name: &str,
147 file_id: FileId,
148 list_range: TextRange,
149) -> Option<()> {
150 let inside_variant_range = TextRange::new(
151 list_range.start().checked_add(TextSize::from(1))?,
152 list_range.end().checked_sub(TextSize::from(1))?,
153 );
154 builder.edit_file(file_id);
155 builder.replace(inside_variant_range, variant_name);
156 Some(())
157}
158
159fn update_reference(
160 ctx: &AssistContext,
161 builder: &mut AssistBuilder,
162 reference: Reference,
163 source_file: &SourceFile,
164 enum_module_def: &ModuleDef,
165 variant_hir_name: &Name,
166 visited_modules_set: &mut FxHashSet<Module>,
167) -> Option<()> {
168 let path_expr: ast::PathExpr = find_node_at_offset::<ast::PathExpr>(
169 source_file.syntax(),
170 reference.file_range.range.start(),
171 )?;
172 let call = path_expr.syntax().parent().and_then(ast::CallExpr::cast)?;
173 let list = call.arg_list()?;
174 let segment = path_expr.path()?.segment()?;
175 let module = ctx.sema.scope(&path_expr.syntax()).module()?;
176 let list_range = list.syntax().text_range();
177 let inside_list_range = TextRange::new(
178 list_range.start().checked_add(TextSize::from(1))?,
179 list_range.end().checked_sub(TextSize::from(1))?,
180 );
181 builder.edit_file(reference.file_range.file_id);
182 if !visited_modules_set.contains(&module) {
183 if insert_import(ctx, builder, &path_expr, &module, enum_module_def, variant_hir_name)
184 .is_some()
185 {
186 visited_modules_set.insert(module);
187 }
188 }
189 builder.replace(inside_list_range, format!("{}{}", segment, list));
190 Some(())
191}
192
193fn list_with_visibility(list: &str) -> String {
194 list.split(',')
195 .map(|part| {
196 let index = if part.chars().next().unwrap() == '(' { 1usize } else { 0 };
197 let mut mod_part = part.trim().to_string();
198 mod_part.insert_str(index, "pub ");
199 mod_part
200 })
201 .collect::<Vec<String>>()
202 .join(", ")
203}
204
205#[cfg(test)]
206mod tests {
207
208 use crate::{
209 tests::{check_assist, check_assist_not_applicable},
210 utils::FamousDefs,
211 };
212
213 use super::*;
214
215 #[test]
216 fn test_extract_struct_several_fields() {
217 check_assist(
218 extract_struct_from_enum_variant,
219 "enum A { <|>One(u32, u32) }",
220 r#"struct One(pub u32, pub u32);
221
222enum A { One(One) }"#,
223 );
224 }
225
226 #[test]
227 fn test_extract_struct_one_field() {
228 check_assist(
229 extract_struct_from_enum_variant,
230 "enum A { <|>One(u32) }",
231 r#"struct One(pub u32);
232
233enum A { One(One) }"#,
234 );
235 }
236
237 #[test]
238 fn test_extract_struct_pub_visibility() {
239 check_assist(
240 extract_struct_from_enum_variant,
241 "pub enum A { <|>One(u32, u32) }",
242 r#"pub struct One(pub u32, pub u32);
243
244pub enum A { One(One) }"#,
245 );
246 }
247
248 #[test]
249 fn test_extract_struct_with_complex_imports() {
250 check_assist(
251 extract_struct_from_enum_variant,
252 r#"mod my_mod {
253 fn another_fn() {
254 let m = my_other_mod::MyEnum::MyField(1, 1);
255 }
256
257 pub mod my_other_mod {
258 fn another_fn() {
259 let m = MyEnum::MyField(1, 1);
260 }
261
262 pub enum MyEnum {
263 <|>MyField(u8, u8),
264 }
265 }
266}
267
268fn another_fn() {
269 let m = my_mod::my_other_mod::MyEnum::MyField(1, 1);
270}"#,
271 r#"use my_mod::my_other_mod::MyField;
272
273mod my_mod {
274 use my_other_mod::MyField;
275
276 fn another_fn() {
277 let m = my_other_mod::MyEnum::MyField(MyField(1, 1));
278 }
279
280 pub mod my_other_mod {
281 fn another_fn() {
282 let m = MyEnum::MyField(MyField(1, 1));
283 }
284
285 pub struct MyField(pub u8, pub u8);
286
287 pub enum MyEnum {
288 MyField(MyField),
289 }
290 }
291}
292
293fn another_fn() {
294 let m = my_mod::my_other_mod::MyEnum::MyField(MyField(1, 1));
295}"#,
296 );
297 }
298
299 fn check_not_applicable(ra_fixture: &str) {
300 let fixture =
301 format!("//- /main.rs crate:main deps:core\n{}\n{}", ra_fixture, FamousDefs::FIXTURE);
302 check_assist_not_applicable(extract_struct_from_enum_variant, &fixture)
303 }
304
305 #[test]
306 fn test_extract_enum_not_applicable_for_element_with_no_fields() {
307 check_not_applicable("enum A { <|>One }");
308 }
309
310 #[test]
311 fn test_extract_enum_not_applicable_if_struct_exists() {
312 check_not_applicable(
313 r#"struct One;
314 enum A { <|>One(u8) }"#,
315 );
316 }
317}
diff --git a/crates/ra_assists/src/handlers/extract_variable.rs b/crates/ra_assists/src/handlers/extract_variable.rs
deleted file mode 100644
index d2ae137cd..000000000
--- a/crates/ra_assists/src/handlers/extract_variable.rs
+++ /dev/null
@@ -1,588 +0,0 @@
1use stdx::format_to;
2use syntax::{
3 ast::{self, AstNode},
4 SyntaxKind::{
5 BLOCK_EXPR, BREAK_EXPR, CLOSURE_EXPR, COMMENT, LOOP_EXPR, MATCH_ARM, PATH_EXPR, RETURN_EXPR,
6 },
7 SyntaxNode,
8};
9use test_utils::mark;
10
11use crate::{AssistContext, AssistId, AssistKind, Assists};
12
13// Assist: extract_variable
14//
15// Extracts subexpression into a variable.
16//
17// ```
18// fn main() {
19// <|>(1 + 2)<|> * 4;
20// }
21// ```
22// ->
23// ```
24// fn main() {
25// let $0var_name = (1 + 2);
26// var_name * 4;
27// }
28// ```
29pub(crate) fn extract_variable(acc: &mut Assists, ctx: &AssistContext) -> Option<()> {
30 if ctx.frange.range.is_empty() {
31 return None;
32 }
33 let node = ctx.covering_element();
34 if node.kind() == COMMENT {
35 mark::hit!(extract_var_in_comment_is_not_applicable);
36 return None;
37 }
38 let to_extract = node.ancestors().find_map(valid_target_expr)?;
39 let anchor = Anchor::from(&to_extract)?;
40 let indent = anchor.syntax().prev_sibling_or_token()?.as_token()?.clone();
41 let target = to_extract.syntax().text_range();
42 acc.add(
43 AssistId("extract_variable", AssistKind::RefactorExtract),
44 "Extract into variable",
45 target,
46 move |edit| {
47 let field_shorthand =
48 match to_extract.syntax().parent().and_then(ast::RecordExprField::cast) {
49 Some(field) => field.name_ref(),
50 None => None,
51 };
52
53 let mut buf = String::new();
54
55 let var_name = match &field_shorthand {
56 Some(it) => it.to_string(),
57 None => "var_name".to_string(),
58 };
59 let expr_range = match &field_shorthand {
60 Some(it) => it.syntax().text_range().cover(to_extract.syntax().text_range()),
61 None => to_extract.syntax().text_range(),
62 };
63
64 if let Anchor::WrapInBlock(_) = anchor {
65 format_to!(buf, "{{ let {} = ", var_name);
66 } else {
67 format_to!(buf, "let {} = ", var_name);
68 };
69 format_to!(buf, "{}", to_extract.syntax());
70
71 if let Anchor::Replace(stmt) = anchor {
72 mark::hit!(test_extract_var_expr_stmt);
73 if stmt.semicolon_token().is_none() {
74 buf.push_str(";");
75 }
76 match ctx.config.snippet_cap {
77 Some(cap) => {
78 let snip = buf
79 .replace(&format!("let {}", var_name), &format!("let $0{}", var_name));
80 edit.replace_snippet(cap, expr_range, snip)
81 }
82 None => edit.replace(expr_range, buf),
83 }
84 return;
85 }
86
87 buf.push_str(";");
88
89 // We want to maintain the indent level,
90 // but we do not want to duplicate possible
91 // extra newlines in the indent block
92 let text = indent.text();
93 if text.starts_with('\n') {
94 buf.push_str("\n");
95 buf.push_str(text.trim_start_matches('\n'));
96 } else {
97 buf.push_str(text);
98 }
99
100 edit.replace(expr_range, var_name.clone());
101 let offset = anchor.syntax().text_range().start();
102 match ctx.config.snippet_cap {
103 Some(cap) => {
104 let snip =
105 buf.replace(&format!("let {}", var_name), &format!("let $0{}", var_name));
106 edit.insert_snippet(cap, offset, snip)
107 }
108 None => edit.insert(offset, buf),
109 }
110
111 if let Anchor::WrapInBlock(_) = anchor {
112 edit.insert(anchor.syntax().text_range().end(), " }");
113 }
114 },
115 )
116}
117
118/// Check whether the node is a valid expression which can be extracted to a variable.
119/// In general that's true for any expression, but in some cases that would produce invalid code.
120fn valid_target_expr(node: SyntaxNode) -> Option<ast::Expr> {
121 match node.kind() {
122 PATH_EXPR | LOOP_EXPR => None,
123 BREAK_EXPR => ast::BreakExpr::cast(node).and_then(|e| e.expr()),
124 RETURN_EXPR => ast::ReturnExpr::cast(node).and_then(|e| e.expr()),
125 BLOCK_EXPR => {
126 ast::BlockExpr::cast(node).filter(|it| it.is_standalone()).map(ast::Expr::from)
127 }
128 _ => ast::Expr::cast(node),
129 }
130}
131
132enum Anchor {
133 Before(SyntaxNode),
134 Replace(ast::ExprStmt),
135 WrapInBlock(SyntaxNode),
136}
137
138impl Anchor {
139 fn from(to_extract: &ast::Expr) -> Option<Anchor> {
140 to_extract.syntax().ancestors().find_map(|node| {
141 if let Some(expr) =
142 node.parent().and_then(ast::BlockExpr::cast).and_then(|it| it.expr())
143 {
144 if expr.syntax() == &node {
145 mark::hit!(test_extract_var_last_expr);
146 return Some(Anchor::Before(node));
147 }
148 }
149
150 if let Some(parent) = node.parent() {
151 if parent.kind() == MATCH_ARM || parent.kind() == CLOSURE_EXPR {
152 return Some(Anchor::WrapInBlock(node));
153 }
154 }
155
156 if let Some(stmt) = ast::Stmt::cast(node.clone()) {
157 if let ast::Stmt::ExprStmt(stmt) = stmt {
158 if stmt.expr().as_ref() == Some(to_extract) {
159 return Some(Anchor::Replace(stmt));
160 }
161 }
162 return Some(Anchor::Before(node));
163 }
164 None
165 })
166 }
167
168 fn syntax(&self) -> &SyntaxNode {
169 match self {
170 Anchor::Before(it) | Anchor::WrapInBlock(it) => it,
171 Anchor::Replace(stmt) => stmt.syntax(),
172 }
173 }
174}
175
176#[cfg(test)]
177mod tests {
178 use test_utils::mark;
179
180 use crate::tests::{check_assist, check_assist_not_applicable, check_assist_target};
181
182 use super::*;
183
184 #[test]
185 fn test_extract_var_simple() {
186 check_assist(
187 extract_variable,
188 r#"
189fn foo() {
190 foo(<|>1 + 1<|>);
191}"#,
192 r#"
193fn foo() {
194 let $0var_name = 1 + 1;
195 foo(var_name);
196}"#,
197 );
198 }
199
200 #[test]
201 fn extract_var_in_comment_is_not_applicable() {
202 mark::check!(extract_var_in_comment_is_not_applicable);
203 check_assist_not_applicable(extract_variable, "fn main() { 1 + /* <|>comment<|> */ 1; }");
204 }
205
206 #[test]
207 fn test_extract_var_expr_stmt() {
208 mark::check!(test_extract_var_expr_stmt);
209 check_assist(
210 extract_variable,
211 r#"
212fn foo() {
213 <|>1 + 1<|>;
214}"#,
215 r#"
216fn foo() {
217 let $0var_name = 1 + 1;
218}"#,
219 );
220 check_assist(
221 extract_variable,
222 "
223fn foo() {
224 <|>{ let x = 0; x }<|>
225 something_else();
226}",
227 "
228fn foo() {
229 let $0var_name = { let x = 0; x };
230 something_else();
231}",
232 );
233 }
234
235 #[test]
236 fn test_extract_var_part_of_expr_stmt() {
237 check_assist(
238 extract_variable,
239 "
240fn foo() {
241 <|>1<|> + 1;
242}",
243 "
244fn foo() {
245 let $0var_name = 1;
246 var_name + 1;
247}",
248 );
249 }
250
251 #[test]
252 fn test_extract_var_last_expr() {
253 mark::check!(test_extract_var_last_expr);
254 check_assist(
255 extract_variable,
256 r#"
257fn foo() {
258 bar(<|>1 + 1<|>)
259}
260"#,
261 r#"
262fn foo() {
263 let $0var_name = 1 + 1;
264 bar(var_name)
265}
266"#,
267 );
268 check_assist(
269 extract_variable,
270 r#"
271fn foo() {
272 <|>bar(1 + 1)<|>
273}
274"#,
275 r#"
276fn foo() {
277 let $0var_name = bar(1 + 1);
278 var_name
279}
280"#,
281 )
282 }
283
284 #[test]
285 fn test_extract_var_in_match_arm_no_block() {
286 check_assist(
287 extract_variable,
288 "
289fn main() {
290 let x = true;
291 let tuple = match x {
292 true => (<|>2 + 2<|>, true)
293 _ => (0, false)
294 };
295}
296",
297 "
298fn main() {
299 let x = true;
300 let tuple = match x {
301 true => { let $0var_name = 2 + 2; (var_name, true) }
302 _ => (0, false)
303 };
304}
305",
306 );
307 }
308
309 #[test]
310 fn test_extract_var_in_match_arm_with_block() {
311 check_assist(
312 extract_variable,
313 "
314fn main() {
315 let x = true;
316 let tuple = match x {
317 true => {
318 let y = 1;
319 (<|>2 + y<|>, true)
320 }
321 _ => (0, false)
322 };
323}
324",
325 "
326fn main() {
327 let x = true;
328 let tuple = match x {
329 true => {
330 let y = 1;
331 let $0var_name = 2 + y;
332 (var_name, true)
333 }
334 _ => (0, false)
335 };
336}
337",
338 );
339 }
340
341 #[test]
342 fn test_extract_var_in_closure_no_block() {
343 check_assist(
344 extract_variable,
345 "
346fn main() {
347 let lambda = |x: u32| <|>x * 2<|>;
348}
349",
350 "
351fn main() {
352 let lambda = |x: u32| { let $0var_name = x * 2; var_name };
353}
354",
355 );
356 }
357
358 #[test]
359 fn test_extract_var_in_closure_with_block() {
360 check_assist(
361 extract_variable,
362 "
363fn main() {
364 let lambda = |x: u32| { <|>x * 2<|> };
365}
366",
367 "
368fn main() {
369 let lambda = |x: u32| { let $0var_name = x * 2; var_name };
370}
371",
372 );
373 }
374
375 #[test]
376 fn test_extract_var_path_simple() {
377 check_assist(
378 extract_variable,
379 "
380fn main() {
381 let o = <|>Some(true)<|>;
382}
383",
384 "
385fn main() {
386 let $0var_name = Some(true);
387 let o = var_name;
388}
389",
390 );
391 }
392
393 #[test]
394 fn test_extract_var_path_method() {
395 check_assist(
396 extract_variable,
397 "
398fn main() {
399 let v = <|>bar.foo()<|>;
400}
401",
402 "
403fn main() {
404 let $0var_name = bar.foo();
405 let v = var_name;
406}
407",
408 );
409 }
410
411 #[test]
412 fn test_extract_var_return() {
413 check_assist(
414 extract_variable,
415 "
416fn foo() -> u32 {
417 <|>return 2 + 2<|>;
418}
419",
420 "
421fn foo() -> u32 {
422 let $0var_name = 2 + 2;
423 return var_name;
424}
425",
426 );
427 }
428
429 #[test]
430 fn test_extract_var_does_not_add_extra_whitespace() {
431 check_assist(
432 extract_variable,
433 "
434fn foo() -> u32 {
435
436
437 <|>return 2 + 2<|>;
438}
439",
440 "
441fn foo() -> u32 {
442
443
444 let $0var_name = 2 + 2;
445 return var_name;
446}
447",
448 );
449
450 check_assist(
451 extract_variable,
452 "
453fn foo() -> u32 {
454
455 <|>return 2 + 2<|>;
456}
457",
458 "
459fn foo() -> u32 {
460
461 let $0var_name = 2 + 2;
462 return var_name;
463}
464",
465 );
466
467 check_assist(
468 extract_variable,
469 "
470fn foo() -> u32 {
471 let foo = 1;
472
473 // bar
474
475
476 <|>return 2 + 2<|>;
477}
478",
479 "
480fn foo() -> u32 {
481 let foo = 1;
482
483 // bar
484
485
486 let $0var_name = 2 + 2;
487 return var_name;
488}
489",
490 );
491 }
492
493 #[test]
494 fn test_extract_var_break() {
495 check_assist(
496 extract_variable,
497 "
498fn main() {
499 let result = loop {
500 <|>break 2 + 2<|>;
501 };
502}
503",
504 "
505fn main() {
506 let result = loop {
507 let $0var_name = 2 + 2;
508 break var_name;
509 };
510}
511",
512 );
513 }
514
515 #[test]
516 fn test_extract_var_for_cast() {
517 check_assist(
518 extract_variable,
519 "
520fn main() {
521 let v = <|>0f32 as u32<|>;
522}
523",
524 "
525fn main() {
526 let $0var_name = 0f32 as u32;
527 let v = var_name;
528}
529",
530 );
531 }
532
533 #[test]
534 fn extract_var_field_shorthand() {
535 check_assist(
536 extract_variable,
537 r#"
538struct S {
539 foo: i32
540}
541
542fn main() {
543 S { foo: <|>1 + 1<|> }
544}
545"#,
546 r#"
547struct S {
548 foo: i32
549}
550
551fn main() {
552 let $0foo = 1 + 1;
553 S { foo }
554}
555"#,
556 )
557 }
558
559 #[test]
560 fn test_extract_var_for_return_not_applicable() {
561 check_assist_not_applicable(extract_variable, "fn foo() { <|>return<|>; } ");
562 }
563
564 #[test]
565 fn test_extract_var_for_break_not_applicable() {
566 check_assist_not_applicable(extract_variable, "fn main() { loop { <|>break<|>; }; }");
567 }
568
569 // FIXME: This is not quite correct, but good enough(tm) for the sorting heuristic
570 #[test]
571 fn extract_var_target() {
572 check_assist_target(extract_variable, "fn foo() -> u32 { <|>return 2 + 2<|>; }", "2 + 2");
573
574 check_assist_target(
575 extract_variable,
576 "
577fn main() {
578 let x = true;
579 let tuple = match x {
580 true => (<|>2 + 2<|>, true)
581 _ => (0, false)
582 };
583}
584",
585 "2 + 2",
586 );
587 }
588}
diff --git a/crates/ra_assists/src/handlers/fill_match_arms.rs b/crates/ra_assists/src/handlers/fill_match_arms.rs
deleted file mode 100644
index 3d9bdb2bf..000000000
--- a/crates/ra_assists/src/handlers/fill_match_arms.rs
+++ /dev/null
@@ -1,747 +0,0 @@
1use std::iter;
2
3use hir::{Adt, HasSource, ModuleDef, Semantics};
4use ide_db::RootDatabase;
5use itertools::Itertools;
6use syntax::ast::{self, make, AstNode, MatchArm, NameOwner, Pat};
7use test_utils::mark;
8
9use crate::{
10 utils::{render_snippet, Cursor, FamousDefs},
11 AssistContext, AssistId, AssistKind, Assists,
12};
13
14// Assist: fill_match_arms
15//
16// Adds missing clauses to a `match` expression.
17//
18// ```
19// enum Action { Move { distance: u32 }, Stop }
20//
21// fn handle(action: Action) {
22// match action {
23// <|>
24// }
25// }
26// ```
27// ->
28// ```
29// enum Action { Move { distance: u32 }, Stop }
30//
31// fn handle(action: Action) {
32// match action {
33// $0Action::Move { distance } => {}
34// Action::Stop => {}
35// }
36// }
37// ```
38pub(crate) fn fill_match_arms(acc: &mut Assists, ctx: &AssistContext) -> Option<()> {
39 let match_expr = ctx.find_node_at_offset::<ast::MatchExpr>()?;
40 let match_arm_list = match_expr.match_arm_list()?;
41
42 let expr = match_expr.expr()?;
43
44 let mut arms: Vec<MatchArm> = match_arm_list.arms().collect();
45 if arms.len() == 1 {
46 if let Some(Pat::WildcardPat(..)) = arms[0].pat() {
47 arms.clear();
48 }
49 }
50
51 let module = ctx.sema.scope(expr.syntax()).module()?;
52
53 let missing_arms: Vec<MatchArm> = if let Some(enum_def) = resolve_enum_def(&ctx.sema, &expr) {
54 let variants = enum_def.variants(ctx.db());
55
56 let mut variants = variants
57 .into_iter()
58 .filter_map(|variant| build_pat(ctx.db(), module, variant))
59 .filter(|variant_pat| is_variant_missing(&mut arms, variant_pat))
60 .map(|pat| make::match_arm(iter::once(pat), make::expr_empty_block()))
61 .collect::<Vec<_>>();
62 if Some(enum_def) == FamousDefs(&ctx.sema, module.krate()).core_option_Option() {
63 // Match `Some` variant first.
64 mark::hit!(option_order);
65 variants.reverse()
66 }
67 variants
68 } else if let Some(enum_defs) = resolve_tuple_of_enum_def(&ctx.sema, &expr) {
69 // Partial fill not currently supported for tuple of enums.
70 if !arms.is_empty() {
71 return None;
72 }
73
74 // We do not currently support filling match arms for a tuple
75 // containing a single enum.
76 if enum_defs.len() < 2 {
77 return None;
78 }
79
80 // When calculating the match arms for a tuple of enums, we want
81 // to create a match arm for each possible combination of enum
82 // values. The `multi_cartesian_product` method transforms
83 // Vec<Vec<EnumVariant>> into Vec<(EnumVariant, .., EnumVariant)>
84 // where each tuple represents a proposed match arm.
85 enum_defs
86 .into_iter()
87 .map(|enum_def| enum_def.variants(ctx.db()))
88 .multi_cartesian_product()
89 .map(|variants| {
90 let patterns =
91 variants.into_iter().filter_map(|variant| build_pat(ctx.db(), module, variant));
92 ast::Pat::from(make::tuple_pat(patterns))
93 })
94 .filter(|variant_pat| is_variant_missing(&mut arms, variant_pat))
95 .map(|pat| make::match_arm(iter::once(pat), make::expr_empty_block()))
96 .collect()
97 } else {
98 return None;
99 };
100
101 if missing_arms.is_empty() {
102 return None;
103 }
104
105 let target = match_expr.syntax().text_range();
106 acc.add(
107 AssistId("fill_match_arms", AssistKind::QuickFix),
108 "Fill match arms",
109 target,
110 |builder| {
111 let new_arm_list = match_arm_list.remove_placeholder();
112 let n_old_arms = new_arm_list.arms().count();
113 let new_arm_list = new_arm_list.append_arms(missing_arms);
114 let first_new_arm = new_arm_list.arms().nth(n_old_arms);
115 let old_range = match_arm_list.syntax().text_range();
116 match (first_new_arm, ctx.config.snippet_cap) {
117 (Some(first_new_arm), Some(cap)) => {
118 let extend_lifetime;
119 let cursor =
120 match first_new_arm.syntax().descendants().find_map(ast::WildcardPat::cast)
121 {
122 Some(it) => {
123 extend_lifetime = it.syntax().clone();
124 Cursor::Replace(&extend_lifetime)
125 }
126 None => Cursor::Before(first_new_arm.syntax()),
127 };
128 let snippet = render_snippet(cap, new_arm_list.syntax(), cursor);
129 builder.replace_snippet(cap, old_range, snippet);
130 }
131 _ => builder.replace(old_range, new_arm_list.to_string()),
132 }
133 },
134 )
135}
136
137fn is_variant_missing(existing_arms: &mut Vec<MatchArm>, var: &Pat) -> bool {
138 existing_arms.iter().filter_map(|arm| arm.pat()).all(|pat| {
139 // Special casee OrPat as separate top-level pats
140 let top_level_pats: Vec<Pat> = match pat {
141 Pat::OrPat(pats) => pats.pats().collect::<Vec<_>>(),
142 _ => vec![pat],
143 };
144
145 !top_level_pats.iter().any(|pat| does_pat_match_variant(pat, var))
146 })
147}
148
149fn does_pat_match_variant(pat: &Pat, var: &Pat) -> bool {
150 let first_node_text = |pat: &Pat| pat.syntax().first_child().map(|node| node.text());
151
152 let pat_head = match pat {
153 Pat::IdentPat(bind_pat) => {
154 if let Some(p) = bind_pat.pat() {
155 first_node_text(&p)
156 } else {
157 return false;
158 }
159 }
160 pat => first_node_text(pat),
161 };
162
163 let var_head = first_node_text(var);
164
165 pat_head == var_head
166}
167
168fn resolve_enum_def(sema: &Semantics<RootDatabase>, expr: &ast::Expr) -> Option<hir::Enum> {
169 sema.type_of_expr(&expr)?.autoderef(sema.db).find_map(|ty| match ty.as_adt() {
170 Some(Adt::Enum(e)) => Some(e),
171 _ => None,
172 })
173}
174
175fn resolve_tuple_of_enum_def(
176 sema: &Semantics<RootDatabase>,
177 expr: &ast::Expr,
178) -> Option<Vec<hir::Enum>> {
179 sema.type_of_expr(&expr)?
180 .tuple_fields(sema.db)
181 .iter()
182 .map(|ty| {
183 ty.autoderef(sema.db).find_map(|ty| match ty.as_adt() {
184 Some(Adt::Enum(e)) => Some(e),
185 // For now we only handle expansion for a tuple of enums. Here
186 // we map non-enum items to None and rely on `collect` to
187 // convert Vec<Option<hir::Enum>> into Option<Vec<hir::Enum>>.
188 _ => None,
189 })
190 })
191 .collect()
192}
193
194fn build_pat(db: &RootDatabase, module: hir::Module, var: hir::EnumVariant) -> Option<ast::Pat> {
195 let path = crate::ast_transform::path_to_ast(module.find_use_path(db, ModuleDef::from(var))?);
196
197 // FIXME: use HIR for this; it doesn't currently expose struct vs. tuple vs. unit variants though
198 let pat: ast::Pat = match var.source(db).value.kind() {
199 ast::StructKind::Tuple(field_list) => {
200 let pats = iter::repeat(make::wildcard_pat().into()).take(field_list.fields().count());
201 make::tuple_struct_pat(path, pats).into()
202 }
203 ast::StructKind::Record(field_list) => {
204 let pats = field_list.fields().map(|f| make::ident_pat(f.name().unwrap()).into());
205 make::record_pat(path, pats).into()
206 }
207 ast::StructKind::Unit => make::path_pat(path),
208 };
209
210 Some(pat)
211}
212
213#[cfg(test)]
214mod tests {
215 use test_utils::mark;
216
217 use crate::{
218 tests::{check_assist, check_assist_not_applicable, check_assist_target},
219 utils::FamousDefs,
220 };
221
222 use super::fill_match_arms;
223
224 #[test]
225 fn all_match_arms_provided() {
226 check_assist_not_applicable(
227 fill_match_arms,
228 r#"
229 enum A {
230 As,
231 Bs{x:i32, y:Option<i32>},
232 Cs(i32, Option<i32>),
233 }
234 fn main() {
235 match A::As<|> {
236 A::As,
237 A::Bs{x,y:Some(_)} => {}
238 A::Cs(_, Some(_)) => {}
239 }
240 }
241 "#,
242 );
243 }
244
245 #[test]
246 fn tuple_of_non_enum() {
247 // for now this case is not handled, although it potentially could be
248 // in the future
249 check_assist_not_applicable(
250 fill_match_arms,
251 r#"
252 fn main() {
253 match (0, false)<|> {
254 }
255 }
256 "#,
257 );
258 }
259
260 #[test]
261 fn partial_fill_record_tuple() {
262 check_assist(
263 fill_match_arms,
264 r#"
265 enum A {
266 As,
267 Bs { x: i32, y: Option<i32> },
268 Cs(i32, Option<i32>),
269 }
270 fn main() {
271 match A::As<|> {
272 A::Bs { x, y: Some(_) } => {}
273 A::Cs(_, Some(_)) => {}
274 }
275 }
276 "#,
277 r#"
278 enum A {
279 As,
280 Bs { x: i32, y: Option<i32> },
281 Cs(i32, Option<i32>),
282 }
283 fn main() {
284 match A::As {
285 A::Bs { x, y: Some(_) } => {}
286 A::Cs(_, Some(_)) => {}
287 $0A::As => {}
288 }
289 }
290 "#,
291 );
292 }
293
294 #[test]
295 fn partial_fill_or_pat() {
296 check_assist(
297 fill_match_arms,
298 r#"
299enum A { As, Bs, Cs(Option<i32>) }
300fn main() {
301 match A::As<|> {
302 A::Cs(_) | A::Bs => {}
303 }
304}
305"#,
306 r#"
307enum A { As, Bs, Cs(Option<i32>) }
308fn main() {
309 match A::As {
310 A::Cs(_) | A::Bs => {}
311 $0A::As => {}
312 }
313}
314"#,
315 );
316 }
317
318 #[test]
319 fn partial_fill() {
320 check_assist(
321 fill_match_arms,
322 r#"
323enum A { As, Bs, Cs, Ds(String), Es(B) }
324enum B { Xs, Ys }
325fn main() {
326 match A::As<|> {
327 A::Bs if 0 < 1 => {}
328 A::Ds(_value) => { let x = 1; }
329 A::Es(B::Xs) => (),
330 }
331}
332"#,
333 r#"
334enum A { As, Bs, Cs, Ds(String), Es(B) }
335enum B { Xs, Ys }
336fn main() {
337 match A::As {
338 A::Bs if 0 < 1 => {}
339 A::Ds(_value) => { let x = 1; }
340 A::Es(B::Xs) => (),
341 $0A::As => {}
342 A::Cs => {}
343 }
344}
345"#,
346 );
347 }
348
349 #[test]
350 fn partial_fill_bind_pat() {
351 check_assist(
352 fill_match_arms,
353 r#"
354enum A { As, Bs, Cs(Option<i32>) }
355fn main() {
356 match A::As<|> {
357 A::As(_) => {}
358 a @ A::Bs(_) => {}
359 }
360}
361"#,
362 r#"
363enum A { As, Bs, Cs(Option<i32>) }
364fn main() {
365 match A::As {
366 A::As(_) => {}
367 a @ A::Bs(_) => {}
368 A::Cs(${0:_}) => {}
369 }
370}
371"#,
372 );
373 }
374
375 #[test]
376 fn fill_match_arms_empty_body() {
377 check_assist(
378 fill_match_arms,
379 r#"
380enum A { As, Bs, Cs(String), Ds(String, String), Es { x: usize, y: usize } }
381
382fn main() {
383 let a = A::As;
384 match a<|> {}
385}
386"#,
387 r#"
388enum A { As, Bs, Cs(String), Ds(String, String), Es { x: usize, y: usize } }
389
390fn main() {
391 let a = A::As;
392 match a {
393 $0A::As => {}
394 A::Bs => {}
395 A::Cs(_) => {}
396 A::Ds(_, _) => {}
397 A::Es { x, y } => {}
398 }
399}
400"#,
401 );
402 }
403
404 #[test]
405 fn fill_match_arms_tuple_of_enum() {
406 check_assist(
407 fill_match_arms,
408 r#"
409 enum A { One, Two }
410 enum B { One, Two }
411
412 fn main() {
413 let a = A::One;
414 let b = B::One;
415 match (a<|>, b) {}
416 }
417 "#,
418 r#"
419 enum A { One, Two }
420 enum B { One, Two }
421
422 fn main() {
423 let a = A::One;
424 let b = B::One;
425 match (a, b) {
426 $0(A::One, B::One) => {}
427 (A::One, B::Two) => {}
428 (A::Two, B::One) => {}
429 (A::Two, B::Two) => {}
430 }
431 }
432 "#,
433 );
434 }
435
436 #[test]
437 fn fill_match_arms_tuple_of_enum_ref() {
438 check_assist(
439 fill_match_arms,
440 r#"
441 enum A { One, Two }
442 enum B { One, Two }
443
444 fn main() {
445 let a = A::One;
446 let b = B::One;
447 match (&a<|>, &b) {}
448 }
449 "#,
450 r#"
451 enum A { One, Two }
452 enum B { One, Two }
453
454 fn main() {
455 let a = A::One;
456 let b = B::One;
457 match (&a, &b) {
458 $0(A::One, B::One) => {}
459 (A::One, B::Two) => {}
460 (A::Two, B::One) => {}
461 (A::Two, B::Two) => {}
462 }
463 }
464 "#,
465 );
466 }
467
468 #[test]
469 fn fill_match_arms_tuple_of_enum_partial() {
470 check_assist_not_applicable(
471 fill_match_arms,
472 r#"
473 enum A { One, Two }
474 enum B { One, Two }
475
476 fn main() {
477 let a = A::One;
478 let b = B::One;
479 match (a<|>, b) {
480 (A::Two, B::One) => {}
481 }
482 }
483 "#,
484 );
485 }
486
487 #[test]
488 fn fill_match_arms_tuple_of_enum_not_applicable() {
489 check_assist_not_applicable(
490 fill_match_arms,
491 r#"
492 enum A { One, Two }
493 enum B { One, Two }
494
495 fn main() {
496 let a = A::One;
497 let b = B::One;
498 match (a<|>, b) {
499 (A::Two, B::One) => {}
500 (A::One, B::One) => {}
501 (A::One, B::Two) => {}
502 (A::Two, B::Two) => {}
503 }
504 }
505 "#,
506 );
507 }
508
509 #[test]
510 fn fill_match_arms_single_element_tuple_of_enum() {
511 // For now we don't hande the case of a single element tuple, but
512 // we could handle this in the future if `make::tuple_pat` allowed
513 // creating a tuple with a single pattern.
514 check_assist_not_applicable(
515 fill_match_arms,
516 r#"
517 enum A { One, Two }
518
519 fn main() {
520 let a = A::One;
521 match (a<|>, ) {
522 }
523 }
524 "#,
525 );
526 }
527
528 #[test]
529 fn test_fill_match_arm_refs() {
530 check_assist(
531 fill_match_arms,
532 r#"
533 enum A { As }
534
535 fn foo(a: &A) {
536 match a<|> {
537 }
538 }
539 "#,
540 r#"
541 enum A { As }
542
543 fn foo(a: &A) {
544 match a {
545 $0A::As => {}
546 }
547 }
548 "#,
549 );
550
551 check_assist(
552 fill_match_arms,
553 r#"
554 enum A {
555 Es { x: usize, y: usize }
556 }
557
558 fn foo(a: &mut A) {
559 match a<|> {
560 }
561 }
562 "#,
563 r#"
564 enum A {
565 Es { x: usize, y: usize }
566 }
567
568 fn foo(a: &mut A) {
569 match a {
570 $0A::Es { x, y } => {}
571 }
572 }
573 "#,
574 );
575 }
576
577 #[test]
578 fn fill_match_arms_target() {
579 check_assist_target(
580 fill_match_arms,
581 r#"
582 enum E { X, Y }
583
584 fn main() {
585 match E::X<|> {}
586 }
587 "#,
588 "match E::X {}",
589 );
590 }
591
592 #[test]
593 fn fill_match_arms_trivial_arm() {
594 check_assist(
595 fill_match_arms,
596 r#"
597 enum E { X, Y }
598
599 fn main() {
600 match E::X {
601 <|>_ => {}
602 }
603 }
604 "#,
605 r#"
606 enum E { X, Y }
607
608 fn main() {
609 match E::X {
610 $0E::X => {}
611 E::Y => {}
612 }
613 }
614 "#,
615 );
616 }
617
618 #[test]
619 fn fill_match_arms_qualifies_path() {
620 check_assist(
621 fill_match_arms,
622 r#"
623 mod foo { pub enum E { X, Y } }
624 use foo::E::X;
625
626 fn main() {
627 match X {
628 <|>
629 }
630 }
631 "#,
632 r#"
633 mod foo { pub enum E { X, Y } }
634 use foo::E::X;
635
636 fn main() {
637 match X {
638 $0X => {}
639 foo::E::Y => {}
640 }
641 }
642 "#,
643 );
644 }
645
646 #[test]
647 fn fill_match_arms_preserves_comments() {
648 check_assist(
649 fill_match_arms,
650 r#"
651 enum A { One, Two }
652 fn foo(a: A) {
653 match a {
654 // foo bar baz<|>
655 A::One => {}
656 // This is where the rest should be
657 }
658 }
659 "#,
660 r#"
661 enum A { One, Two }
662 fn foo(a: A) {
663 match a {
664 // foo bar baz
665 A::One => {}
666 // This is where the rest should be
667 $0A::Two => {}
668 }
669 }
670 "#,
671 );
672 }
673
674 #[test]
675 fn fill_match_arms_preserves_comments_empty() {
676 check_assist(
677 fill_match_arms,
678 r#"
679 enum A { One, Two }
680 fn foo(a: A) {
681 match a {
682 // foo bar baz<|>
683 }
684 }
685 "#,
686 r#"
687 enum A { One, Two }
688 fn foo(a: A) {
689 match a {
690 // foo bar baz
691 $0A::One => {}
692 A::Two => {}
693 }
694 }
695 "#,
696 );
697 }
698
699 #[test]
700 fn fill_match_arms_placeholder() {
701 check_assist(
702 fill_match_arms,
703 r#"
704 enum A { One, Two, }
705 fn foo(a: A) {
706 match a<|> {
707 _ => (),
708 }
709 }
710 "#,
711 r#"
712 enum A { One, Two, }
713 fn foo(a: A) {
714 match a {
715 $0A::One => {}
716 A::Two => {}
717 }
718 }
719 "#,
720 );
721 }
722
723 #[test]
724 fn option_order() {
725 mark::check!(option_order);
726 let before = r#"
727fn foo(opt: Option<i32>) {
728 match opt<|> {
729 }
730}
731"#;
732 let before = &format!("//- /main.rs crate:main deps:core{}{}", before, FamousDefs::FIXTURE);
733
734 check_assist(
735 fill_match_arms,
736 before,
737 r#"
738fn foo(opt: Option<i32>) {
739 match opt {
740 Some(${0:_}) => {}
741 None => {}
742 }
743}
744"#,
745 );
746 }
747}
diff --git a/crates/ra_assists/src/handlers/fix_visibility.rs b/crates/ra_assists/src/handlers/fix_visibility.rs
deleted file mode 100644
index 7cd76ea06..000000000
--- a/crates/ra_assists/src/handlers/fix_visibility.rs
+++ /dev/null
@@ -1,607 +0,0 @@
1use base_db::FileId;
2use hir::{db::HirDatabase, HasSource, HasVisibility, PathResolution};
3use syntax::{ast, AstNode, TextRange, TextSize};
4
5use crate::{utils::vis_offset, AssistContext, AssistId, AssistKind, Assists};
6use ast::VisibilityOwner;
7
8// FIXME: this really should be a fix for diagnostic, rather than an assist.
9
10// Assist: fix_visibility
11//
12// Makes inaccessible item public.
13//
14// ```
15// mod m {
16// fn frobnicate() {}
17// }
18// fn main() {
19// m::frobnicate<|>() {}
20// }
21// ```
22// ->
23// ```
24// mod m {
25// $0pub(crate) fn frobnicate() {}
26// }
27// fn main() {
28// m::frobnicate() {}
29// }
30// ```
31pub(crate) fn fix_visibility(acc: &mut Assists, ctx: &AssistContext) -> Option<()> {
32 add_vis_to_referenced_module_def(acc, ctx)
33 .or_else(|| add_vis_to_referenced_record_field(acc, ctx))
34}
35
36fn add_vis_to_referenced_module_def(acc: &mut Assists, ctx: &AssistContext) -> Option<()> {
37 let path: ast::Path = ctx.find_node_at_offset()?;
38 let path_res = ctx.sema.resolve_path(&path)?;
39 let def = match path_res {
40 PathResolution::Def(def) => def,
41 _ => return None,
42 };
43
44 let current_module = ctx.sema.scope(&path.syntax()).module()?;
45 let target_module = def.module(ctx.db())?;
46
47 let vis = target_module.visibility_of(ctx.db(), &def)?;
48 if vis.is_visible_from(ctx.db(), current_module.into()) {
49 return None;
50 };
51
52 let (offset, current_visibility, target, target_file, target_name) =
53 target_data_for_def(ctx.db(), def)?;
54
55 let missing_visibility =
56 if current_module.krate() == target_module.krate() { "pub(crate)" } else { "pub" };
57
58 let assist_label = match target_name {
59 None => format!("Change visibility to {}", missing_visibility),
60 Some(name) => format!("Change visibility of {} to {}", name, missing_visibility),
61 };
62
63 acc.add(AssistId("fix_visibility", AssistKind::QuickFix), assist_label, target, |builder| {
64 builder.edit_file(target_file);
65 match ctx.config.snippet_cap {
66 Some(cap) => match current_visibility {
67 Some(current_visibility) => builder.replace_snippet(
68 cap,
69 current_visibility.syntax().text_range(),
70 format!("$0{}", missing_visibility),
71 ),
72 None => builder.insert_snippet(cap, offset, format!("$0{} ", missing_visibility)),
73 },
74 None => match current_visibility {
75 Some(current_visibility) => {
76 builder.replace(current_visibility.syntax().text_range(), missing_visibility)
77 }
78 None => builder.insert(offset, format!("{} ", missing_visibility)),
79 },
80 }
81 })
82}
83
84fn add_vis_to_referenced_record_field(acc: &mut Assists, ctx: &AssistContext) -> Option<()> {
85 let record_field: ast::RecordExprField = ctx.find_node_at_offset()?;
86 let (record_field_def, _) = ctx.sema.resolve_record_field(&record_field)?;
87
88 let current_module = ctx.sema.scope(record_field.syntax()).module()?;
89 let visibility = record_field_def.visibility(ctx.db());
90 if visibility.is_visible_from(ctx.db(), current_module.into()) {
91 return None;
92 }
93
94 let parent = record_field_def.parent_def(ctx.db());
95 let parent_name = parent.name(ctx.db());
96 let target_module = parent.module(ctx.db());
97
98 let in_file_source = record_field_def.source(ctx.db());
99 let (offset, current_visibility, target) = match in_file_source.value {
100 hir::FieldSource::Named(it) => {
101 let s = it.syntax();
102 (vis_offset(s), it.visibility(), s.text_range())
103 }
104 hir::FieldSource::Pos(it) => {
105 let s = it.syntax();
106 (vis_offset(s), it.visibility(), s.text_range())
107 }
108 };
109
110 let missing_visibility =
111 if current_module.krate() == target_module.krate() { "pub(crate)" } else { "pub" };
112 let target_file = in_file_source.file_id.original_file(ctx.db());
113
114 let target_name = record_field_def.name(ctx.db());
115 let assist_label =
116 format!("Change visibility of {}.{} to {}", parent_name, target_name, missing_visibility);
117
118 acc.add(AssistId("fix_visibility", AssistKind::QuickFix), assist_label, target, |builder| {
119 builder.edit_file(target_file);
120 match ctx.config.snippet_cap {
121 Some(cap) => match current_visibility {
122 Some(current_visibility) => builder.replace_snippet(
123 cap,
124 current_visibility.syntax().text_range(),
125 format!("$0{}", missing_visibility),
126 ),
127 None => builder.insert_snippet(cap, offset, format!("$0{} ", missing_visibility)),
128 },
129 None => match current_visibility {
130 Some(current_visibility) => {
131 builder.replace(current_visibility.syntax().text_range(), missing_visibility)
132 }
133 None => builder.insert(offset, format!("{} ", missing_visibility)),
134 },
135 }
136 })
137}
138
139fn target_data_for_def(
140 db: &dyn HirDatabase,
141 def: hir::ModuleDef,
142) -> Option<(TextSize, Option<ast::Visibility>, TextRange, FileId, Option<hir::Name>)> {
143 fn offset_target_and_file_id<S, Ast>(
144 db: &dyn HirDatabase,
145 x: S,
146 ) -> (TextSize, Option<ast::Visibility>, TextRange, FileId)
147 where
148 S: HasSource<Ast = Ast>,
149 Ast: AstNode + ast::VisibilityOwner,
150 {
151 let source = x.source(db);
152 let in_file_syntax = source.syntax();
153 let file_id = in_file_syntax.file_id;
154 let syntax = in_file_syntax.value;
155 let current_visibility = source.value.visibility();
156 (
157 vis_offset(syntax),
158 current_visibility,
159 syntax.text_range(),
160 file_id.original_file(db.upcast()),
161 )
162 }
163
164 let target_name;
165 let (offset, current_visibility, target, target_file) = match def {
166 hir::ModuleDef::Function(f) => {
167 target_name = Some(f.name(db));
168 offset_target_and_file_id(db, f)
169 }
170 hir::ModuleDef::Adt(adt) => {
171 target_name = Some(adt.name(db));
172 match adt {
173 hir::Adt::Struct(s) => offset_target_and_file_id(db, s),
174 hir::Adt::Union(u) => offset_target_and_file_id(db, u),
175 hir::Adt::Enum(e) => offset_target_and_file_id(db, e),
176 }
177 }
178 hir::ModuleDef::Const(c) => {
179 target_name = c.name(db);
180 offset_target_and_file_id(db, c)
181 }
182 hir::ModuleDef::Static(s) => {
183 target_name = s.name(db);
184 offset_target_and_file_id(db, s)
185 }
186 hir::ModuleDef::Trait(t) => {
187 target_name = Some(t.name(db));
188 offset_target_and_file_id(db, t)
189 }
190 hir::ModuleDef::TypeAlias(t) => {
191 target_name = Some(t.name(db));
192 offset_target_and_file_id(db, t)
193 }
194 hir::ModuleDef::Module(m) => {
195 target_name = m.name(db);
196 let in_file_source = m.declaration_source(db)?;
197 let file_id = in_file_source.file_id.original_file(db.upcast());
198 let syntax = in_file_source.value.syntax();
199 (vis_offset(syntax), in_file_source.value.visibility(), syntax.text_range(), file_id)
200 }
201 // Enum variants can't be private, we can't modify builtin types
202 hir::ModuleDef::EnumVariant(_) | hir::ModuleDef::BuiltinType(_) => return None,
203 };
204
205 Some((offset, current_visibility, target, target_file, target_name))
206}
207
208#[cfg(test)]
209mod tests {
210 use crate::tests::{check_assist, check_assist_not_applicable};
211
212 use super::*;
213
214 #[test]
215 fn fix_visibility_of_fn() {
216 check_assist(
217 fix_visibility,
218 r"mod foo { fn foo() {} }
219 fn main() { foo::foo<|>() } ",
220 r"mod foo { $0pub(crate) fn foo() {} }
221 fn main() { foo::foo() } ",
222 );
223 check_assist_not_applicable(
224 fix_visibility,
225 r"mod foo { pub fn foo() {} }
226 fn main() { foo::foo<|>() } ",
227 )
228 }
229
230 #[test]
231 fn fix_visibility_of_adt_in_submodule() {
232 check_assist(
233 fix_visibility,
234 r"mod foo { struct Foo; }
235 fn main() { foo::Foo<|> } ",
236 r"mod foo { $0pub(crate) struct Foo; }
237 fn main() { foo::Foo } ",
238 );
239 check_assist_not_applicable(
240 fix_visibility,
241 r"mod foo { pub struct Foo; }
242 fn main() { foo::Foo<|> } ",
243 );
244 check_assist(
245 fix_visibility,
246 r"mod foo { enum Foo; }
247 fn main() { foo::Foo<|> } ",
248 r"mod foo { $0pub(crate) enum Foo; }
249 fn main() { foo::Foo } ",
250 );
251 check_assist_not_applicable(
252 fix_visibility,
253 r"mod foo { pub enum Foo; }
254 fn main() { foo::Foo<|> } ",
255 );
256 check_assist(
257 fix_visibility,
258 r"mod foo { union Foo; }
259 fn main() { foo::Foo<|> } ",
260 r"mod foo { $0pub(crate) union Foo; }
261 fn main() { foo::Foo } ",
262 );
263 check_assist_not_applicable(
264 fix_visibility,
265 r"mod foo { pub union Foo; }
266 fn main() { foo::Foo<|> } ",
267 );
268 }
269
270 #[test]
271 fn fix_visibility_of_adt_in_other_file() {
272 check_assist(
273 fix_visibility,
274 r"
275//- /main.rs
276mod foo;
277fn main() { foo::Foo<|> }
278
279//- /foo.rs
280struct Foo;
281",
282 r"$0pub(crate) struct Foo;
283",
284 );
285 }
286
287 #[test]
288 fn fix_visibility_of_struct_field() {
289 check_assist(
290 fix_visibility,
291 r"mod foo { pub struct Foo { bar: (), } }
292 fn main() { foo::Foo { <|>bar: () }; } ",
293 r"mod foo { pub struct Foo { $0pub(crate) bar: (), } }
294 fn main() { foo::Foo { bar: () }; } ",
295 );
296 check_assist(
297 fix_visibility,
298 r"
299//- /lib.rs
300mod foo;
301fn main() { foo::Foo { <|>bar: () }; }
302//- /foo.rs
303pub struct Foo { bar: () }
304",
305 r"pub struct Foo { $0pub(crate) bar: () }
306",
307 );
308 check_assist_not_applicable(
309 fix_visibility,
310 r"mod foo { pub struct Foo { pub bar: (), } }
311 fn main() { foo::Foo { <|>bar: () }; } ",
312 );
313 check_assist_not_applicable(
314 fix_visibility,
315 r"
316//- /lib.rs
317mod foo;
318fn main() { foo::Foo { <|>bar: () }; }
319//- /foo.rs
320pub struct Foo { pub bar: () }
321",
322 );
323 }
324
325 #[test]
326 fn fix_visibility_of_enum_variant_field() {
327 check_assist(
328 fix_visibility,
329 r"mod foo { pub enum Foo { Bar { bar: () } } }
330 fn main() { foo::Foo::Bar { <|>bar: () }; } ",
331 r"mod foo { pub enum Foo { Bar { $0pub(crate) bar: () } } }
332 fn main() { foo::Foo::Bar { bar: () }; } ",
333 );
334 check_assist(
335 fix_visibility,
336 r"
337//- /lib.rs
338mod foo;
339fn main() { foo::Foo::Bar { <|>bar: () }; }
340//- /foo.rs
341pub enum Foo { Bar { bar: () } }
342",
343 r"pub enum Foo { Bar { $0pub(crate) bar: () } }
344",
345 );
346 check_assist_not_applicable(
347 fix_visibility,
348 r"mod foo { pub struct Foo { pub bar: (), } }
349 fn main() { foo::Foo { <|>bar: () }; } ",
350 );
351 check_assist_not_applicable(
352 fix_visibility,
353 r"
354//- /lib.rs
355mod foo;
356fn main() { foo::Foo { <|>bar: () }; }
357//- /foo.rs
358pub struct Foo { pub bar: () }
359",
360 );
361 }
362
363 #[test]
364 #[ignore]
365 // FIXME reenable this test when `Semantics::resolve_record_field` works with union fields
366 fn fix_visibility_of_union_field() {
367 check_assist(
368 fix_visibility,
369 r"mod foo { pub union Foo { bar: (), } }
370 fn main() { foo::Foo { <|>bar: () }; } ",
371 r"mod foo { pub union Foo { $0pub(crate) bar: (), } }
372 fn main() { foo::Foo { bar: () }; } ",
373 );
374 check_assist(
375 fix_visibility,
376 r"
377//- /lib.rs
378mod foo;
379fn main() { foo::Foo { <|>bar: () }; }
380//- /foo.rs
381pub union Foo { bar: () }
382",
383 r"pub union Foo { $0pub(crate) bar: () }
384",
385 );
386 check_assist_not_applicable(
387 fix_visibility,
388 r"mod foo { pub union Foo { pub bar: (), } }
389 fn main() { foo::Foo { <|>bar: () }; } ",
390 );
391 check_assist_not_applicable(
392 fix_visibility,
393 r"
394//- /lib.rs
395mod foo;
396fn main() { foo::Foo { <|>bar: () }; }
397//- /foo.rs
398pub union Foo { pub bar: () }
399",
400 );
401 }
402
403 #[test]
404 fn fix_visibility_of_const() {
405 check_assist(
406 fix_visibility,
407 r"mod foo { const FOO: () = (); }
408 fn main() { foo::FOO<|> } ",
409 r"mod foo { $0pub(crate) const FOO: () = (); }
410 fn main() { foo::FOO } ",
411 );
412 check_assist_not_applicable(
413 fix_visibility,
414 r"mod foo { pub const FOO: () = (); }
415 fn main() { foo::FOO<|> } ",
416 );
417 }
418
419 #[test]
420 fn fix_visibility_of_static() {
421 check_assist(
422 fix_visibility,
423 r"mod foo { static FOO: () = (); }
424 fn main() { foo::FOO<|> } ",
425 r"mod foo { $0pub(crate) static FOO: () = (); }
426 fn main() { foo::FOO } ",
427 );
428 check_assist_not_applicable(
429 fix_visibility,
430 r"mod foo { pub static FOO: () = (); }
431 fn main() { foo::FOO<|> } ",
432 );
433 }
434
435 #[test]
436 fn fix_visibility_of_trait() {
437 check_assist(
438 fix_visibility,
439 r"mod foo { trait Foo { fn foo(&self) {} } }
440 fn main() { let x: &dyn foo::<|>Foo; } ",
441 r"mod foo { $0pub(crate) trait Foo { fn foo(&self) {} } }
442 fn main() { let x: &dyn foo::Foo; } ",
443 );
444 check_assist_not_applicable(
445 fix_visibility,
446 r"mod foo { pub trait Foo { fn foo(&self) {} } }
447 fn main() { let x: &dyn foo::Foo<|>; } ",
448 );
449 }
450
451 #[test]
452 fn fix_visibility_of_type_alias() {
453 check_assist(
454 fix_visibility,
455 r"mod foo { type Foo = (); }
456 fn main() { let x: foo::Foo<|>; } ",
457 r"mod foo { $0pub(crate) type Foo = (); }
458 fn main() { let x: foo::Foo; } ",
459 );
460 check_assist_not_applicable(
461 fix_visibility,
462 r"mod foo { pub type Foo = (); }
463 fn main() { let x: foo::Foo<|>; } ",
464 );
465 }
466
467 #[test]
468 fn fix_visibility_of_module() {
469 check_assist(
470 fix_visibility,
471 r"mod foo { mod bar { fn bar() {} } }
472 fn main() { foo::bar<|>::bar(); } ",
473 r"mod foo { $0pub(crate) mod bar { fn bar() {} } }
474 fn main() { foo::bar::bar(); } ",
475 );
476
477 check_assist(
478 fix_visibility,
479 r"
480//- /main.rs
481mod foo;
482fn main() { foo::bar<|>::baz(); }
483
484//- /foo.rs
485mod bar {
486 pub fn baz() {}
487}
488",
489 r"$0pub(crate) mod bar {
490 pub fn baz() {}
491}
492",
493 );
494
495 check_assist_not_applicable(
496 fix_visibility,
497 r"mod foo { pub mod bar { pub fn bar() {} } }
498 fn main() { foo::bar<|>::bar(); } ",
499 );
500 }
501
502 #[test]
503 fn fix_visibility_of_inline_module_in_other_file() {
504 check_assist(
505 fix_visibility,
506 r"
507//- /main.rs
508mod foo;
509fn main() { foo::bar<|>::baz(); }
510
511//- /foo.rs
512mod bar;
513//- /foo/bar.rs
514pub fn baz() {}
515",
516 r"$0pub(crate) mod bar;
517",
518 );
519 }
520
521 #[test]
522 fn fix_visibility_of_module_declaration_in_other_file() {
523 check_assist(
524 fix_visibility,
525 r"
526//- /main.rs
527mod foo;
528fn main() { foo::bar<|>>::baz(); }
529
530//- /foo.rs
531mod bar {
532 pub fn baz() {}
533}
534",
535 r"$0pub(crate) mod bar {
536 pub fn baz() {}
537}
538",
539 );
540 }
541
542 #[test]
543 fn adds_pub_when_target_is_in_another_crate() {
544 check_assist(
545 fix_visibility,
546 r"
547//- /main.rs crate:a deps:foo
548foo::Bar<|>
549//- /lib.rs crate:foo
550struct Bar;
551",
552 r"$0pub struct Bar;
553",
554 )
555 }
556
557 #[test]
558 fn replaces_pub_crate_with_pub() {
559 check_assist(
560 fix_visibility,
561 r"
562//- /main.rs crate:a deps:foo
563foo::Bar<|>
564//- /lib.rs crate:foo
565pub(crate) struct Bar;
566",
567 r"$0pub struct Bar;
568",
569 );
570 check_assist(
571 fix_visibility,
572 r"
573//- /main.rs crate:a deps:foo
574fn main() {
575 foo::Foo { <|>bar: () };
576}
577//- /lib.rs crate:foo
578pub struct Foo { pub(crate) bar: () }
579",
580 r"pub struct Foo { $0pub bar: () }
581",
582 );
583 }
584
585 #[test]
586 #[ignore]
587 // FIXME handle reexports properly
588 fn fix_visibility_of_reexport() {
589 check_assist(
590 fix_visibility,
591 r"
592 mod foo {
593 use bar::Baz;
594 mod bar { pub(super) struct Baz; }
595 }
596 foo::Baz<|>
597 ",
598 r"
599 mod foo {
600 $0pub(crate) use bar::Baz;
601 mod bar { pub(super) struct Baz; }
602 }
603 foo::Baz
604 ",
605 )
606 }
607}
diff --git a/crates/ra_assists/src/handlers/flip_binexpr.rs b/crates/ra_assists/src/handlers/flip_binexpr.rs
deleted file mode 100644
index 404f06133..000000000
--- a/crates/ra_assists/src/handlers/flip_binexpr.rs
+++ /dev/null
@@ -1,142 +0,0 @@
1use syntax::ast::{AstNode, BinExpr, BinOp};
2
3use crate::{AssistContext, AssistId, AssistKind, Assists};
4
5// Assist: flip_binexpr
6//
7// Flips operands of a binary expression.
8//
9// ```
10// fn main() {
11// let _ = 90 +<|> 2;
12// }
13// ```
14// ->
15// ```
16// fn main() {
17// let _ = 2 + 90;
18// }
19// ```
20pub(crate) fn flip_binexpr(acc: &mut Assists, ctx: &AssistContext) -> Option<()> {
21 let expr = ctx.find_node_at_offset::<BinExpr>()?;
22 let lhs = expr.lhs()?.syntax().clone();
23 let rhs = expr.rhs()?.syntax().clone();
24 let op_range = expr.op_token()?.text_range();
25 // The assist should be applied only if the cursor is on the operator
26 let cursor_in_range = op_range.contains_range(ctx.frange.range);
27 if !cursor_in_range {
28 return None;
29 }
30 let action: FlipAction = expr.op_kind()?.into();
31 // The assist should not be applied for certain operators
32 if let FlipAction::DontFlip = action {
33 return None;
34 }
35
36 acc.add(
37 AssistId("flip_binexpr", AssistKind::RefactorRewrite),
38 "Flip binary expression",
39 op_range,
40 |edit| {
41 if let FlipAction::FlipAndReplaceOp(new_op) = action {
42 edit.replace(op_range, new_op);
43 }
44 edit.replace(lhs.text_range(), rhs.text());
45 edit.replace(rhs.text_range(), lhs.text());
46 },
47 )
48}
49
50enum FlipAction {
51 // Flip the expression
52 Flip,
53 // Flip the expression and replace the operator with this string
54 FlipAndReplaceOp(&'static str),
55 // Do not flip the expression
56 DontFlip,
57}
58
59impl From<BinOp> for FlipAction {
60 fn from(op_kind: BinOp) -> Self {
61 match op_kind {
62 kind if kind.is_assignment() => FlipAction::DontFlip,
63 BinOp::GreaterTest => FlipAction::FlipAndReplaceOp("<"),
64 BinOp::GreaterEqualTest => FlipAction::FlipAndReplaceOp("<="),
65 BinOp::LesserTest => FlipAction::FlipAndReplaceOp(">"),
66 BinOp::LesserEqualTest => FlipAction::FlipAndReplaceOp(">="),
67 _ => FlipAction::Flip,
68 }
69 }
70}
71
72#[cfg(test)]
73mod tests {
74 use super::*;
75
76 use crate::tests::{check_assist, check_assist_not_applicable, check_assist_target};
77
78 #[test]
79 fn flip_binexpr_target_is_the_op() {
80 check_assist_target(flip_binexpr, "fn f() { let res = 1 ==<|> 2; }", "==")
81 }
82
83 #[test]
84 fn flip_binexpr_not_applicable_for_assignment() {
85 check_assist_not_applicable(flip_binexpr, "fn f() { let mut _x = 1; _x +=<|> 2 }")
86 }
87
88 #[test]
89 fn flip_binexpr_works_for_eq() {
90 check_assist(
91 flip_binexpr,
92 "fn f() { let res = 1 ==<|> 2; }",
93 "fn f() { let res = 2 == 1; }",
94 )
95 }
96
97 #[test]
98 fn flip_binexpr_works_for_gt() {
99 check_assist(flip_binexpr, "fn f() { let res = 1 ><|> 2; }", "fn f() { let res = 2 < 1; }")
100 }
101
102 #[test]
103 fn flip_binexpr_works_for_lteq() {
104 check_assist(
105 flip_binexpr,
106 "fn f() { let res = 1 <=<|> 2; }",
107 "fn f() { let res = 2 >= 1; }",
108 )
109 }
110
111 #[test]
112 fn flip_binexpr_works_for_complex_expr() {
113 check_assist(
114 flip_binexpr,
115 "fn f() { let res = (1 + 1) ==<|> (2 + 2); }",
116 "fn f() { let res = (2 + 2) == (1 + 1); }",
117 )
118 }
119
120 #[test]
121 fn flip_binexpr_works_inside_match() {
122 check_assist(
123 flip_binexpr,
124 r#"
125 fn dyn_eq(&self, other: &dyn Diagnostic) -> bool {
126 match other.downcast_ref::<Self>() {
127 None => false,
128 Some(it) => it ==<|> self,
129 }
130 }
131 "#,
132 r#"
133 fn dyn_eq(&self, other: &dyn Diagnostic) -> bool {
134 match other.downcast_ref::<Self>() {
135 None => false,
136 Some(it) => self == it,
137 }
138 }
139 "#,
140 )
141 }
142}
diff --git a/crates/ra_assists/src/handlers/flip_comma.rs b/crates/ra_assists/src/handlers/flip_comma.rs
deleted file mode 100644
index 5c69db53e..000000000
--- a/crates/ra_assists/src/handlers/flip_comma.rs
+++ /dev/null
@@ -1,84 +0,0 @@
1use syntax::{algo::non_trivia_sibling, Direction, T};
2
3use crate::{AssistContext, AssistId, AssistKind, Assists};
4
5// Assist: flip_comma
6//
7// Flips two comma-separated items.
8//
9// ```
10// fn main() {
11// ((1, 2),<|> (3, 4));
12// }
13// ```
14// ->
15// ```
16// fn main() {
17// ((3, 4), (1, 2));
18// }
19// ```
20pub(crate) fn flip_comma(acc: &mut Assists, ctx: &AssistContext) -> Option<()> {
21 let comma = ctx.find_token_at_offset(T![,])?;
22 let prev = non_trivia_sibling(comma.clone().into(), Direction::Prev)?;
23 let next = non_trivia_sibling(comma.clone().into(), Direction::Next)?;
24
25 // Don't apply a "flip" in case of a last comma
26 // that typically comes before punctuation
27 if next.kind().is_punct() {
28 return None;
29 }
30
31 acc.add(
32 AssistId("flip_comma", AssistKind::RefactorRewrite),
33 "Flip comma",
34 comma.text_range(),
35 |edit| {
36 edit.replace(prev.text_range(), next.to_string());
37 edit.replace(next.text_range(), prev.to_string());
38 },
39 )
40}
41
42#[cfg(test)]
43mod tests {
44 use super::*;
45
46 use crate::tests::{check_assist, check_assist_target};
47
48 #[test]
49 fn flip_comma_works_for_function_parameters() {
50 check_assist(
51 flip_comma,
52 "fn foo(x: i32,<|> y: Result<(), ()>) {}",
53 "fn foo(y: Result<(), ()>, x: i32) {}",
54 )
55 }
56
57 #[test]
58 fn flip_comma_target() {
59 check_assist_target(flip_comma, "fn foo(x: i32,<|> y: Result<(), ()>) {}", ",")
60 }
61
62 #[test]
63 #[should_panic]
64 fn flip_comma_before_punct() {
65 // See https://github.com/rust-analyzer/rust-analyzer/issues/1619
66 // "Flip comma" assist shouldn't be applicable to the last comma in enum or struct
67 // declaration body.
68 check_assist_target(
69 flip_comma,
70 "pub enum Test { \
71 A,<|> \
72 }",
73 ",",
74 );
75
76 check_assist_target(
77 flip_comma,
78 "pub struct Test { \
79 foo: usize,<|> \
80 }",
81 ",",
82 );
83 }
84}
diff --git a/crates/ra_assists/src/handlers/flip_trait_bound.rs b/crates/ra_assists/src/handlers/flip_trait_bound.rs
deleted file mode 100644
index 347e79b1d..000000000
--- a/crates/ra_assists/src/handlers/flip_trait_bound.rs
+++ /dev/null
@@ -1,121 +0,0 @@
1use syntax::{
2 algo::non_trivia_sibling,
3 ast::{self, AstNode},
4 Direction, T,
5};
6
7use crate::{AssistContext, AssistId, AssistKind, Assists};
8
9// Assist: flip_trait_bound
10//
11// Flips two trait bounds.
12//
13// ```
14// fn foo<T: Clone +<|> Copy>() { }
15// ```
16// ->
17// ```
18// fn foo<T: Copy + Clone>() { }
19// ```
20pub(crate) fn flip_trait_bound(acc: &mut Assists, ctx: &AssistContext) -> Option<()> {
21 // We want to replicate the behavior of `flip_binexpr` by only suggesting
22 // the assist when the cursor is on a `+`
23 let plus = ctx.find_token_at_offset(T![+])?;
24
25 // Make sure we're in a `TypeBoundList`
26 if ast::TypeBoundList::cast(plus.parent()).is_none() {
27 return None;
28 }
29
30 let (before, after) = (
31 non_trivia_sibling(plus.clone().into(), Direction::Prev)?,
32 non_trivia_sibling(plus.clone().into(), Direction::Next)?,
33 );
34
35 let target = plus.text_range();
36 acc.add(
37 AssistId("flip_trait_bound", AssistKind::RefactorRewrite),
38 "Flip trait bounds",
39 target,
40 |edit| {
41 edit.replace(before.text_range(), after.to_string());
42 edit.replace(after.text_range(), before.to_string());
43 },
44 )
45}
46
47#[cfg(test)]
48mod tests {
49 use super::*;
50
51 use crate::tests::{check_assist, check_assist_not_applicable, check_assist_target};
52
53 #[test]
54 fn flip_trait_bound_assist_available() {
55 check_assist_target(flip_trait_bound, "struct S<T> where T: A <|>+ B + C { }", "+")
56 }
57
58 #[test]
59 fn flip_trait_bound_not_applicable_for_single_trait_bound() {
60 check_assist_not_applicable(flip_trait_bound, "struct S<T> where T: <|>A { }")
61 }
62
63 #[test]
64 fn flip_trait_bound_works_for_struct() {
65 check_assist(
66 flip_trait_bound,
67 "struct S<T> where T: A <|>+ B { }",
68 "struct S<T> where T: B + A { }",
69 )
70 }
71
72 #[test]
73 fn flip_trait_bound_works_for_trait_impl() {
74 check_assist(
75 flip_trait_bound,
76 "impl X for S<T> where T: A +<|> B { }",
77 "impl X for S<T> where T: B + A { }",
78 )
79 }
80
81 #[test]
82 fn flip_trait_bound_works_for_fn() {
83 check_assist(flip_trait_bound, "fn f<T: A <|>+ B>(t: T) { }", "fn f<T: B + A>(t: T) { }")
84 }
85
86 #[test]
87 fn flip_trait_bound_works_for_fn_where_clause() {
88 check_assist(
89 flip_trait_bound,
90 "fn f<T>(t: T) where T: A +<|> B { }",
91 "fn f<T>(t: T) where T: B + A { }",
92 )
93 }
94
95 #[test]
96 fn flip_trait_bound_works_for_lifetime() {
97 check_assist(
98 flip_trait_bound,
99 "fn f<T>(t: T) where T: A <|>+ 'static { }",
100 "fn f<T>(t: T) where T: 'static + A { }",
101 )
102 }
103
104 #[test]
105 fn flip_trait_bound_works_for_complex_bounds() {
106 check_assist(
107 flip_trait_bound,
108 "struct S<T> where T: A<T> <|>+ b_mod::B<T> + C<T> { }",
109 "struct S<T> where T: b_mod::B<T> + A<T> + C<T> { }",
110 )
111 }
112
113 #[test]
114 fn flip_trait_bound_works_for_long_bounds() {
115 check_assist(
116 flip_trait_bound,
117 "struct S<T> where T: A + B + C + D + E + F +<|> G + H + I + J { }",
118 "struct S<T> where T: A + B + C + D + E + G + F + H + I + J { }",
119 )
120 }
121}
diff --git a/crates/ra_assists/src/handlers/generate_derive.rs b/crates/ra_assists/src/handlers/generate_derive.rs
deleted file mode 100644
index 314504e15..000000000
--- a/crates/ra_assists/src/handlers/generate_derive.rs
+++ /dev/null
@@ -1,132 +0,0 @@
1use syntax::{
2 ast::{self, AstNode, AttrsOwner},
3 SyntaxKind::{COMMENT, WHITESPACE},
4 TextSize,
5};
6
7use crate::{AssistContext, AssistId, AssistKind, Assists};
8
9// Assist: generate_derive
10//
11// Adds a new `#[derive()]` clause to a struct or enum.
12//
13// ```
14// struct Point {
15// x: u32,
16// y: u32,<|>
17// }
18// ```
19// ->
20// ```
21// #[derive($0)]
22// struct Point {
23// x: u32,
24// y: u32,
25// }
26// ```
27pub(crate) fn generate_derive(acc: &mut Assists, ctx: &AssistContext) -> Option<()> {
28 let cap = ctx.config.snippet_cap?;
29 let nominal = ctx.find_node_at_offset::<ast::AdtDef>()?;
30 let node_start = derive_insertion_offset(&nominal)?;
31 let target = nominal.syntax().text_range();
32 acc.add(
33 AssistId("generate_derive", AssistKind::Generate),
34 "Add `#[derive]`",
35 target,
36 |builder| {
37 let derive_attr = nominal
38 .attrs()
39 .filter_map(|x| x.as_simple_call())
40 .filter(|(name, _arg)| name == "derive")
41 .map(|(_name, arg)| arg)
42 .next();
43 match derive_attr {
44 None => {
45 builder.insert_snippet(cap, node_start, "#[derive($0)]\n");
46 }
47 Some(tt) => {
48 // Just move the cursor.
49 builder.insert_snippet(
50 cap,
51 tt.syntax().text_range().end() - TextSize::of(')'),
52 "$0",
53 )
54 }
55 };
56 },
57 )
58}
59
60// Insert `derive` after doc comments.
61fn derive_insertion_offset(nominal: &ast::AdtDef) -> Option<TextSize> {
62 let non_ws_child = nominal
63 .syntax()
64 .children_with_tokens()
65 .find(|it| it.kind() != COMMENT && it.kind() != WHITESPACE)?;
66 Some(non_ws_child.text_range().start())
67}
68
69#[cfg(test)]
70mod tests {
71 use crate::tests::{check_assist, check_assist_target};
72
73 use super::*;
74
75 #[test]
76 fn add_derive_new() {
77 check_assist(
78 generate_derive,
79 "struct Foo { a: i32, <|>}",
80 "#[derive($0)]\nstruct Foo { a: i32, }",
81 );
82 check_assist(
83 generate_derive,
84 "struct Foo { <|> a: i32, }",
85 "#[derive($0)]\nstruct Foo { a: i32, }",
86 );
87 }
88
89 #[test]
90 fn add_derive_existing() {
91 check_assist(
92 generate_derive,
93 "#[derive(Clone)]\nstruct Foo { a: i32<|>, }",
94 "#[derive(Clone$0)]\nstruct Foo { a: i32, }",
95 );
96 }
97
98 #[test]
99 fn add_derive_new_with_doc_comment() {
100 check_assist(
101 generate_derive,
102 "
103/// `Foo` is a pretty important struct.
104/// It does stuff.
105struct Foo { a: i32<|>, }
106 ",
107 "
108/// `Foo` is a pretty important struct.
109/// It does stuff.
110#[derive($0)]
111struct Foo { a: i32, }
112 ",
113 );
114 }
115
116 #[test]
117 fn add_derive_target() {
118 check_assist_target(
119 generate_derive,
120 "
121struct SomeThingIrrelevant;
122/// `Foo` is a pretty important struct.
123/// It does stuff.
124struct Foo { a: i32<|>, }
125struct EvenMoreIrrelevant;
126 ",
127 "/// `Foo` is a pretty important struct.
128/// It does stuff.
129struct Foo { a: i32, }",
130 );
131 }
132}
diff --git a/crates/ra_assists/src/handlers/generate_from_impl_for_enum.rs b/crates/ra_assists/src/handlers/generate_from_impl_for_enum.rs
deleted file mode 100644
index 7f04b9572..000000000
--- a/crates/ra_assists/src/handlers/generate_from_impl_for_enum.rs
+++ /dev/null
@@ -1,200 +0,0 @@
1use ide_db::RootDatabase;
2use syntax::ast::{self, AstNode, NameOwner};
3use test_utils::mark;
4
5use crate::{utils::FamousDefs, AssistContext, AssistId, AssistKind, Assists};
6
7// Assist: generate_from_impl_for_enum
8//
9// Adds a From impl for an enum variant with one tuple field.
10//
11// ```
12// enum A { <|>One(u32) }
13// ```
14// ->
15// ```
16// enum A { One(u32) }
17//
18// impl From<u32> for A {
19// fn from(v: u32) -> Self {
20// A::One(v)
21// }
22// }
23// ```
24pub(crate) fn generate_from_impl_for_enum(acc: &mut Assists, ctx: &AssistContext) -> Option<()> {
25 let variant = ctx.find_node_at_offset::<ast::Variant>()?;
26 let variant_name = variant.name()?;
27 let enum_name = variant.parent_enum().name()?;
28 let field_list = match variant.kind() {
29 ast::StructKind::Tuple(field_list) => field_list,
30 _ => return None,
31 };
32 if field_list.fields().count() != 1 {
33 return None;
34 }
35 let field_type = field_list.fields().next()?.ty()?;
36 let path = match field_type {
37 ast::Type::PathType(it) => it,
38 _ => return None,
39 };
40
41 if existing_from_impl(&ctx.sema, &variant).is_some() {
42 mark::hit!(test_add_from_impl_already_exists);
43 return None;
44 }
45
46 let target = variant.syntax().text_range();
47 acc.add(
48 AssistId("generate_from_impl_for_enum", AssistKind::Generate),
49 "Generate `From` impl for this enum variant",
50 target,
51 |edit| {
52 let start_offset = variant.parent_enum().syntax().text_range().end();
53 let buf = format!(
54 r#"
55
56impl From<{0}> for {1} {{
57 fn from(v: {0}) -> Self {{
58 {1}::{2}(v)
59 }}
60}}"#,
61 path.syntax(),
62 enum_name,
63 variant_name
64 );
65 edit.insert(start_offset, buf);
66 },
67 )
68}
69
70fn existing_from_impl(
71 sema: &'_ hir::Semantics<'_, RootDatabase>,
72 variant: &ast::Variant,
73) -> Option<()> {
74 let variant = sema.to_def(variant)?;
75 let enum_ = variant.parent_enum(sema.db);
76 let krate = enum_.module(sema.db).krate();
77
78 let from_trait = FamousDefs(sema, krate).core_convert_From()?;
79
80 let enum_type = enum_.ty(sema.db);
81
82 let wrapped_type = variant.fields(sema.db).get(0)?.signature_ty(sema.db);
83
84 if enum_type.impls_trait(sema.db, from_trait, &[wrapped_type]) {
85 Some(())
86 } else {
87 None
88 }
89}
90
91#[cfg(test)]
92mod tests {
93 use test_utils::mark;
94
95 use crate::tests::{check_assist, check_assist_not_applicable};
96
97 use super::*;
98
99 #[test]
100 fn test_generate_from_impl_for_enum() {
101 check_assist(
102 generate_from_impl_for_enum,
103 "enum A { <|>One(u32) }",
104 r#"enum A { One(u32) }
105
106impl From<u32> for A {
107 fn from(v: u32) -> Self {
108 A::One(v)
109 }
110}"#,
111 );
112 }
113
114 #[test]
115 fn test_generate_from_impl_for_enum_complicated_path() {
116 check_assist(
117 generate_from_impl_for_enum,
118 r#"enum A { <|>One(foo::bar::baz::Boo) }"#,
119 r#"enum A { One(foo::bar::baz::Boo) }
120
121impl From<foo::bar::baz::Boo> for A {
122 fn from(v: foo::bar::baz::Boo) -> Self {
123 A::One(v)
124 }
125}"#,
126 );
127 }
128
129 fn check_not_applicable(ra_fixture: &str) {
130 let fixture =
131 format!("//- /main.rs crate:main deps:core\n{}\n{}", ra_fixture, FamousDefs::FIXTURE);
132 check_assist_not_applicable(generate_from_impl_for_enum, &fixture)
133 }
134
135 #[test]
136 fn test_add_from_impl_no_element() {
137 check_not_applicable("enum A { <|>One }");
138 }
139
140 #[test]
141 fn test_add_from_impl_more_than_one_element_in_tuple() {
142 check_not_applicable("enum A { <|>One(u32, String) }");
143 }
144
145 #[test]
146 fn test_add_from_impl_struct_variant() {
147 check_not_applicable("enum A { <|>One { x: u32 } }");
148 }
149
150 #[test]
151 fn test_add_from_impl_already_exists() {
152 mark::check!(test_add_from_impl_already_exists);
153 check_not_applicable(
154 r#"
155enum A { <|>One(u32), }
156
157impl From<u32> for A {
158 fn from(v: u32) -> Self {
159 A::One(v)
160 }
161}
162"#,
163 );
164 }
165
166 #[test]
167 fn test_add_from_impl_different_variant_impl_exists() {
168 check_assist(
169 generate_from_impl_for_enum,
170 r#"enum A { <|>One(u32), Two(String), }
171
172impl From<String> for A {
173 fn from(v: String) -> Self {
174 A::Two(v)
175 }
176}
177
178pub trait From<T> {
179 fn from(T) -> Self;
180}"#,
181 r#"enum A { One(u32), Two(String), }
182
183impl From<u32> for A {
184 fn from(v: u32) -> Self {
185 A::One(v)
186 }
187}
188
189impl From<String> for A {
190 fn from(v: String) -> Self {
191 A::Two(v)
192 }
193}
194
195pub trait From<T> {
196 fn from(T) -> Self;
197}"#,
198 );
199 }
200}
diff --git a/crates/ra_assists/src/handlers/generate_function.rs b/crates/ra_assists/src/handlers/generate_function.rs
deleted file mode 100644
index b38d64058..000000000
--- a/crates/ra_assists/src/handlers/generate_function.rs
+++ /dev/null
@@ -1,1058 +0,0 @@
1use base_db::FileId;
2use hir::HirDisplay;
3use rustc_hash::{FxHashMap, FxHashSet};
4use syntax::{
5 ast::{
6 self,
7 edit::{AstNodeEdit, IndentLevel},
8 make, ArgListOwner, AstNode, ModuleItemOwner,
9 },
10 SyntaxKind, SyntaxNode, TextSize,
11};
12
13use crate::{
14 assist_config::SnippetCap,
15 utils::{render_snippet, Cursor},
16 AssistContext, AssistId, AssistKind, Assists,
17};
18
19// Assist: generate_function
20//
21// Adds a stub function with a signature matching the function under the cursor.
22//
23// ```
24// struct Baz;
25// fn baz() -> Baz { Baz }
26// fn foo() {
27// bar<|>("", baz());
28// }
29//
30// ```
31// ->
32// ```
33// struct Baz;
34// fn baz() -> Baz { Baz }
35// fn foo() {
36// bar("", baz());
37// }
38//
39// fn bar(arg: &str, baz: Baz) {
40// ${0:todo!()}
41// }
42//
43// ```
44pub(crate) fn generate_function(acc: &mut Assists, ctx: &AssistContext) -> Option<()> {
45 let path_expr: ast::PathExpr = ctx.find_node_at_offset()?;
46 let call = path_expr.syntax().parent().and_then(ast::CallExpr::cast)?;
47 let path = path_expr.path()?;
48
49 if ctx.sema.resolve_path(&path).is_some() {
50 // The function call already resolves, no need to add a function
51 return None;
52 }
53
54 let target_module = match path.qualifier() {
55 Some(qualifier) => match ctx.sema.resolve_path(&qualifier) {
56 Some(hir::PathResolution::Def(hir::ModuleDef::Module(module))) => Some(module),
57 _ => return None,
58 },
59 None => None,
60 };
61
62 let function_builder = FunctionBuilder::from_call(&ctx, &call, &path, target_module)?;
63
64 let target = call.syntax().text_range();
65 acc.add(
66 AssistId("generate_function", AssistKind::Generate),
67 format!("Generate `{}` function", function_builder.fn_name),
68 target,
69 |builder| {
70 let function_template = function_builder.render();
71 builder.edit_file(function_template.file);
72 let new_fn = function_template.to_string(ctx.config.snippet_cap);
73 match ctx.config.snippet_cap {
74 Some(cap) => builder.insert_snippet(cap, function_template.insert_offset, new_fn),
75 None => builder.insert(function_template.insert_offset, new_fn),
76 }
77 },
78 )
79}
80
81struct FunctionTemplate {
82 insert_offset: TextSize,
83 placeholder_expr: ast::MacroCall,
84 leading_ws: String,
85 fn_def: ast::Fn,
86 trailing_ws: String,
87 file: FileId,
88}
89
90impl FunctionTemplate {
91 fn to_string(&self, cap: Option<SnippetCap>) -> String {
92 let f = match cap {
93 Some(cap) => render_snippet(
94 cap,
95 self.fn_def.syntax(),
96 Cursor::Replace(self.placeholder_expr.syntax()),
97 ),
98 None => self.fn_def.to_string(),
99 };
100 format!("{}{}{}", self.leading_ws, f, self.trailing_ws)
101 }
102}
103
104struct FunctionBuilder {
105 target: GeneratedFunctionTarget,
106 fn_name: ast::Name,
107 type_params: Option<ast::GenericParamList>,
108 params: ast::ParamList,
109 file: FileId,
110 needs_pub: bool,
111}
112
113impl FunctionBuilder {
114 /// Prepares a generated function that matches `call`.
115 /// The function is generated in `target_module` or next to `call`
116 fn from_call(
117 ctx: &AssistContext,
118 call: &ast::CallExpr,
119 path: &ast::Path,
120 target_module: Option<hir::Module>,
121 ) -> Option<Self> {
122 let mut file = ctx.frange.file_id;
123 let target = match &target_module {
124 Some(target_module) => {
125 let module_source = target_module.definition_source(ctx.db());
126 let (in_file, target) = next_space_for_fn_in_module(ctx.sema.db, &module_source)?;
127 file = in_file;
128 target
129 }
130 None => next_space_for_fn_after_call_site(&call)?,
131 };
132 let needs_pub = target_module.is_some();
133 let target_module = target_module.or_else(|| ctx.sema.scope(target.syntax()).module())?;
134 let fn_name = fn_name(&path)?;
135 let (type_params, params) = fn_args(ctx, target_module, &call)?;
136
137 Some(Self { target, fn_name, type_params, params, file, needs_pub })
138 }
139
140 fn render(self) -> FunctionTemplate {
141 let placeholder_expr = make::expr_todo();
142 let fn_body = make::block_expr(vec![], Some(placeholder_expr));
143 let visibility = if self.needs_pub { Some(make::visibility_pub_crate()) } else { None };
144 let mut fn_def =
145 make::fn_(visibility, self.fn_name, self.type_params, self.params, fn_body);
146 let leading_ws;
147 let trailing_ws;
148
149 let insert_offset = match self.target {
150 GeneratedFunctionTarget::BehindItem(it) => {
151 let indent = IndentLevel::from_node(&it);
152 leading_ws = format!("\n\n{}", indent);
153 fn_def = fn_def.indent(indent);
154 trailing_ws = String::new();
155 it.text_range().end()
156 }
157 GeneratedFunctionTarget::InEmptyItemList(it) => {
158 let indent = IndentLevel::from_node(it.syntax());
159 leading_ws = format!("\n{}", indent + 1);
160 fn_def = fn_def.indent(indent + 1);
161 trailing_ws = format!("\n{}", indent);
162 it.syntax().text_range().start() + TextSize::of('{')
163 }
164 };
165
166 let placeholder_expr =
167 fn_def.syntax().descendants().find_map(ast::MacroCall::cast).unwrap();
168 FunctionTemplate {
169 insert_offset,
170 placeholder_expr,
171 leading_ws,
172 fn_def,
173 trailing_ws,
174 file: self.file,
175 }
176 }
177}
178
179enum GeneratedFunctionTarget {
180 BehindItem(SyntaxNode),
181 InEmptyItemList(ast::ItemList),
182}
183
184impl GeneratedFunctionTarget {
185 fn syntax(&self) -> &SyntaxNode {
186 match self {
187 GeneratedFunctionTarget::BehindItem(it) => it,
188 GeneratedFunctionTarget::InEmptyItemList(it) => it.syntax(),
189 }
190 }
191}
192
193fn fn_name(call: &ast::Path) -> Option<ast::Name> {
194 let name = call.segment()?.syntax().to_string();
195 Some(make::name(&name))
196}
197
198/// Computes the type variables and arguments required for the generated function
199fn fn_args(
200 ctx: &AssistContext,
201 target_module: hir::Module,
202 call: &ast::CallExpr,
203) -> Option<(Option<ast::GenericParamList>, ast::ParamList)> {
204 let mut arg_names = Vec::new();
205 let mut arg_types = Vec::new();
206 for arg in call.arg_list()?.args() {
207 arg_names.push(match fn_arg_name(&arg) {
208 Some(name) => name,
209 None => String::from("arg"),
210 });
211 arg_types.push(match fn_arg_type(ctx, target_module, &arg) {
212 Some(ty) => ty,
213 None => String::from("()"),
214 });
215 }
216 deduplicate_arg_names(&mut arg_names);
217 let params = arg_names.into_iter().zip(arg_types).map(|(name, ty)| make::param(name, ty));
218 Some((None, make::param_list(params)))
219}
220
221/// Makes duplicate argument names unique by appending incrementing numbers.
222///
223/// ```
224/// let mut names: Vec<String> =
225/// vec!["foo".into(), "foo".into(), "bar".into(), "baz".into(), "bar".into()];
226/// deduplicate_arg_names(&mut names);
227/// let expected: Vec<String> =
228/// vec!["foo_1".into(), "foo_2".into(), "bar_1".into(), "baz".into(), "bar_2".into()];
229/// assert_eq!(names, expected);
230/// ```
231fn deduplicate_arg_names(arg_names: &mut Vec<String>) {
232 let arg_name_counts = arg_names.iter().fold(FxHashMap::default(), |mut m, name| {
233 *m.entry(name).or_insert(0) += 1;
234 m
235 });
236 let duplicate_arg_names: FxHashSet<String> = arg_name_counts
237 .into_iter()
238 .filter(|(_, count)| *count >= 2)
239 .map(|(name, _)| name.clone())
240 .collect();
241
242 let mut counter_per_name = FxHashMap::default();
243 for arg_name in arg_names.iter_mut() {
244 if duplicate_arg_names.contains(arg_name) {
245 let counter = counter_per_name.entry(arg_name.clone()).or_insert(1);
246 arg_name.push('_');
247 arg_name.push_str(&counter.to_string());
248 *counter += 1;
249 }
250 }
251}
252
253fn fn_arg_name(fn_arg: &ast::Expr) -> Option<String> {
254 match fn_arg {
255 ast::Expr::CastExpr(cast_expr) => fn_arg_name(&cast_expr.expr()?),
256 _ => Some(
257 fn_arg
258 .syntax()
259 .descendants()
260 .filter(|d| ast::NameRef::can_cast(d.kind()))
261 .last()?
262 .to_string(),
263 ),
264 }
265}
266
267fn fn_arg_type(
268 ctx: &AssistContext,
269 target_module: hir::Module,
270 fn_arg: &ast::Expr,
271) -> Option<String> {
272 let ty = ctx.sema.type_of_expr(fn_arg)?;
273 if ty.is_unknown() {
274 return None;
275 }
276
277 if let Ok(rendered) = ty.display_source_code(ctx.db(), target_module.into()) {
278 Some(rendered)
279 } else {
280 None
281 }
282}
283
284/// Returns the position inside the current mod or file
285/// directly after the current block
286/// We want to write the generated function directly after
287/// fns, impls or macro calls, but inside mods
288fn next_space_for_fn_after_call_site(expr: &ast::CallExpr) -> Option<GeneratedFunctionTarget> {
289 let mut ancestors = expr.syntax().ancestors().peekable();
290 let mut last_ancestor: Option<SyntaxNode> = None;
291 while let Some(next_ancestor) = ancestors.next() {
292 match next_ancestor.kind() {
293 SyntaxKind::SOURCE_FILE => {
294 break;
295 }
296 SyntaxKind::ITEM_LIST => {
297 if ancestors.peek().map(|a| a.kind()) == Some(SyntaxKind::MODULE) {
298 break;
299 }
300 }
301 _ => {}
302 }
303 last_ancestor = Some(next_ancestor);
304 }
305 last_ancestor.map(GeneratedFunctionTarget::BehindItem)
306}
307
308fn next_space_for_fn_in_module(
309 db: &dyn hir::db::AstDatabase,
310 module_source: &hir::InFile<hir::ModuleSource>,
311) -> Option<(FileId, GeneratedFunctionTarget)> {
312 let file = module_source.file_id.original_file(db);
313 let assist_item = match &module_source.value {
314 hir::ModuleSource::SourceFile(it) => {
315 if let Some(last_item) = it.items().last() {
316 GeneratedFunctionTarget::BehindItem(last_item.syntax().clone())
317 } else {
318 GeneratedFunctionTarget::BehindItem(it.syntax().clone())
319 }
320 }
321 hir::ModuleSource::Module(it) => {
322 if let Some(last_item) = it.item_list().and_then(|it| it.items().last()) {
323 GeneratedFunctionTarget::BehindItem(last_item.syntax().clone())
324 } else {
325 GeneratedFunctionTarget::InEmptyItemList(it.item_list()?)
326 }
327 }
328 };
329 Some((file, assist_item))
330}
331
332#[cfg(test)]
333mod tests {
334 use crate::tests::{check_assist, check_assist_not_applicable};
335
336 use super::*;
337
338 #[test]
339 fn add_function_with_no_args() {
340 check_assist(
341 generate_function,
342 r"
343fn foo() {
344 bar<|>();
345}
346",
347 r"
348fn foo() {
349 bar();
350}
351
352fn bar() {
353 ${0:todo!()}
354}
355",
356 )
357 }
358
359 #[test]
360 fn add_function_from_method() {
361 // This ensures that the function is correctly generated
362 // in the next outer mod or file
363 check_assist(
364 generate_function,
365 r"
366impl Foo {
367 fn foo() {
368 bar<|>();
369 }
370}
371",
372 r"
373impl Foo {
374 fn foo() {
375 bar();
376 }
377}
378
379fn bar() {
380 ${0:todo!()}
381}
382",
383 )
384 }
385
386 #[test]
387 fn add_function_directly_after_current_block() {
388 // The new fn should not be created at the end of the file or module
389 check_assist(
390 generate_function,
391 r"
392fn foo1() {
393 bar<|>();
394}
395
396fn foo2() {}
397",
398 r"
399fn foo1() {
400 bar();
401}
402
403fn bar() {
404 ${0:todo!()}
405}
406
407fn foo2() {}
408",
409 )
410 }
411
412 #[test]
413 fn add_function_with_no_args_in_same_module() {
414 check_assist(
415 generate_function,
416 r"
417mod baz {
418 fn foo() {
419 bar<|>();
420 }
421}
422",
423 r"
424mod baz {
425 fn foo() {
426 bar();
427 }
428
429 fn bar() {
430 ${0:todo!()}
431 }
432}
433",
434 )
435 }
436
437 #[test]
438 fn add_function_with_function_call_arg() {
439 check_assist(
440 generate_function,
441 r"
442struct Baz;
443fn baz() -> Baz { todo!() }
444fn foo() {
445 bar<|>(baz());
446}
447",
448 r"
449struct Baz;
450fn baz() -> Baz { todo!() }
451fn foo() {
452 bar(baz());
453}
454
455fn bar(baz: Baz) {
456 ${0:todo!()}
457}
458",
459 );
460 }
461
462 #[test]
463 fn add_function_with_method_call_arg() {
464 check_assist(
465 generate_function,
466 r"
467struct Baz;
468impl Baz {
469 fn foo(&self) -> Baz {
470 ba<|>r(self.baz())
471 }
472 fn baz(&self) -> Baz {
473 Baz
474 }
475}
476",
477 r"
478struct Baz;
479impl Baz {
480 fn foo(&self) -> Baz {
481 bar(self.baz())
482 }
483 fn baz(&self) -> Baz {
484 Baz
485 }
486}
487
488fn bar(baz: Baz) {
489 ${0:todo!()}
490}
491",
492 )
493 }
494
495 #[test]
496 fn add_function_with_string_literal_arg() {
497 check_assist(
498 generate_function,
499 r#"
500fn foo() {
501 <|>bar("bar")
502}
503"#,
504 r#"
505fn foo() {
506 bar("bar")
507}
508
509fn bar(arg: &str) {
510 ${0:todo!()}
511}
512"#,
513 )
514 }
515
516 #[test]
517 fn add_function_with_char_literal_arg() {
518 check_assist(
519 generate_function,
520 r#"
521fn foo() {
522 <|>bar('x')
523}
524"#,
525 r#"
526fn foo() {
527 bar('x')
528}
529
530fn bar(arg: char) {
531 ${0:todo!()}
532}
533"#,
534 )
535 }
536
537 #[test]
538 fn add_function_with_int_literal_arg() {
539 check_assist(
540 generate_function,
541 r"
542fn foo() {
543 <|>bar(42)
544}
545",
546 r"
547fn foo() {
548 bar(42)
549}
550
551fn bar(arg: i32) {
552 ${0:todo!()}
553}
554",
555 )
556 }
557
558 #[test]
559 fn add_function_with_cast_int_literal_arg() {
560 check_assist(
561 generate_function,
562 r"
563fn foo() {
564 <|>bar(42 as u8)
565}
566",
567 r"
568fn foo() {
569 bar(42 as u8)
570}
571
572fn bar(arg: u8) {
573 ${0:todo!()}
574}
575",
576 )
577 }
578
579 #[test]
580 fn name_of_cast_variable_is_used() {
581 // Ensures that the name of the cast type isn't used
582 // in the generated function signature.
583 check_assist(
584 generate_function,
585 r"
586fn foo() {
587 let x = 42;
588 bar<|>(x as u8)
589}
590",
591 r"
592fn foo() {
593 let x = 42;
594 bar(x as u8)
595}
596
597fn bar(x: u8) {
598 ${0:todo!()}
599}
600",
601 )
602 }
603
604 #[test]
605 fn add_function_with_variable_arg() {
606 check_assist(
607 generate_function,
608 r"
609fn foo() {
610 let worble = ();
611 <|>bar(worble)
612}
613",
614 r"
615fn foo() {
616 let worble = ();
617 bar(worble)
618}
619
620fn bar(worble: ()) {
621 ${0:todo!()}
622}
623",
624 )
625 }
626
627 #[test]
628 fn add_function_with_impl_trait_arg() {
629 check_assist(
630 generate_function,
631 r"
632trait Foo {}
633fn foo() -> impl Foo {
634 todo!()
635}
636fn baz() {
637 <|>bar(foo())
638}
639",
640 r"
641trait Foo {}
642fn foo() -> impl Foo {
643 todo!()
644}
645fn baz() {
646 bar(foo())
647}
648
649fn bar(foo: impl Foo) {
650 ${0:todo!()}
651}
652",
653 )
654 }
655
656 #[test]
657 fn borrowed_arg() {
658 check_assist(
659 generate_function,
660 r"
661struct Baz;
662fn baz() -> Baz { todo!() }
663
664fn foo() {
665 bar<|>(&baz())
666}
667",
668 r"
669struct Baz;
670fn baz() -> Baz { todo!() }
671
672fn foo() {
673 bar(&baz())
674}
675
676fn bar(baz: &Baz) {
677 ${0:todo!()}
678}
679",
680 )
681 }
682
683 #[test]
684 fn add_function_with_qualified_path_arg() {
685 check_assist(
686 generate_function,
687 r"
688mod Baz {
689 pub struct Bof;
690 pub fn baz() -> Bof { Bof }
691}
692fn foo() {
693 <|>bar(Baz::baz())
694}
695",
696 r"
697mod Baz {
698 pub struct Bof;
699 pub fn baz() -> Bof { Bof }
700}
701fn foo() {
702 bar(Baz::baz())
703}
704
705fn bar(baz: Baz::Bof) {
706 ${0:todo!()}
707}
708",
709 )
710 }
711
712 #[test]
713 #[ignore]
714 // FIXME fix printing the generics of a `Ty` to make this test pass
715 fn add_function_with_generic_arg() {
716 check_assist(
717 generate_function,
718 r"
719fn foo<T>(t: T) {
720 <|>bar(t)
721}
722",
723 r"
724fn foo<T>(t: T) {
725 bar(t)
726}
727
728fn bar<T>(t: T) {
729 ${0:todo!()}
730}
731",
732 )
733 }
734
735 #[test]
736 #[ignore]
737 // FIXME Fix function type printing to make this test pass
738 fn add_function_with_fn_arg() {
739 check_assist(
740 generate_function,
741 r"
742struct Baz;
743impl Baz {
744 fn new() -> Self { Baz }
745}
746fn foo() {
747 <|>bar(Baz::new);
748}
749",
750 r"
751struct Baz;
752impl Baz {
753 fn new() -> Self { Baz }
754}
755fn foo() {
756 bar(Baz::new);
757}
758
759fn bar(arg: fn() -> Baz) {
760 ${0:todo!()}
761}
762",
763 )
764 }
765
766 #[test]
767 #[ignore]
768 // FIXME Fix closure type printing to make this test pass
769 fn add_function_with_closure_arg() {
770 check_assist(
771 generate_function,
772 r"
773fn foo() {
774 let closure = |x: i64| x - 1;
775 <|>bar(closure)
776}
777",
778 r"
779fn foo() {
780 let closure = |x: i64| x - 1;
781 bar(closure)
782}
783
784fn bar(closure: impl Fn(i64) -> i64) {
785 ${0:todo!()}
786}
787",
788 )
789 }
790
791 #[test]
792 fn unresolveable_types_default_to_unit() {
793 check_assist(
794 generate_function,
795 r"
796fn foo() {
797 <|>bar(baz)
798}
799",
800 r"
801fn foo() {
802 bar(baz)
803}
804
805fn bar(baz: ()) {
806 ${0:todo!()}
807}
808",
809 )
810 }
811
812 #[test]
813 fn arg_names_dont_overlap() {
814 check_assist(
815 generate_function,
816 r"
817struct Baz;
818fn baz() -> Baz { Baz }
819fn foo() {
820 <|>bar(baz(), baz())
821}
822",
823 r"
824struct Baz;
825fn baz() -> Baz { Baz }
826fn foo() {
827 bar(baz(), baz())
828}
829
830fn bar(baz_1: Baz, baz_2: Baz) {
831 ${0:todo!()}
832}
833",
834 )
835 }
836
837 #[test]
838 fn arg_name_counters_start_at_1_per_name() {
839 check_assist(
840 generate_function,
841 r#"
842struct Baz;
843fn baz() -> Baz { Baz }
844fn foo() {
845 <|>bar(baz(), baz(), "foo", "bar")
846}
847"#,
848 r#"
849struct Baz;
850fn baz() -> Baz { Baz }
851fn foo() {
852 bar(baz(), baz(), "foo", "bar")
853}
854
855fn bar(baz_1: Baz, baz_2: Baz, arg_1: &str, arg_2: &str) {
856 ${0:todo!()}
857}
858"#,
859 )
860 }
861
862 #[test]
863 fn add_function_in_module() {
864 check_assist(
865 generate_function,
866 r"
867mod bar {}
868
869fn foo() {
870 bar::my_fn<|>()
871}
872",
873 r"
874mod bar {
875 pub(crate) fn my_fn() {
876 ${0:todo!()}
877 }
878}
879
880fn foo() {
881 bar::my_fn()
882}
883",
884 )
885 }
886
887 #[test]
888 #[ignore]
889 // Ignored until local imports are supported.
890 // See https://github.com/rust-analyzer/rust-analyzer/issues/1165
891 fn qualified_path_uses_correct_scope() {
892 check_assist(
893 generate_function,
894 "
895mod foo {
896 pub struct Foo;
897}
898fn bar() {
899 use foo::Foo;
900 let foo = Foo;
901 baz<|>(foo)
902}
903",
904 "
905mod foo {
906 pub struct Foo;
907}
908fn bar() {
909 use foo::Foo;
910 let foo = Foo;
911 baz(foo)
912}
913
914fn baz(foo: foo::Foo) {
915 ${0:todo!()}
916}
917",
918 )
919 }
920
921 #[test]
922 fn add_function_in_module_containing_other_items() {
923 check_assist(
924 generate_function,
925 r"
926mod bar {
927 fn something_else() {}
928}
929
930fn foo() {
931 bar::my_fn<|>()
932}
933",
934 r"
935mod bar {
936 fn something_else() {}
937
938 pub(crate) fn my_fn() {
939 ${0:todo!()}
940 }
941}
942
943fn foo() {
944 bar::my_fn()
945}
946",
947 )
948 }
949
950 #[test]
951 fn add_function_in_nested_module() {
952 check_assist(
953 generate_function,
954 r"
955mod bar {
956 mod baz {}
957}
958
959fn foo() {
960 bar::baz::my_fn<|>()
961}
962",
963 r"
964mod bar {
965 mod baz {
966 pub(crate) fn my_fn() {
967 ${0:todo!()}
968 }
969 }
970}
971
972fn foo() {
973 bar::baz::my_fn()
974}
975",
976 )
977 }
978
979 #[test]
980 fn add_function_in_another_file() {
981 check_assist(
982 generate_function,
983 r"
984//- /main.rs
985mod foo;
986
987fn main() {
988 foo::bar<|>()
989}
990//- /foo.rs
991",
992 r"
993
994
995pub(crate) fn bar() {
996 ${0:todo!()}
997}",
998 )
999 }
1000
1001 #[test]
1002 fn add_function_not_applicable_if_function_already_exists() {
1003 check_assist_not_applicable(
1004 generate_function,
1005 r"
1006fn foo() {
1007 bar<|>();
1008}
1009
1010fn bar() {}
1011",
1012 )
1013 }
1014
1015 #[test]
1016 fn add_function_not_applicable_if_unresolved_variable_in_call_is_selected() {
1017 check_assist_not_applicable(
1018 // bar is resolved, but baz isn't.
1019 // The assist is only active if the cursor is on an unresolved path,
1020 // but the assist should only be offered if the path is a function call.
1021 generate_function,
1022 r"
1023fn foo() {
1024 bar(b<|>az);
1025}
1026
1027fn bar(baz: ()) {}
1028",
1029 )
1030 }
1031
1032 #[test]
1033 #[ignore]
1034 fn create_method_with_no_args() {
1035 check_assist(
1036 generate_function,
1037 r"
1038struct Foo;
1039impl Foo {
1040 fn foo(&self) {
1041 self.bar()<|>;
1042 }
1043}
1044 ",
1045 r"
1046struct Foo;
1047impl Foo {
1048 fn foo(&self) {
1049 self.bar();
1050 }
1051 fn bar(&self) {
1052 todo!();
1053 }
1054}
1055 ",
1056 )
1057 }
1058}
diff --git a/crates/ra_assists/src/handlers/generate_impl.rs b/crates/ra_assists/src/handlers/generate_impl.rs
deleted file mode 100644
index 9989109b5..000000000
--- a/crates/ra_assists/src/handlers/generate_impl.rs
+++ /dev/null
@@ -1,110 +0,0 @@
1use itertools::Itertools;
2use stdx::format_to;
3use syntax::ast::{self, AstNode, GenericParamsOwner, NameOwner};
4
5use crate::{AssistContext, AssistId, AssistKind, Assists};
6
7// Assist: generate_impl
8//
9// Adds a new inherent impl for a type.
10//
11// ```
12// struct Ctx<T: Clone> {
13// data: T,<|>
14// }
15// ```
16// ->
17// ```
18// struct Ctx<T: Clone> {
19// data: T,
20// }
21//
22// impl<T: Clone> Ctx<T> {
23// $0
24// }
25// ```
26pub(crate) fn generate_impl(acc: &mut Assists, ctx: &AssistContext) -> Option<()> {
27 let nominal = ctx.find_node_at_offset::<ast::AdtDef>()?;
28 let name = nominal.name()?;
29 let target = nominal.syntax().text_range();
30 acc.add(
31 AssistId("generate_impl", AssistKind::Generate),
32 format!("Generate impl for `{}`", name),
33 target,
34 |edit| {
35 let type_params = nominal.generic_param_list();
36 let start_offset = nominal.syntax().text_range().end();
37 let mut buf = String::new();
38 buf.push_str("\n\nimpl");
39 if let Some(type_params) = &type_params {
40 format_to!(buf, "{}", type_params.syntax());
41 }
42 buf.push_str(" ");
43 buf.push_str(name.text().as_str());
44 if let Some(type_params) = type_params {
45 let lifetime_params = type_params
46 .lifetime_params()
47 .filter_map(|it| it.lifetime_token())
48 .map(|it| it.text().clone());
49 let type_params = type_params
50 .type_params()
51 .filter_map(|it| it.name())
52 .map(|it| it.text().clone());
53
54 let generic_params = lifetime_params.chain(type_params).format(", ");
55 format_to!(buf, "<{}>", generic_params)
56 }
57 match ctx.config.snippet_cap {
58 Some(cap) => {
59 buf.push_str(" {\n $0\n}");
60 edit.insert_snippet(cap, start_offset, buf);
61 }
62 None => {
63 buf.push_str(" {\n}");
64 edit.insert(start_offset, buf);
65 }
66 }
67 },
68 )
69}
70
71#[cfg(test)]
72mod tests {
73 use crate::tests::{check_assist, check_assist_target};
74
75 use super::*;
76
77 #[test]
78 fn test_add_impl() {
79 check_assist(
80 generate_impl,
81 "struct Foo {<|>}\n",
82 "struct Foo {}\n\nimpl Foo {\n $0\n}\n",
83 );
84 check_assist(
85 generate_impl,
86 "struct Foo<T: Clone> {<|>}",
87 "struct Foo<T: Clone> {}\n\nimpl<T: Clone> Foo<T> {\n $0\n}",
88 );
89 check_assist(
90 generate_impl,
91 "struct Foo<'a, T: Foo<'a>> {<|>}",
92 "struct Foo<'a, T: Foo<'a>> {}\n\nimpl<'a, T: Foo<'a>> Foo<'a, T> {\n $0\n}",
93 );
94 }
95
96 #[test]
97 fn add_impl_target() {
98 check_assist_target(
99 generate_impl,
100 "
101struct SomeThingIrrelevant;
102/// Has a lifetime parameter
103struct Foo<'a, T: Foo<'a>> {<|>}
104struct EvenMoreIrrelevant;
105",
106 "/// Has a lifetime parameter
107struct Foo<'a, T: Foo<'a>> {}",
108 );
109 }
110}
diff --git a/crates/ra_assists/src/handlers/generate_new.rs b/crates/ra_assists/src/handlers/generate_new.rs
deleted file mode 100644
index 7db10f276..000000000
--- a/crates/ra_assists/src/handlers/generate_new.rs
+++ /dev/null
@@ -1,421 +0,0 @@
1use hir::Adt;
2use itertools::Itertools;
3use stdx::format_to;
4use syntax::{
5 ast::{self, AstNode, GenericParamsOwner, NameOwner, StructKind, VisibilityOwner},
6 T,
7};
8
9use crate::{AssistContext, AssistId, AssistKind, Assists};
10
11// Assist: generate_new
12//
13// Adds a new inherent impl for a type.
14//
15// ```
16// struct Ctx<T: Clone> {
17// data: T,<|>
18// }
19// ```
20// ->
21// ```
22// struct Ctx<T: Clone> {
23// data: T,
24// }
25//
26// impl<T: Clone> Ctx<T> {
27// fn $0new(data: T) -> Self { Self { data } }
28// }
29//
30// ```
31pub(crate) fn generate_new(acc: &mut Assists, ctx: &AssistContext) -> Option<()> {
32 let strukt = ctx.find_node_at_offset::<ast::Struct>()?;
33
34 // We want to only apply this to non-union structs with named fields
35 let field_list = match strukt.kind() {
36 StructKind::Record(named) => named,
37 _ => return None,
38 };
39
40 // Return early if we've found an existing new fn
41 let impl_def = find_struct_impl(&ctx, &strukt)?;
42
43 let target = strukt.syntax().text_range();
44 acc.add(AssistId("generate_new", AssistKind::Generate), "Generate `new`", target, |builder| {
45 let mut buf = String::with_capacity(512);
46
47 if impl_def.is_some() {
48 buf.push('\n');
49 }
50
51 let vis = strukt.visibility().map_or(String::new(), |v| format!("{} ", v));
52
53 let params = field_list
54 .fields()
55 .filter_map(|f| Some(format!("{}: {}", f.name()?.syntax(), f.ty()?.syntax())))
56 .format(", ");
57 let fields = field_list.fields().filter_map(|f| f.name()).format(", ");
58
59 format_to!(buf, " {}fn new({}) -> Self {{ Self {{ {} }} }}", vis, params, fields);
60
61 let start_offset = impl_def
62 .and_then(|impl_def| {
63 buf.push('\n');
64 let start = impl_def
65 .syntax()
66 .descendants_with_tokens()
67 .find(|t| t.kind() == T!['{'])?
68 .text_range()
69 .end();
70
71 Some(start)
72 })
73 .unwrap_or_else(|| {
74 buf = generate_impl_text(&strukt, &buf);
75 strukt.syntax().text_range().end()
76 });
77
78 match ctx.config.snippet_cap {
79 None => builder.insert(start_offset, buf),
80 Some(cap) => {
81 buf = buf.replace("fn new", "fn $0new");
82 builder.insert_snippet(cap, start_offset, buf);
83 }
84 }
85 })
86}
87
88// Generates the surrounding `impl Type { <code> }` including type and lifetime
89// parameters
90fn generate_impl_text(strukt: &ast::Struct, code: &str) -> String {
91 let type_params = strukt.generic_param_list();
92 let mut buf = String::with_capacity(code.len());
93 buf.push_str("\n\nimpl");
94 if let Some(type_params) = &type_params {
95 format_to!(buf, "{}", type_params.syntax());
96 }
97 buf.push_str(" ");
98 buf.push_str(strukt.name().unwrap().text().as_str());
99 if let Some(type_params) = type_params {
100 let lifetime_params = type_params
101 .lifetime_params()
102 .filter_map(|it| it.lifetime_token())
103 .map(|it| it.text().clone());
104 let type_params =
105 type_params.type_params().filter_map(|it| it.name()).map(|it| it.text().clone());
106 format_to!(buf, "<{}>", lifetime_params.chain(type_params).format(", "))
107 }
108
109 format_to!(buf, " {{\n{}\n}}\n", code);
110
111 buf
112}
113
114// Uses a syntax-driven approach to find any impl blocks for the struct that
115// exist within the module/file
116//
117// Returns `None` if we've found an existing `new` fn
118//
119// FIXME: change the new fn checking to a more semantic approach when that's more
120// viable (e.g. we process proc macros, etc)
121fn find_struct_impl(ctx: &AssistContext, strukt: &ast::Struct) -> Option<Option<ast::Impl>> {
122 let db = ctx.db();
123 let module = strukt.syntax().ancestors().find(|node| {
124 ast::Module::can_cast(node.kind()) || ast::SourceFile::can_cast(node.kind())
125 })?;
126
127 let struct_def = ctx.sema.to_def(strukt)?;
128
129 let block = module.descendants().filter_map(ast::Impl::cast).find_map(|impl_blk| {
130 let blk = ctx.sema.to_def(&impl_blk)?;
131
132 // FIXME: handle e.g. `struct S<T>; impl<U> S<U> {}`
133 // (we currently use the wrong type parameter)
134 // also we wouldn't want to use e.g. `impl S<u32>`
135 let same_ty = match blk.target_ty(db).as_adt() {
136 Some(def) => def == Adt::Struct(struct_def),
137 None => false,
138 };
139 let not_trait_impl = blk.target_trait(db).is_none();
140
141 if !(same_ty && not_trait_impl) {
142 None
143 } else {
144 Some(impl_blk)
145 }
146 });
147
148 if let Some(ref impl_blk) = block {
149 if has_new_fn(impl_blk) {
150 return None;
151 }
152 }
153
154 Some(block)
155}
156
157fn has_new_fn(imp: &ast::Impl) -> bool {
158 if let Some(il) = imp.assoc_item_list() {
159 for item in il.assoc_items() {
160 if let ast::AssocItem::Fn(f) = item {
161 if let Some(name) = f.name() {
162 if name.text().eq_ignore_ascii_case("new") {
163 return true;
164 }
165 }
166 }
167 }
168 }
169
170 false
171}
172
173#[cfg(test)]
174mod tests {
175 use crate::tests::{check_assist, check_assist_not_applicable, check_assist_target};
176
177 use super::*;
178
179 #[test]
180 #[rustfmt::skip]
181 fn test_generate_new() {
182 // Check output of generation
183 check_assist(
184 generate_new,
185"struct Foo {<|>}",
186"struct Foo {}
187
188impl Foo {
189 fn $0new() -> Self { Self { } }
190}
191",
192 );
193 check_assist(
194 generate_new,
195"struct Foo<T: Clone> {<|>}",
196"struct Foo<T: Clone> {}
197
198impl<T: Clone> Foo<T> {
199 fn $0new() -> Self { Self { } }
200}
201",
202 );
203 check_assist(
204 generate_new,
205"struct Foo<'a, T: Foo<'a>> {<|>}",
206"struct Foo<'a, T: Foo<'a>> {}
207
208impl<'a, T: Foo<'a>> Foo<'a, T> {
209 fn $0new() -> Self { Self { } }
210}
211",
212 );
213 check_assist(
214 generate_new,
215"struct Foo { baz: String <|>}",
216"struct Foo { baz: String }
217
218impl Foo {
219 fn $0new(baz: String) -> Self { Self { baz } }
220}
221",
222 );
223 check_assist(
224 generate_new,
225"struct Foo { baz: String, qux: Vec<i32> <|>}",
226"struct Foo { baz: String, qux: Vec<i32> }
227
228impl Foo {
229 fn $0new(baz: String, qux: Vec<i32>) -> Self { Self { baz, qux } }
230}
231",
232 );
233
234 // Check that visibility modifiers don't get brought in for fields
235 check_assist(
236 generate_new,
237"struct Foo { pub baz: String, pub qux: Vec<i32> <|>}",
238"struct Foo { pub baz: String, pub qux: Vec<i32> }
239
240impl Foo {
241 fn $0new(baz: String, qux: Vec<i32>) -> Self { Self { baz, qux } }
242}
243",
244 );
245
246 // Check that it reuses existing impls
247 check_assist(
248 generate_new,
249"struct Foo {<|>}
250
251impl Foo {}
252",
253"struct Foo {}
254
255impl Foo {
256 fn $0new() -> Self { Self { } }
257}
258",
259 );
260 check_assist(
261 generate_new,
262"struct Foo {<|>}
263
264impl Foo {
265 fn qux(&self) {}
266}
267",
268"struct Foo {}
269
270impl Foo {
271 fn $0new() -> Self { Self { } }
272
273 fn qux(&self) {}
274}
275",
276 );
277
278 check_assist(
279 generate_new,
280"struct Foo {<|>}
281
282impl Foo {
283 fn qux(&self) {}
284 fn baz() -> i32 {
285 5
286 }
287}
288",
289"struct Foo {}
290
291impl Foo {
292 fn $0new() -> Self { Self { } }
293
294 fn qux(&self) {}
295 fn baz() -> i32 {
296 5
297 }
298}
299",
300 );
301
302 // Check visibility of new fn based on struct
303 check_assist(
304 generate_new,
305"pub struct Foo {<|>}",
306"pub struct Foo {}
307
308impl Foo {
309 pub fn $0new() -> Self { Self { } }
310}
311",
312 );
313 check_assist(
314 generate_new,
315"pub(crate) struct Foo {<|>}",
316"pub(crate) struct Foo {}
317
318impl Foo {
319 pub(crate) fn $0new() -> Self { Self { } }
320}
321",
322 );
323 }
324
325 #[test]
326 fn generate_new_not_applicable_if_fn_exists() {
327 check_assist_not_applicable(
328 generate_new,
329 "
330struct Foo {<|>}
331
332impl Foo {
333 fn new() -> Self {
334 Self
335 }
336}",
337 );
338
339 check_assist_not_applicable(
340 generate_new,
341 "
342struct Foo {<|>}
343
344impl Foo {
345 fn New() -> Self {
346 Self
347 }
348}",
349 );
350 }
351
352 #[test]
353 fn generate_new_target() {
354 check_assist_target(
355 generate_new,
356 "
357struct SomeThingIrrelevant;
358/// Has a lifetime parameter
359struct Foo<'a, T: Foo<'a>> {<|>}
360struct EvenMoreIrrelevant;
361",
362 "/// Has a lifetime parameter
363struct Foo<'a, T: Foo<'a>> {}",
364 );
365 }
366
367 #[test]
368 fn test_unrelated_new() {
369 check_assist(
370 generate_new,
371 r##"
372pub struct AstId<N: AstNode> {
373 file_id: HirFileId,
374 file_ast_id: FileAstId<N>,
375}
376
377impl<N: AstNode> AstId<N> {
378 pub fn new(file_id: HirFileId, file_ast_id: FileAstId<N>) -> AstId<N> {
379 AstId { file_id, file_ast_id }
380 }
381}
382
383pub struct Source<T> {
384 pub file_id: HirFileId,<|>
385 pub ast: T,
386}
387
388impl<T> Source<T> {
389 pub fn map<F: FnOnce(T) -> U, U>(self, f: F) -> Source<U> {
390 Source { file_id: self.file_id, ast: f(self.ast) }
391 }
392}
393"##,
394 r##"
395pub struct AstId<N: AstNode> {
396 file_id: HirFileId,
397 file_ast_id: FileAstId<N>,
398}
399
400impl<N: AstNode> AstId<N> {
401 pub fn new(file_id: HirFileId, file_ast_id: FileAstId<N>) -> AstId<N> {
402 AstId { file_id, file_ast_id }
403 }
404}
405
406pub struct Source<T> {
407 pub file_id: HirFileId,
408 pub ast: T,
409}
410
411impl<T> Source<T> {
412 pub fn $0new(file_id: HirFileId, ast: T) -> Self { Self { file_id, ast } }
413
414 pub fn map<F: FnOnce(T) -> U, U>(self, f: F) -> Source<U> {
415 Source { file_id: self.file_id, ast: f(self.ast) }
416 }
417}
418"##,
419 );
420 }
421}
diff --git a/crates/ra_assists/src/handlers/inline_local_variable.rs b/crates/ra_assists/src/handlers/inline_local_variable.rs
deleted file mode 100644
index 2b52b333b..000000000
--- a/crates/ra_assists/src/handlers/inline_local_variable.rs
+++ /dev/null
@@ -1,695 +0,0 @@
1use ide_db::defs::Definition;
2use syntax::{
3 ast::{self, AstNode, AstToken},
4 TextRange,
5};
6use test_utils::mark;
7
8use crate::{
9 assist_context::{AssistContext, Assists},
10 AssistId, AssistKind,
11};
12
13// Assist: inline_local_variable
14//
15// Inlines local variable.
16//
17// ```
18// fn main() {
19// let x<|> = 1 + 2;
20// x * 4;
21// }
22// ```
23// ->
24// ```
25// fn main() {
26// (1 + 2) * 4;
27// }
28// ```
29pub(crate) fn inline_local_variable(acc: &mut Assists, ctx: &AssistContext) -> Option<()> {
30 let let_stmt = ctx.find_node_at_offset::<ast::LetStmt>()?;
31 let bind_pat = match let_stmt.pat()? {
32 ast::Pat::IdentPat(pat) => pat,
33 _ => return None,
34 };
35 if bind_pat.mut_token().is_some() {
36 mark::hit!(test_not_inline_mut_variable);
37 return None;
38 }
39 if !bind_pat.syntax().text_range().contains_inclusive(ctx.offset()) {
40 mark::hit!(not_applicable_outside_of_bind_pat);
41 return None;
42 }
43 let initializer_expr = let_stmt.initializer()?;
44
45 let def = ctx.sema.to_def(&bind_pat)?;
46 let def = Definition::Local(def);
47 let refs = def.find_usages(&ctx.sema, None);
48 if refs.is_empty() {
49 mark::hit!(test_not_applicable_if_variable_unused);
50 return None;
51 };
52
53 let delete_range = if let Some(whitespace) = let_stmt
54 .syntax()
55 .next_sibling_or_token()
56 .and_then(|it| ast::Whitespace::cast(it.as_token()?.clone()))
57 {
58 TextRange::new(
59 let_stmt.syntax().text_range().start(),
60 whitespace.syntax().text_range().end(),
61 )
62 } else {
63 let_stmt.syntax().text_range()
64 };
65
66 let mut wrap_in_parens = vec![true; refs.len()];
67
68 for (i, desc) in refs.iter().enumerate() {
69 let usage_node = ctx
70 .covering_node_for_range(desc.file_range.range)
71 .ancestors()
72 .find_map(ast::PathExpr::cast)?;
73 let usage_parent_option = usage_node.syntax().parent().and_then(ast::Expr::cast);
74 let usage_parent = match usage_parent_option {
75 Some(u) => u,
76 None => {
77 wrap_in_parens[i] = false;
78 continue;
79 }
80 };
81
82 wrap_in_parens[i] = match (&initializer_expr, usage_parent) {
83 (ast::Expr::CallExpr(_), _)
84 | (ast::Expr::IndexExpr(_), _)
85 | (ast::Expr::MethodCallExpr(_), _)
86 | (ast::Expr::FieldExpr(_), _)
87 | (ast::Expr::TryExpr(_), _)
88 | (ast::Expr::RefExpr(_), _)
89 | (ast::Expr::Literal(_), _)
90 | (ast::Expr::TupleExpr(_), _)
91 | (ast::Expr::ArrayExpr(_), _)
92 | (ast::Expr::ParenExpr(_), _)
93 | (ast::Expr::PathExpr(_), _)
94 | (ast::Expr::BlockExpr(_), _)
95 | (ast::Expr::EffectExpr(_), _)
96 | (_, ast::Expr::CallExpr(_))
97 | (_, ast::Expr::TupleExpr(_))
98 | (_, ast::Expr::ArrayExpr(_))
99 | (_, ast::Expr::ParenExpr(_))
100 | (_, ast::Expr::ForExpr(_))
101 | (_, ast::Expr::WhileExpr(_))
102 | (_, ast::Expr::BreakExpr(_))
103 | (_, ast::Expr::ReturnExpr(_))
104 | (_, ast::Expr::MatchExpr(_)) => false,
105 _ => true,
106 };
107 }
108
109 let init_str = initializer_expr.syntax().text().to_string();
110 let init_in_paren = format!("({})", &init_str);
111
112 let target = bind_pat.syntax().text_range();
113 acc.add(
114 AssistId("inline_local_variable", AssistKind::RefactorInline),
115 "Inline variable",
116 target,
117 move |builder| {
118 builder.delete(delete_range);
119 for (desc, should_wrap) in refs.iter().zip(wrap_in_parens) {
120 let replacement =
121 if should_wrap { init_in_paren.clone() } else { init_str.clone() };
122 builder.replace(desc.file_range.range, replacement)
123 }
124 },
125 )
126}
127
128#[cfg(test)]
129mod tests {
130 use test_utils::mark;
131
132 use crate::tests::{check_assist, check_assist_not_applicable};
133
134 use super::*;
135
136 #[test]
137 fn test_inline_let_bind_literal_expr() {
138 check_assist(
139 inline_local_variable,
140 r"
141fn bar(a: usize) {}
142fn foo() {
143 let a<|> = 1;
144 a + 1;
145 if a > 10 {
146 }
147
148 while a > 10 {
149
150 }
151 let b = a * 10;
152 bar(a);
153}",
154 r"
155fn bar(a: usize) {}
156fn foo() {
157 1 + 1;
158 if 1 > 10 {
159 }
160
161 while 1 > 10 {
162
163 }
164 let b = 1 * 10;
165 bar(1);
166}",
167 );
168 }
169
170 #[test]
171 fn test_inline_let_bind_bin_expr() {
172 check_assist(
173 inline_local_variable,
174 r"
175fn bar(a: usize) {}
176fn foo() {
177 let a<|> = 1 + 1;
178 a + 1;
179 if a > 10 {
180 }
181
182 while a > 10 {
183
184 }
185 let b = a * 10;
186 bar(a);
187}",
188 r"
189fn bar(a: usize) {}
190fn foo() {
191 (1 + 1) + 1;
192 if (1 + 1) > 10 {
193 }
194
195 while (1 + 1) > 10 {
196
197 }
198 let b = (1 + 1) * 10;
199 bar(1 + 1);
200}",
201 );
202 }
203
204 #[test]
205 fn test_inline_let_bind_function_call_expr() {
206 check_assist(
207 inline_local_variable,
208 r"
209fn bar(a: usize) {}
210fn foo() {
211 let a<|> = bar(1);
212 a + 1;
213 if a > 10 {
214 }
215
216 while a > 10 {
217
218 }
219 let b = a * 10;
220 bar(a);
221}",
222 r"
223fn bar(a: usize) {}
224fn foo() {
225 bar(1) + 1;
226 if bar(1) > 10 {
227 }
228
229 while bar(1) > 10 {
230
231 }
232 let b = bar(1) * 10;
233 bar(bar(1));
234}",
235 );
236 }
237
238 #[test]
239 fn test_inline_let_bind_cast_expr() {
240 check_assist(
241 inline_local_variable,
242 r"
243fn bar(a: usize): usize { a }
244fn foo() {
245 let a<|> = bar(1) as u64;
246 a + 1;
247 if a > 10 {
248 }
249
250 while a > 10 {
251
252 }
253 let b = a * 10;
254 bar(a);
255}",
256 r"
257fn bar(a: usize): usize { a }
258fn foo() {
259 (bar(1) as u64) + 1;
260 if (bar(1) as u64) > 10 {
261 }
262
263 while (bar(1) as u64) > 10 {
264
265 }
266 let b = (bar(1) as u64) * 10;
267 bar(bar(1) as u64);
268}",
269 );
270 }
271
272 #[test]
273 fn test_inline_let_bind_block_expr() {
274 check_assist(
275 inline_local_variable,
276 r"
277fn foo() {
278 let a<|> = { 10 + 1 };
279 a + 1;
280 if a > 10 {
281 }
282
283 while a > 10 {
284
285 }
286 let b = a * 10;
287 bar(a);
288}",
289 r"
290fn foo() {
291 { 10 + 1 } + 1;
292 if { 10 + 1 } > 10 {
293 }
294
295 while { 10 + 1 } > 10 {
296
297 }
298 let b = { 10 + 1 } * 10;
299 bar({ 10 + 1 });
300}",
301 );
302 }
303
304 #[test]
305 fn test_inline_let_bind_paren_expr() {
306 check_assist(
307 inline_local_variable,
308 r"
309fn foo() {
310 let a<|> = ( 10 + 1 );
311 a + 1;
312 if a > 10 {
313 }
314
315 while a > 10 {
316
317 }
318 let b = a * 10;
319 bar(a);
320}",
321 r"
322fn foo() {
323 ( 10 + 1 ) + 1;
324 if ( 10 + 1 ) > 10 {
325 }
326
327 while ( 10 + 1 ) > 10 {
328
329 }
330 let b = ( 10 + 1 ) * 10;
331 bar(( 10 + 1 ));
332}",
333 );
334 }
335
336 #[test]
337 fn test_not_inline_mut_variable() {
338 mark::check!(test_not_inline_mut_variable);
339 check_assist_not_applicable(
340 inline_local_variable,
341 r"
342fn foo() {
343 let mut a<|> = 1 + 1;
344 a + 1;
345}",
346 );
347 }
348
349 #[test]
350 fn test_call_expr() {
351 check_assist(
352 inline_local_variable,
353 r"
354fn foo() {
355 let a<|> = bar(10 + 1);
356 let b = a * 10;
357 let c = a as usize;
358}",
359 r"
360fn foo() {
361 let b = bar(10 + 1) * 10;
362 let c = bar(10 + 1) as usize;
363}",
364 );
365 }
366
367 #[test]
368 fn test_index_expr() {
369 check_assist(
370 inline_local_variable,
371 r"
372fn foo() {
373 let x = vec![1, 2, 3];
374 let a<|> = x[0];
375 let b = a * 10;
376 let c = a as usize;
377}",
378 r"
379fn foo() {
380 let x = vec![1, 2, 3];
381 let b = x[0] * 10;
382 let c = x[0] as usize;
383}",
384 );
385 }
386
387 #[test]
388 fn test_method_call_expr() {
389 check_assist(
390 inline_local_variable,
391 r"
392fn foo() {
393 let bar = vec![1];
394 let a<|> = bar.len();
395 let b = a * 10;
396 let c = a as usize;
397}",
398 r"
399fn foo() {
400 let bar = vec![1];
401 let b = bar.len() * 10;
402 let c = bar.len() as usize;
403}",
404 );
405 }
406
407 #[test]
408 fn test_field_expr() {
409 check_assist(
410 inline_local_variable,
411 r"
412struct Bar {
413 foo: usize
414}
415
416fn foo() {
417 let bar = Bar { foo: 1 };
418 let a<|> = bar.foo;
419 let b = a * 10;
420 let c = a as usize;
421}",
422 r"
423struct Bar {
424 foo: usize
425}
426
427fn foo() {
428 let bar = Bar { foo: 1 };
429 let b = bar.foo * 10;
430 let c = bar.foo as usize;
431}",
432 );
433 }
434
435 #[test]
436 fn test_try_expr() {
437 check_assist(
438 inline_local_variable,
439 r"
440fn foo() -> Option<usize> {
441 let bar = Some(1);
442 let a<|> = bar?;
443 let b = a * 10;
444 let c = a as usize;
445 None
446}",
447 r"
448fn foo() -> Option<usize> {
449 let bar = Some(1);
450 let b = bar? * 10;
451 let c = bar? as usize;
452 None
453}",
454 );
455 }
456
457 #[test]
458 fn test_ref_expr() {
459 check_assist(
460 inline_local_variable,
461 r"
462fn foo() {
463 let bar = 10;
464 let a<|> = &bar;
465 let b = a * 10;
466}",
467 r"
468fn foo() {
469 let bar = 10;
470 let b = &bar * 10;
471}",
472 );
473 }
474
475 #[test]
476 fn test_tuple_expr() {
477 check_assist(
478 inline_local_variable,
479 r"
480fn foo() {
481 let a<|> = (10, 20);
482 let b = a[0];
483}",
484 r"
485fn foo() {
486 let b = (10, 20)[0];
487}",
488 );
489 }
490
491 #[test]
492 fn test_array_expr() {
493 check_assist(
494 inline_local_variable,
495 r"
496fn foo() {
497 let a<|> = [1, 2, 3];
498 let b = a.len();
499}",
500 r"
501fn foo() {
502 let b = [1, 2, 3].len();
503}",
504 );
505 }
506
507 #[test]
508 fn test_paren() {
509 check_assist(
510 inline_local_variable,
511 r"
512fn foo() {
513 let a<|> = (10 + 20);
514 let b = a * 10;
515 let c = a as usize;
516}",
517 r"
518fn foo() {
519 let b = (10 + 20) * 10;
520 let c = (10 + 20) as usize;
521}",
522 );
523 }
524
525 #[test]
526 fn test_path_expr() {
527 check_assist(
528 inline_local_variable,
529 r"
530fn foo() {
531 let d = 10;
532 let a<|> = d;
533 let b = a * 10;
534 let c = a as usize;
535}",
536 r"
537fn foo() {
538 let d = 10;
539 let b = d * 10;
540 let c = d as usize;
541}",
542 );
543 }
544
545 #[test]
546 fn test_block_expr() {
547 check_assist(
548 inline_local_variable,
549 r"
550fn foo() {
551 let a<|> = { 10 };
552 let b = a * 10;
553 let c = a as usize;
554}",
555 r"
556fn foo() {
557 let b = { 10 } * 10;
558 let c = { 10 } as usize;
559}",
560 );
561 }
562
563 #[test]
564 fn test_used_in_different_expr1() {
565 check_assist(
566 inline_local_variable,
567 r"
568fn foo() {
569 let a<|> = 10 + 20;
570 let b = a * 10;
571 let c = (a, 20);
572 let d = [a, 10];
573 let e = (a);
574}",
575 r"
576fn foo() {
577 let b = (10 + 20) * 10;
578 let c = (10 + 20, 20);
579 let d = [10 + 20, 10];
580 let e = (10 + 20);
581}",
582 );
583 }
584
585 #[test]
586 fn test_used_in_for_expr() {
587 check_assist(
588 inline_local_variable,
589 r"
590fn foo() {
591 let a<|> = vec![10, 20];
592 for i in a {}
593}",
594 r"
595fn foo() {
596 for i in vec![10, 20] {}
597}",
598 );
599 }
600
601 #[test]
602 fn test_used_in_while_expr() {
603 check_assist(
604 inline_local_variable,
605 r"
606fn foo() {
607 let a<|> = 1 > 0;
608 while a {}
609}",
610 r"
611fn foo() {
612 while 1 > 0 {}
613}",
614 );
615 }
616
617 #[test]
618 fn test_used_in_break_expr() {
619 check_assist(
620 inline_local_variable,
621 r"
622fn foo() {
623 let a<|> = 1 + 1;
624 loop {
625 break a;
626 }
627}",
628 r"
629fn foo() {
630 loop {
631 break 1 + 1;
632 }
633}",
634 );
635 }
636
637 #[test]
638 fn test_used_in_return_expr() {
639 check_assist(
640 inline_local_variable,
641 r"
642fn foo() {
643 let a<|> = 1 > 0;
644 return a;
645}",
646 r"
647fn foo() {
648 return 1 > 0;
649}",
650 );
651 }
652
653 #[test]
654 fn test_used_in_match_expr() {
655 check_assist(
656 inline_local_variable,
657 r"
658fn foo() {
659 let a<|> = 1 > 0;
660 match a {}
661}",
662 r"
663fn foo() {
664 match 1 > 0 {}
665}",
666 );
667 }
668
669 #[test]
670 fn test_not_applicable_if_variable_unused() {
671 mark::check!(test_not_applicable_if_variable_unused);
672 check_assist_not_applicable(
673 inline_local_variable,
674 r"
675fn foo() {
676 let <|>a = 0;
677}
678 ",
679 )
680 }
681
682 #[test]
683 fn not_applicable_outside_of_bind_pat() {
684 mark::check!(not_applicable_outside_of_bind_pat);
685 check_assist_not_applicable(
686 inline_local_variable,
687 r"
688fn main() {
689 let x = <|>1 + 2;
690 x * 4;
691}
692",
693 )
694 }
695}
diff --git a/crates/ra_assists/src/handlers/introduce_named_lifetime.rs b/crates/ra_assists/src/handlers/introduce_named_lifetime.rs
deleted file mode 100644
index 5f623e5f7..000000000
--- a/crates/ra_assists/src/handlers/introduce_named_lifetime.rs
+++ /dev/null
@@ -1,318 +0,0 @@
1use rustc_hash::FxHashSet;
2use syntax::{
3 ast::{self, GenericParamsOwner, NameOwner},
4 AstNode, SyntaxKind, TextRange, TextSize,
5};
6
7use crate::{assist_context::AssistBuilder, AssistContext, AssistId, AssistKind, Assists};
8
9static ASSIST_NAME: &str = "introduce_named_lifetime";
10static ASSIST_LABEL: &str = "Introduce named lifetime";
11
12// Assist: introduce_named_lifetime
13//
14// Change an anonymous lifetime to a named lifetime.
15//
16// ```
17// impl Cursor<'_<|>> {
18// fn node(self) -> &SyntaxNode {
19// match self {
20// Cursor::Replace(node) | Cursor::Before(node) => node,
21// }
22// }
23// }
24// ```
25// ->
26// ```
27// impl<'a> Cursor<'a> {
28// fn node(self) -> &SyntaxNode {
29// match self {
30// Cursor::Replace(node) | Cursor::Before(node) => node,
31// }
32// }
33// }
34// ```
35// FIXME: How can we handle renaming any one of multiple anonymous lifetimes?
36// FIXME: should also add support for the case fun(f: &Foo) -> &<|>Foo
37pub(crate) fn introduce_named_lifetime(acc: &mut Assists, ctx: &AssistContext) -> Option<()> {
38 let lifetime_token = ctx
39 .find_token_at_offset(SyntaxKind::LIFETIME)
40 .filter(|lifetime| lifetime.text() == "'_")?;
41 if let Some(fn_def) = lifetime_token.ancestors().find_map(ast::Fn::cast) {
42 generate_fn_def_assist(acc, &fn_def, lifetime_token.text_range())
43 } else if let Some(impl_def) = lifetime_token.ancestors().find_map(ast::Impl::cast) {
44 generate_impl_def_assist(acc, &impl_def, lifetime_token.text_range())
45 } else {
46 None
47 }
48}
49
50/// Generate the assist for the fn def case
51fn generate_fn_def_assist(
52 acc: &mut Assists,
53 fn_def: &ast::Fn,
54 lifetime_loc: TextRange,
55) -> Option<()> {
56 let param_list: ast::ParamList = fn_def.param_list()?;
57 let new_lifetime_param = generate_unique_lifetime_param_name(&fn_def.generic_param_list())?;
58 let end_of_fn_ident = fn_def.name()?.ident_token()?.text_range().end();
59 let self_param =
60 // use the self if it's a reference and has no explicit lifetime
61 param_list.self_param().filter(|p| p.lifetime_token().is_none() && p.amp_token().is_some());
62 // compute the location which implicitly has the same lifetime as the anonymous lifetime
63 let loc_needing_lifetime = if let Some(self_param) = self_param {
64 // if we have a self reference, use that
65 Some(self_param.self_token()?.text_range().start())
66 } else {
67 // otherwise, if there's a single reference parameter without a named liftime, use that
68 let fn_params_without_lifetime: Vec<_> = param_list
69 .params()
70 .filter_map(|param| match param.ty() {
71 Some(ast::Type::RefType(ascribed_type))
72 if ascribed_type.lifetime_token() == None =>
73 {
74 Some(ascribed_type.amp_token()?.text_range().end())
75 }
76 _ => None,
77 })
78 .collect();
79 match fn_params_without_lifetime.len() {
80 1 => Some(fn_params_without_lifetime.into_iter().nth(0)?),
81 0 => None,
82 // multiple unnnamed is invalid. assist is not applicable
83 _ => return None,
84 }
85 };
86 acc.add(AssistId(ASSIST_NAME, AssistKind::Refactor), ASSIST_LABEL, lifetime_loc, |builder| {
87 add_lifetime_param(fn_def, builder, end_of_fn_ident, new_lifetime_param);
88 builder.replace(lifetime_loc, format!("'{}", new_lifetime_param));
89 loc_needing_lifetime.map(|loc| builder.insert(loc, format!("'{} ", new_lifetime_param)));
90 })
91}
92
93/// Generate the assist for the impl def case
94fn generate_impl_def_assist(
95 acc: &mut Assists,
96 impl_def: &ast::Impl,
97 lifetime_loc: TextRange,
98) -> Option<()> {
99 let new_lifetime_param = generate_unique_lifetime_param_name(&impl_def.generic_param_list())?;
100 let end_of_impl_kw = impl_def.impl_token()?.text_range().end();
101 acc.add(AssistId(ASSIST_NAME, AssistKind::Refactor), ASSIST_LABEL, lifetime_loc, |builder| {
102 add_lifetime_param(impl_def, builder, end_of_impl_kw, new_lifetime_param);
103 builder.replace(lifetime_loc, format!("'{}", new_lifetime_param));
104 })
105}
106
107/// Given a type parameter list, generate a unique lifetime parameter name
108/// which is not in the list
109fn generate_unique_lifetime_param_name(
110 existing_type_param_list: &Option<ast::GenericParamList>,
111) -> Option<char> {
112 match existing_type_param_list {
113 Some(type_params) => {
114 let used_lifetime_params: FxHashSet<_> = type_params
115 .lifetime_params()
116 .map(|p| p.syntax().text().to_string()[1..].to_owned())
117 .collect();
118 (b'a'..=b'z').map(char::from).find(|c| !used_lifetime_params.contains(&c.to_string()))
119 }
120 None => Some('a'),
121 }
122}
123
124/// Add the lifetime param to `builder`. If there are type parameters in `type_params_owner`, add it to the end. Otherwise
125/// add new type params brackets with the lifetime parameter at `new_type_params_loc`.
126fn add_lifetime_param<TypeParamsOwner: ast::GenericParamsOwner>(
127 type_params_owner: &TypeParamsOwner,
128 builder: &mut AssistBuilder,
129 new_type_params_loc: TextSize,
130 new_lifetime_param: char,
131) {
132 match type_params_owner.generic_param_list() {
133 // add the new lifetime parameter to an existing type param list
134 Some(type_params) => {
135 builder.insert(
136 (u32::from(type_params.syntax().text_range().end()) - 1).into(),
137 format!(", '{}", new_lifetime_param),
138 );
139 }
140 // create a new type param list containing only the new lifetime parameter
141 None => {
142 builder.insert(new_type_params_loc, format!("<'{}>", new_lifetime_param));
143 }
144 }
145}
146
147#[cfg(test)]
148mod tests {
149 use super::*;
150 use crate::tests::{check_assist, check_assist_not_applicable};
151
152 #[test]
153 fn test_example_case() {
154 check_assist(
155 introduce_named_lifetime,
156 r#"impl Cursor<'_<|>> {
157 fn node(self) -> &SyntaxNode {
158 match self {
159 Cursor::Replace(node) | Cursor::Before(node) => node,
160 }
161 }
162 }"#,
163 r#"impl<'a> Cursor<'a> {
164 fn node(self) -> &SyntaxNode {
165 match self {
166 Cursor::Replace(node) | Cursor::Before(node) => node,
167 }
168 }
169 }"#,
170 );
171 }
172
173 #[test]
174 fn test_example_case_simplified() {
175 check_assist(
176 introduce_named_lifetime,
177 r#"impl Cursor<'_<|>> {"#,
178 r#"impl<'a> Cursor<'a> {"#,
179 );
180 }
181
182 #[test]
183 fn test_example_case_cursor_after_tick() {
184 check_assist(
185 introduce_named_lifetime,
186 r#"impl Cursor<'<|>_> {"#,
187 r#"impl<'a> Cursor<'a> {"#,
188 );
189 }
190
191 #[test]
192 fn test_impl_with_other_type_param() {
193 check_assist(
194 introduce_named_lifetime,
195 "impl<I> fmt::Display for SepByBuilder<'_<|>, I>
196 where
197 I: Iterator,
198 I::Item: fmt::Display,
199 {",
200 "impl<I, 'a> fmt::Display for SepByBuilder<'a, I>
201 where
202 I: Iterator,
203 I::Item: fmt::Display,
204 {",
205 )
206 }
207
208 #[test]
209 fn test_example_case_cursor_before_tick() {
210 check_assist(
211 introduce_named_lifetime,
212 r#"impl Cursor<<|>'_> {"#,
213 r#"impl<'a> Cursor<'a> {"#,
214 );
215 }
216
217 #[test]
218 fn test_not_applicable_cursor_position() {
219 check_assist_not_applicable(introduce_named_lifetime, r#"impl Cursor<'_><|> {"#);
220 check_assist_not_applicable(introduce_named_lifetime, r#"impl Cursor<|><'_> {"#);
221 }
222
223 #[test]
224 fn test_not_applicable_lifetime_already_name() {
225 check_assist_not_applicable(introduce_named_lifetime, r#"impl Cursor<'a<|>> {"#);
226 check_assist_not_applicable(introduce_named_lifetime, r#"fn my_fun<'a>() -> X<'a<|>>"#);
227 }
228
229 #[test]
230 fn test_with_type_parameter() {
231 check_assist(
232 introduce_named_lifetime,
233 r#"impl<T> Cursor<T, '_<|>>"#,
234 r#"impl<T, 'a> Cursor<T, 'a>"#,
235 );
236 }
237
238 #[test]
239 fn test_with_existing_lifetime_name_conflict() {
240 check_assist(
241 introduce_named_lifetime,
242 r#"impl<'a, 'b> Cursor<'a, 'b, '_<|>>"#,
243 r#"impl<'a, 'b, 'c> Cursor<'a, 'b, 'c>"#,
244 );
245 }
246
247 #[test]
248 fn test_function_return_value_anon_lifetime_param() {
249 check_assist(
250 introduce_named_lifetime,
251 r#"fn my_fun() -> X<'_<|>>"#,
252 r#"fn my_fun<'a>() -> X<'a>"#,
253 );
254 }
255
256 #[test]
257 fn test_function_return_value_anon_reference_lifetime() {
258 check_assist(
259 introduce_named_lifetime,
260 r#"fn my_fun() -> &'_<|> X"#,
261 r#"fn my_fun<'a>() -> &'a X"#,
262 );
263 }
264
265 #[test]
266 fn test_function_param_anon_lifetime() {
267 check_assist(
268 introduce_named_lifetime,
269 r#"fn my_fun(x: X<'_<|>>)"#,
270 r#"fn my_fun<'a>(x: X<'a>)"#,
271 );
272 }
273
274 #[test]
275 fn test_function_add_lifetime_to_params() {
276 check_assist(
277 introduce_named_lifetime,
278 r#"fn my_fun(f: &Foo) -> X<'_<|>>"#,
279 r#"fn my_fun<'a>(f: &'a Foo) -> X<'a>"#,
280 );
281 }
282
283 #[test]
284 fn test_function_add_lifetime_to_params_in_presence_of_other_lifetime() {
285 check_assist(
286 introduce_named_lifetime,
287 r#"fn my_fun<'other>(f: &Foo, b: &'other Bar) -> X<'_<|>>"#,
288 r#"fn my_fun<'other, 'a>(f: &'a Foo, b: &'other Bar) -> X<'a>"#,
289 );
290 }
291
292 #[test]
293 fn test_function_not_applicable_without_self_and_multiple_unnamed_param_lifetimes() {
294 // this is not permitted under lifetime elision rules
295 check_assist_not_applicable(
296 introduce_named_lifetime,
297 r#"fn my_fun(f: &Foo, b: &Bar) -> X<'_<|>>"#,
298 );
299 }
300
301 #[test]
302 fn test_function_add_lifetime_to_self_ref_param() {
303 check_assist(
304 introduce_named_lifetime,
305 r#"fn my_fun<'other>(&self, f: &Foo, b: &'other Bar) -> X<'_<|>>"#,
306 r#"fn my_fun<'other, 'a>(&'a self, f: &Foo, b: &'other Bar) -> X<'a>"#,
307 );
308 }
309
310 #[test]
311 fn test_function_add_lifetime_to_param_with_non_ref_self() {
312 check_assist(
313 introduce_named_lifetime,
314 r#"fn my_fun<'other>(self, f: &Foo, b: &'other Bar) -> X<'_<|>>"#,
315 r#"fn my_fun<'other, 'a>(self, f: &'a Foo, b: &'other Bar) -> X<'a>"#,
316 );
317 }
318}
diff --git a/crates/ra_assists/src/handlers/invert_if.rs b/crates/ra_assists/src/handlers/invert_if.rs
deleted file mode 100644
index f0e047538..000000000
--- a/crates/ra_assists/src/handlers/invert_if.rs
+++ /dev/null
@@ -1,109 +0,0 @@
1use syntax::{
2 ast::{self, AstNode},
3 T,
4};
5
6use crate::{
7 assist_context::{AssistContext, Assists},
8 utils::invert_boolean_expression,
9 AssistId, AssistKind,
10};
11
12// Assist: invert_if
13//
14// Apply invert_if
15// This transforms if expressions of the form `if !x {A} else {B}` into `if x {B} else {A}`
16// This also works with `!=`. This assist can only be applied with the cursor
17// on `if`.
18//
19// ```
20// fn main() {
21// if<|> !y { A } else { B }
22// }
23// ```
24// ->
25// ```
26// fn main() {
27// if y { B } else { A }
28// }
29// ```
30
31pub(crate) fn invert_if(acc: &mut Assists, ctx: &AssistContext) -> Option<()> {
32 let if_keyword = ctx.find_token_at_offset(T![if])?;
33 let expr = ast::IfExpr::cast(if_keyword.parent())?;
34 let if_range = if_keyword.text_range();
35 let cursor_in_range = if_range.contains_range(ctx.frange.range);
36 if !cursor_in_range {
37 return None;
38 }
39
40 // This assist should not apply for if-let.
41 if expr.condition()?.pat().is_some() {
42 return None;
43 }
44
45 let cond = expr.condition()?.expr()?;
46 let then_node = expr.then_branch()?.syntax().clone();
47 let else_block = match expr.else_branch()? {
48 ast::ElseBranch::Block(it) => it,
49 ast::ElseBranch::IfExpr(_) => return None,
50 };
51
52 let cond_range = cond.syntax().text_range();
53 let flip_cond = invert_boolean_expression(cond);
54 let else_node = else_block.syntax();
55 let else_range = else_node.text_range();
56 let then_range = then_node.text_range();
57 acc.add(AssistId("invert_if", AssistKind::RefactorRewrite), "Invert if", if_range, |edit| {
58 edit.replace(cond_range, flip_cond.syntax().text());
59 edit.replace(else_range, then_node.text());
60 edit.replace(then_range, else_node.text());
61 })
62}
63
64#[cfg(test)]
65mod tests {
66 use super::*;
67
68 use crate::tests::{check_assist, check_assist_not_applicable};
69
70 #[test]
71 fn invert_if_remove_inequality() {
72 check_assist(
73 invert_if,
74 "fn f() { i<|>f x != 3 { 1 } else { 3 + 2 } }",
75 "fn f() { if x == 3 { 3 + 2 } else { 1 } }",
76 )
77 }
78
79 #[test]
80 fn invert_if_remove_not() {
81 check_assist(
82 invert_if,
83 "fn f() { <|>if !cond { 3 * 2 } else { 1 } }",
84 "fn f() { if cond { 1 } else { 3 * 2 } }",
85 )
86 }
87
88 #[test]
89 fn invert_if_general_case() {
90 check_assist(
91 invert_if,
92 "fn f() { i<|>f cond { 3 * 2 } else { 1 } }",
93 "fn f() { if !cond { 1 } else { 3 * 2 } }",
94 )
95 }
96
97 #[test]
98 fn invert_if_doesnt_apply_with_cursor_not_on_if() {
99 check_assist_not_applicable(invert_if, "fn f() { if !<|>cond { 3 * 2 } else { 1 } }")
100 }
101
102 #[test]
103 fn invert_if_doesnt_apply_with_if_let() {
104 check_assist_not_applicable(
105 invert_if,
106 "fn f() { i<|>f let Some(_) = Some(1) { 1 } else { 0 } }",
107 )
108 }
109}
diff --git a/crates/ra_assists/src/handlers/merge_imports.rs b/crates/ra_assists/src/handlers/merge_imports.rs
deleted file mode 100644
index 47d465404..000000000
--- a/crates/ra_assists/src/handlers/merge_imports.rs
+++ /dev/null
@@ -1,321 +0,0 @@
1use std::iter::successors;
2
3use syntax::{
4 algo::{neighbor, skip_trivia_token, SyntaxRewriter},
5 ast::{self, edit::AstNodeEdit, make},
6 AstNode, Direction, InsertPosition, SyntaxElement, T,
7};
8
9use crate::{
10 assist_context::{AssistContext, Assists},
11 AssistId, AssistKind,
12};
13
14// Assist: merge_imports
15//
16// Merges two imports with a common prefix.
17//
18// ```
19// use std::<|>fmt::Formatter;
20// use std::io;
21// ```
22// ->
23// ```
24// use std::{fmt::Formatter, io};
25// ```
26pub(crate) fn merge_imports(acc: &mut Assists, ctx: &AssistContext) -> Option<()> {
27 let tree: ast::UseTree = ctx.find_node_at_offset()?;
28 let mut rewriter = SyntaxRewriter::default();
29 let mut offset = ctx.offset();
30
31 if let Some(use_item) = tree.syntax().parent().and_then(ast::Use::cast) {
32 let (merged, to_delete) = next_prev()
33 .filter_map(|dir| neighbor(&use_item, dir))
34 .filter_map(|it| Some((it.clone(), it.use_tree()?)))
35 .find_map(|(use_item, use_tree)| {
36 Some((try_merge_trees(&tree, &use_tree)?, use_item))
37 })?;
38
39 rewriter.replace_ast(&tree, &merged);
40 rewriter += to_delete.remove();
41
42 if to_delete.syntax().text_range().end() < offset {
43 offset -= to_delete.syntax().text_range().len();
44 }
45 } else {
46 let (merged, to_delete) = next_prev()
47 .filter_map(|dir| neighbor(&tree, dir))
48 .find_map(|use_tree| Some((try_merge_trees(&tree, &use_tree)?, use_tree.clone())))?;
49
50 rewriter.replace_ast(&tree, &merged);
51 rewriter += to_delete.remove();
52
53 if to_delete.syntax().text_range().end() < offset {
54 offset -= to_delete.syntax().text_range().len();
55 }
56 };
57
58 let target = tree.syntax().text_range();
59 acc.add(
60 AssistId("merge_imports", AssistKind::RefactorRewrite),
61 "Merge imports",
62 target,
63 |builder| {
64 builder.rewrite(rewriter);
65 },
66 )
67}
68
69fn next_prev() -> impl Iterator<Item = Direction> {
70 [Direction::Next, Direction::Prev].iter().copied()
71}
72
73fn try_merge_trees(old: &ast::UseTree, new: &ast::UseTree) -> Option<ast::UseTree> {
74 let lhs_path = old.path()?;
75 let rhs_path = new.path()?;
76
77 let (lhs_prefix, rhs_prefix) = common_prefix(&lhs_path, &rhs_path)?;
78
79 let lhs = old.split_prefix(&lhs_prefix);
80 let rhs = new.split_prefix(&rhs_prefix);
81
82 let should_insert_comma = lhs
83 .use_tree_list()?
84 .r_curly_token()
85 .and_then(|it| skip_trivia_token(it.prev_token()?, Direction::Prev))
86 .map(|it| it.kind() != T![,])
87 .unwrap_or(true);
88
89 let mut to_insert: Vec<SyntaxElement> = Vec::new();
90 if should_insert_comma {
91 to_insert.push(make::token(T![,]).into());
92 to_insert.push(make::tokens::single_space().into());
93 }
94 to_insert.extend(
95 rhs.use_tree_list()?
96 .syntax()
97 .children_with_tokens()
98 .filter(|it| it.kind() != T!['{'] && it.kind() != T!['}']),
99 );
100 let use_tree_list = lhs.use_tree_list()?;
101 let pos = InsertPosition::Before(use_tree_list.r_curly_token()?.into());
102 let use_tree_list = use_tree_list.insert_children(pos, to_insert);
103 Some(lhs.with_use_tree_list(use_tree_list))
104}
105
106fn common_prefix(lhs: &ast::Path, rhs: &ast::Path) -> Option<(ast::Path, ast::Path)> {
107 let mut res = None;
108 let mut lhs_curr = first_path(&lhs);
109 let mut rhs_curr = first_path(&rhs);
110 loop {
111 match (lhs_curr.segment(), rhs_curr.segment()) {
112 (Some(lhs), Some(rhs)) if lhs.syntax().text() == rhs.syntax().text() => (),
113 _ => break,
114 }
115 res = Some((lhs_curr.clone(), rhs_curr.clone()));
116
117 match (lhs_curr.parent_path(), rhs_curr.parent_path()) {
118 (Some(lhs), Some(rhs)) => {
119 lhs_curr = lhs;
120 rhs_curr = rhs;
121 }
122 _ => break,
123 }
124 }
125
126 res
127}
128
129fn first_path(path: &ast::Path) -> ast::Path {
130 successors(Some(path.clone()), |it| it.qualifier()).last().unwrap()
131}
132
133#[cfg(test)]
134mod tests {
135 use crate::tests::{check_assist, check_assist_not_applicable};
136
137 use super::*;
138
139 #[test]
140 fn test_merge_first() {
141 check_assist(
142 merge_imports,
143 r"
144use std::fmt<|>::Debug;
145use std::fmt::Display;
146",
147 r"
148use std::fmt::{Debug, Display};
149",
150 )
151 }
152
153 #[test]
154 fn test_merge_second() {
155 check_assist(
156 merge_imports,
157 r"
158use std::fmt::Debug;
159use std::fmt<|>::Display;
160",
161 r"
162use std::fmt::{Display, Debug};
163",
164 );
165 }
166
167 #[test]
168 fn merge_self1() {
169 check_assist(
170 merge_imports,
171 r"
172use std::fmt<|>;
173use std::fmt::Display;
174",
175 r"
176use std::fmt::{self, Display};
177",
178 );
179 }
180
181 #[test]
182 fn merge_self2() {
183 check_assist(
184 merge_imports,
185 r"
186use std::{fmt, <|>fmt::Display};
187",
188 r"
189use std::{fmt::{Display, self}};
190",
191 );
192 }
193
194 #[test]
195 fn test_merge_nested() {
196 check_assist(
197 merge_imports,
198 r"
199use std::{fmt<|>::Debug, fmt::Display};
200",
201 r"
202use std::{fmt::{Debug, Display}};
203",
204 );
205 check_assist(
206 merge_imports,
207 r"
208use std::{fmt::Debug, fmt<|>::Display};
209",
210 r"
211use std::{fmt::{Display, Debug}};
212",
213 );
214 }
215
216 #[test]
217 fn test_merge_single_wildcard_diff_prefixes() {
218 check_assist(
219 merge_imports,
220 r"
221use std<|>::cell::*;
222use std::str;
223",
224 r"
225use std::{cell::*, str};
226",
227 )
228 }
229
230 #[test]
231 fn test_merge_both_wildcard_diff_prefixes() {
232 check_assist(
233 merge_imports,
234 r"
235use std<|>::cell::*;
236use std::str::*;
237",
238 r"
239use std::{cell::*, str::*};
240",
241 )
242 }
243
244 #[test]
245 fn removes_just_enough_whitespace() {
246 check_assist(
247 merge_imports,
248 r"
249use foo<|>::bar;
250use foo::baz;
251
252/// Doc comment
253",
254 r"
255use foo::{bar, baz};
256
257/// Doc comment
258",
259 );
260 }
261
262 #[test]
263 fn works_with_trailing_comma() {
264 check_assist(
265 merge_imports,
266 r"
267use {
268 foo<|>::bar,
269 foo::baz,
270};
271",
272 r"
273use {
274 foo::{bar, baz},
275};
276",
277 );
278 check_assist(
279 merge_imports,
280 r"
281use {
282 foo::baz,
283 foo<|>::bar,
284};
285",
286 r"
287use {
288 foo::{bar, baz},
289};
290",
291 );
292 }
293
294 #[test]
295 fn test_double_comma() {
296 check_assist(
297 merge_imports,
298 r"
299use foo::bar::baz;
300use foo::<|>{
301 FooBar,
302};
303",
304 r"
305use foo::{
306 FooBar,
307bar::baz};
308",
309 )
310 }
311
312 #[test]
313 fn test_empty_use() {
314 check_assist_not_applicable(
315 merge_imports,
316 r"
317use std::<|>
318fn main() {}",
319 );
320 }
321}
diff --git a/crates/ra_assists/src/handlers/merge_match_arms.rs b/crates/ra_assists/src/handlers/merge_match_arms.rs
deleted file mode 100644
index c347eb40e..000000000
--- a/crates/ra_assists/src/handlers/merge_match_arms.rs
+++ /dev/null
@@ -1,248 +0,0 @@
1use std::iter::successors;
2
3use syntax::{
4 algo::neighbor,
5 ast::{self, AstNode},
6 Direction,
7};
8
9use crate::{AssistContext, AssistId, AssistKind, Assists, TextRange};
10
11// Assist: merge_match_arms
12//
13// Merges identical match arms.
14//
15// ```
16// enum Action { Move { distance: u32 }, Stop }
17//
18// fn handle(action: Action) {
19// match action {
20// <|>Action::Move(..) => foo(),
21// Action::Stop => foo(),
22// }
23// }
24// ```
25// ->
26// ```
27// enum Action { Move { distance: u32 }, Stop }
28//
29// fn handle(action: Action) {
30// match action {
31// Action::Move(..) | Action::Stop => foo(),
32// }
33// }
34// ```
35pub(crate) fn merge_match_arms(acc: &mut Assists, ctx: &AssistContext) -> Option<()> {
36 let current_arm = ctx.find_node_at_offset::<ast::MatchArm>()?;
37 // Don't try to handle arms with guards for now - can add support for this later
38 if current_arm.guard().is_some() {
39 return None;
40 }
41 let current_expr = current_arm.expr()?;
42 let current_text_range = current_arm.syntax().text_range();
43
44 // We check if the following match arms match this one. We could, but don't,
45 // compare to the previous match arm as well.
46 let arms_to_merge = successors(Some(current_arm), |it| neighbor(it, Direction::Next))
47 .take_while(|arm| {
48 if arm.guard().is_some() {
49 return false;
50 }
51 match arm.expr() {
52 Some(expr) => expr.syntax().text() == current_expr.syntax().text(),
53 None => false,
54 }
55 })
56 .collect::<Vec<_>>();
57
58 if arms_to_merge.len() <= 1 {
59 return None;
60 }
61
62 acc.add(
63 AssistId("merge_match_arms", AssistKind::RefactorRewrite),
64 "Merge match arms",
65 current_text_range,
66 |edit| {
67 let pats = if arms_to_merge.iter().any(contains_placeholder) {
68 "_".into()
69 } else {
70 arms_to_merge
71 .iter()
72 .filter_map(ast::MatchArm::pat)
73 .map(|x| x.syntax().to_string())
74 .collect::<Vec<String>>()
75 .join(" | ")
76 };
77
78 let arm = format!("{} => {}", pats, current_expr.syntax().text());
79
80 let start = arms_to_merge.first().unwrap().syntax().text_range().start();
81 let end = arms_to_merge.last().unwrap().syntax().text_range().end();
82
83 edit.replace(TextRange::new(start, end), arm);
84 },
85 )
86}
87
88fn contains_placeholder(a: &ast::MatchArm) -> bool {
89 matches!(a.pat(), Some(ast::Pat::WildcardPat(..)))
90}
91
92#[cfg(test)]
93mod tests {
94 use crate::tests::{check_assist, check_assist_not_applicable};
95
96 use super::*;
97
98 #[test]
99 fn merge_match_arms_single_patterns() {
100 check_assist(
101 merge_match_arms,
102 r#"
103 #[derive(Debug)]
104 enum X { A, B, C }
105
106 fn main() {
107 let x = X::A;
108 let y = match x {
109 X::A => { 1i32<|> }
110 X::B => { 1i32 }
111 X::C => { 2i32 }
112 }
113 }
114 "#,
115 r#"
116 #[derive(Debug)]
117 enum X { A, B, C }
118
119 fn main() {
120 let x = X::A;
121 let y = match x {
122 X::A | X::B => { 1i32 }
123 X::C => { 2i32 }
124 }
125 }
126 "#,
127 );
128 }
129
130 #[test]
131 fn merge_match_arms_multiple_patterns() {
132 check_assist(
133 merge_match_arms,
134 r#"
135 #[derive(Debug)]
136 enum X { A, B, C, D, E }
137
138 fn main() {
139 let x = X::A;
140 let y = match x {
141 X::A | X::B => {<|> 1i32 },
142 X::C | X::D => { 1i32 },
143 X::E => { 2i32 },
144 }
145 }
146 "#,
147 r#"
148 #[derive(Debug)]
149 enum X { A, B, C, D, E }
150
151 fn main() {
152 let x = X::A;
153 let y = match x {
154 X::A | X::B | X::C | X::D => { 1i32 },
155 X::E => { 2i32 },
156 }
157 }
158 "#,
159 );
160 }
161
162 #[test]
163 fn merge_match_arms_placeholder_pattern() {
164 check_assist(
165 merge_match_arms,
166 r#"
167 #[derive(Debug)]
168 enum X { A, B, C, D, E }
169
170 fn main() {
171 let x = X::A;
172 let y = match x {
173 X::A => { 1i32 },
174 X::B => { 2i<|>32 },
175 _ => { 2i32 }
176 }
177 }
178 "#,
179 r#"
180 #[derive(Debug)]
181 enum X { A, B, C, D, E }
182
183 fn main() {
184 let x = X::A;
185 let y = match x {
186 X::A => { 1i32 },
187 _ => { 2i32 }
188 }
189 }
190 "#,
191 );
192 }
193
194 #[test]
195 fn merges_all_subsequent_arms() {
196 check_assist(
197 merge_match_arms,
198 r#"
199 enum X { A, B, C, D, E }
200
201 fn main() {
202 match X::A {
203 X::A<|> => 92,
204 X::B => 92,
205 X::C => 92,
206 X::D => 62,
207 _ => panic!(),
208 }
209 }
210 "#,
211 r#"
212 enum X { A, B, C, D, E }
213
214 fn main() {
215 match X::A {
216 X::A | X::B | X::C => 92,
217 X::D => 62,
218 _ => panic!(),
219 }
220 }
221 "#,
222 )
223 }
224
225 #[test]
226 fn merge_match_arms_rejects_guards() {
227 check_assist_not_applicable(
228 merge_match_arms,
229 r#"
230 #[derive(Debug)]
231 enum X {
232 A(i32),
233 B,
234 C
235 }
236
237 fn main() {
238 let x = X::A;
239 let y = match x {
240 X::A(a) if a > 5 => { <|>1i32 },
241 X::B => { 1i32 },
242 X::C => { 2i32 }
243 }
244 }
245 "#,
246 );
247 }
248}
diff --git a/crates/ra_assists/src/handlers/move_bounds.rs b/crates/ra_assists/src/handlers/move_bounds.rs
deleted file mode 100644
index e2e461520..000000000
--- a/crates/ra_assists/src/handlers/move_bounds.rs
+++ /dev/null
@@ -1,152 +0,0 @@
1use syntax::{
2 ast::{self, edit::AstNodeEdit, make, AstNode, NameOwner, TypeBoundsOwner},
3 match_ast,
4 SyntaxKind::*,
5 T,
6};
7
8use crate::{AssistContext, AssistId, AssistKind, Assists};
9
10// Assist: move_bounds_to_where_clause
11//
12// Moves inline type bounds to a where clause.
13//
14// ```
15// fn apply<T, U, <|>F: FnOnce(T) -> U>(f: F, x: T) -> U {
16// f(x)
17// }
18// ```
19// ->
20// ```
21// fn apply<T, U, F>(f: F, x: T) -> U where F: FnOnce(T) -> U {
22// f(x)
23// }
24// ```
25pub(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>()?;
27
28 let mut type_params = type_param_list.type_params();
29 if type_params.all(|p| p.type_bound_list().is_none()) {
30 return None;
31 }
32
33 let parent = type_param_list.syntax().parent()?;
34 if parent.children_with_tokens().any(|it| it.kind() == WHERE_CLAUSE) {
35 return None;
36 }
37
38 let anchor = match_ast! {
39 match parent {
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(),
44 ast::Struct(it) => {
45 it.syntax().children_with_tokens()
46 .find(|it| it.kind() == RECORD_FIELD_LIST || it.kind() == T![;])?
47 },
48 _ => return None
49 }
50 };
51
52 let target = type_param_list.syntax().text_range();
53 acc.add(
54 AssistId("move_bounds_to_where_clause", AssistKind::RefactorRewrite),
55 "Move to where clause",
56 target,
57 |edit| {
58 let new_params = type_param_list
59 .type_params()
60 .filter(|it| it.type_bound_list().is_some())
61 .map(|type_param| {
62 let without_bounds = type_param.remove_bounds();
63 (type_param, without_bounds)
64 });
65
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);
68
69 let where_clause = {
70 let predicates = type_param_list.type_params().filter_map(build_predicate);
71 make::where_clause(predicates)
72 };
73
74 let to_insert = match anchor.prev_sibling_or_token() {
75 Some(ref elem) if elem.kind() == WHITESPACE => {
76 format!("{} ", where_clause.syntax())
77 }
78 _ => format!(" {}", where_clause.syntax()),
79 };
80 edit.insert(anchor.text_range().start(), to_insert);
81 },
82 )
83}
84
85fn build_predicate(param: ast::TypeParam) -> Option<ast::WherePred> {
86 let path = {
87 let name_ref = make::name_ref(&param.name()?.syntax().to_string());
88 let segment = make::path_segment(name_ref);
89 make::path_unqualified(segment)
90 };
91 let predicate = make::where_pred(path, param.type_bound_list()?.bounds());
92 Some(predicate)
93}
94
95#[cfg(test)]
96mod tests {
97 use super::*;
98
99 use crate::tests::check_assist;
100
101 #[test]
102 fn move_bounds_to_where_clause_fn() {
103 check_assist(
104 move_bounds_to_where_clause,
105 r#"
106 fn foo<T: u32, <|>F: FnOnce(T) -> T>() {}
107 "#,
108 r#"
109 fn foo<T, F>() where T: u32, F: FnOnce(T) -> T {}
110 "#,
111 );
112 }
113
114 #[test]
115 fn move_bounds_to_where_clause_impl() {
116 check_assist(
117 move_bounds_to_where_clause,
118 r#"
119 impl<U: u32, <|>T> A<U, T> {}
120 "#,
121 r#"
122 impl<U, T> A<U, T> where U: u32 {}
123 "#,
124 );
125 }
126
127 #[test]
128 fn move_bounds_to_where_clause_struct() {
129 check_assist(
130 move_bounds_to_where_clause,
131 r#"
132 struct A<<|>T: Iterator<Item = u32>> {}
133 "#,
134 r#"
135 struct A<T> where T: Iterator<Item = u32> {}
136 "#,
137 );
138 }
139
140 #[test]
141 fn move_bounds_to_where_clause_tuple_struct() {
142 check_assist(
143 move_bounds_to_where_clause,
144 r#"
145 struct Pair<<|>T: u32>(T, T);
146 "#,
147 r#"
148 struct Pair<T>(T, T) where T: u32;
149 "#,
150 );
151 }
152}
diff --git a/crates/ra_assists/src/handlers/move_guard.rs b/crates/ra_assists/src/handlers/move_guard.rs
deleted file mode 100644
index 452115fe6..000000000
--- a/crates/ra_assists/src/handlers/move_guard.rs
+++ /dev/null
@@ -1,293 +0,0 @@
1use syntax::{
2 ast::{edit::AstNodeEdit, make, AstNode, IfExpr, MatchArm},
3 SyntaxKind::WHITESPACE,
4};
5
6use crate::{AssistContext, AssistId, AssistKind, Assists};
7
8// Assist: move_guard_to_arm_body
9//
10// Moves match guard into match arm body.
11//
12// ```
13// enum Action { Move { distance: u32 }, Stop }
14//
15// fn handle(action: Action) {
16// match action {
17// Action::Move { distance } <|>if distance > 10 => foo(),
18// _ => (),
19// }
20// }
21// ```
22// ->
23// ```
24// enum Action { Move { distance: u32 }, Stop }
25//
26// fn handle(action: Action) {
27// match action {
28// Action::Move { distance } => if distance > 10 {
29// foo()
30// },
31// _ => (),
32// }
33// }
34// ```
35pub(crate) fn move_guard_to_arm_body(acc: &mut Assists, ctx: &AssistContext) -> Option<()> {
36 let match_arm = ctx.find_node_at_offset::<MatchArm>()?;
37 let guard = match_arm.guard()?;
38 let space_before_guard = guard.syntax().prev_sibling_or_token();
39
40 let guard_condition = guard.expr()?;
41 let arm_expr = match_arm.expr()?;
42 let if_expr = make::expr_if(
43 make::condition(guard_condition, None),
44 make::block_expr(None, Some(arm_expr.clone())),
45 )
46 .indent(arm_expr.indent_level());
47
48 let target = guard.syntax().text_range();
49 acc.add(
50 AssistId("move_guard_to_arm_body", AssistKind::RefactorRewrite),
51 "Move guard to arm body",
52 target,
53 |edit| {
54 match space_before_guard {
55 Some(element) if element.kind() == WHITESPACE => {
56 edit.delete(element.text_range());
57 }
58 _ => (),
59 };
60
61 edit.delete(guard.syntax().text_range());
62 edit.replace_ast(arm_expr, if_expr);
63 },
64 )
65}
66
67// Assist: move_arm_cond_to_match_guard
68//
69// Moves if expression from match arm body into a guard.
70//
71// ```
72// enum Action { Move { distance: u32 }, Stop }
73//
74// fn handle(action: Action) {
75// match action {
76// Action::Move { distance } => <|>if distance > 10 { foo() },
77// _ => (),
78// }
79// }
80// ```
81// ->
82// ```
83// enum Action { Move { distance: u32 }, Stop }
84//
85// fn handle(action: Action) {
86// match action {
87// Action::Move { distance } if distance > 10 => foo(),
88// _ => (),
89// }
90// }
91// ```
92pub(crate) fn move_arm_cond_to_match_guard(acc: &mut Assists, ctx: &AssistContext) -> Option<()> {
93 let match_arm: MatchArm = ctx.find_node_at_offset::<MatchArm>()?;
94 let match_pat = match_arm.pat()?;
95
96 let arm_body = match_arm.expr()?;
97 let if_expr: IfExpr = IfExpr::cast(arm_body.syntax().clone())?;
98 let cond = if_expr.condition()?;
99 let then_block = if_expr.then_branch()?;
100
101 // Not support if with else branch
102 if if_expr.else_branch().is_some() {
103 return None;
104 }
105 // Not support moving if let to arm guard
106 if cond.pat().is_some() {
107 return None;
108 }
109
110 let buf = format!(" if {}", cond.syntax().text());
111
112 let target = if_expr.syntax().text_range();
113 acc.add(
114 AssistId("move_arm_cond_to_match_guard", AssistKind::RefactorRewrite),
115 "Move condition to match guard",
116 target,
117 |edit| {
118 let then_only_expr = then_block.statements().next().is_none();
119
120 match &then_block.expr() {
121 Some(then_expr) if then_only_expr => {
122 edit.replace(if_expr.syntax().text_range(), then_expr.syntax().text())
123 }
124 _ => edit.replace(if_expr.syntax().text_range(), then_block.syntax().text()),
125 }
126
127 edit.insert(match_pat.syntax().text_range().end(), buf);
128 },
129 )
130}
131
132#[cfg(test)]
133mod tests {
134 use super::*;
135
136 use crate::tests::{check_assist, check_assist_not_applicable, check_assist_target};
137
138 #[test]
139 fn move_guard_to_arm_body_target() {
140 check_assist_target(
141 move_guard_to_arm_body,
142 r#"
143fn main() {
144 match 92 {
145 x <|>if x > 10 => false,
146 _ => true
147 }
148}
149"#,
150 r#"if x > 10"#,
151 );
152 }
153
154 #[test]
155 fn move_guard_to_arm_body_works() {
156 check_assist(
157 move_guard_to_arm_body,
158 r#"
159fn main() {
160 match 92 {
161 x <|>if x > 10 => false,
162 _ => true
163 }
164}
165"#,
166 r#"
167fn main() {
168 match 92 {
169 x => if x > 10 {
170 false
171 },
172 _ => true
173 }
174}
175"#,
176 );
177 }
178
179 #[test]
180 fn move_guard_to_arm_body_works_complex_match() {
181 check_assist(
182 move_guard_to_arm_body,
183 r#"
184fn main() {
185 match 92 {
186 <|>x @ 4 | x @ 5 if x > 5 => true,
187 _ => false
188 }
189}
190"#,
191 r#"
192fn main() {
193 match 92 {
194 x @ 4 | x @ 5 => if x > 5 {
195 true
196 },
197 _ => false
198 }
199}
200"#,
201 );
202 }
203
204 #[test]
205 fn move_arm_cond_to_match_guard_works() {
206 check_assist(
207 move_arm_cond_to_match_guard,
208 r#"
209fn main() {
210 match 92 {
211 x => if x > 10 { <|>false },
212 _ => true
213 }
214}
215"#,
216 r#"
217fn main() {
218 match 92 {
219 x if x > 10 => false,
220 _ => true
221 }
222}
223"#,
224 );
225 }
226
227 #[test]
228 fn move_arm_cond_to_match_guard_if_let_not_works() {
229 check_assist_not_applicable(
230 move_arm_cond_to_match_guard,
231 r#"
232fn main() {
233 match 92 {
234 x => if let 62 = x { <|>false },
235 _ => true
236 }
237}
238"#,
239 );
240 }
241
242 #[test]
243 fn move_arm_cond_to_match_guard_if_empty_body_works() {
244 check_assist(
245 move_arm_cond_to_match_guard,
246 r#"
247fn main() {
248 match 92 {
249 x => if x > 10 { <|> },
250 _ => true
251 }
252}
253"#,
254 r#"
255fn main() {
256 match 92 {
257 x if x > 10 => { },
258 _ => true
259 }
260}
261"#,
262 );
263 }
264
265 #[test]
266 fn move_arm_cond_to_match_guard_if_multiline_body_works() {
267 check_assist(
268 move_arm_cond_to_match_guard,
269 r#"
270fn main() {
271 match 92 {
272 x => if x > 10 {
273 92;<|>
274 false
275 },
276 _ => true
277 }
278}
279"#,
280 r#"
281fn main() {
282 match 92 {
283 x if x > 10 => {
284 92;
285 false
286 },
287 _ => true
288 }
289}
290"#,
291 );
292 }
293}
diff --git a/crates/ra_assists/src/handlers/raw_string.rs b/crates/ra_assists/src/handlers/raw_string.rs
deleted file mode 100644
index 9ddd116e0..000000000
--- a/crates/ra_assists/src/handlers/raw_string.rs
+++ /dev/null
@@ -1,504 +0,0 @@
1use std::borrow::Cow;
2
3use syntax::{
4 ast::{self, HasQuotes, HasStringValue},
5 AstToken,
6 SyntaxKind::{RAW_STRING, STRING},
7 TextRange, TextSize,
8};
9use test_utils::mark;
10
11use crate::{AssistContext, AssistId, AssistKind, Assists};
12
13// Assist: make_raw_string
14//
15// Adds `r#` to a plain string literal.
16//
17// ```
18// fn main() {
19// "Hello,<|> World!";
20// }
21// ```
22// ->
23// ```
24// fn main() {
25// r#"Hello, World!"#;
26// }
27// ```
28pub(crate) fn make_raw_string(acc: &mut Assists, ctx: &AssistContext) -> Option<()> {
29 let token = ctx.find_token_at_offset(STRING).and_then(ast::String::cast)?;
30 let value = token.value()?;
31 let target = token.syntax().text_range();
32 acc.add(
33 AssistId("make_raw_string", AssistKind::RefactorRewrite),
34 "Rewrite as raw string",
35 target,
36 |edit| {
37 let hashes = "#".repeat(required_hashes(&value).max(1));
38 if matches!(value, Cow::Borrowed(_)) {
39 // Avoid replacing the whole string to better position the cursor.
40 edit.insert(token.syntax().text_range().start(), format!("r{}", hashes));
41 edit.insert(token.syntax().text_range().end(), format!("{}", hashes));
42 } else {
43 edit.replace(
44 token.syntax().text_range(),
45 format!("r{}\"{}\"{}", hashes, value, hashes),
46 );
47 }
48 },
49 )
50}
51
52// Assist: make_usual_string
53//
54// Turns a raw string into a plain string.
55//
56// ```
57// fn main() {
58// r#"Hello,<|> "World!""#;
59// }
60// ```
61// ->
62// ```
63// fn main() {
64// "Hello, \"World!\"";
65// }
66// ```
67pub(crate) fn make_usual_string(acc: &mut Assists, ctx: &AssistContext) -> Option<()> {
68 let token = ctx.find_token_at_offset(RAW_STRING).and_then(ast::RawString::cast)?;
69 let value = token.value()?;
70 let target = token.syntax().text_range();
71 acc.add(
72 AssistId("make_usual_string", AssistKind::RefactorRewrite),
73 "Rewrite as regular string",
74 target,
75 |edit| {
76 // parse inside string to escape `"`
77 let escaped = value.escape_default().to_string();
78 if let Some(offsets) = token.quote_offsets() {
79 if token.text()[offsets.contents - token.syntax().text_range().start()] == escaped {
80 edit.replace(offsets.quotes.0, "\"");
81 edit.replace(offsets.quotes.1, "\"");
82 return;
83 }
84 }
85
86 edit.replace(token.syntax().text_range(), format!("\"{}\"", escaped));
87 },
88 )
89}
90
91// Assist: add_hash
92//
93// Adds a hash to a raw string literal.
94//
95// ```
96// fn main() {
97// r#"Hello,<|> World!"#;
98// }
99// ```
100// ->
101// ```
102// fn main() {
103// r##"Hello, World!"##;
104// }
105// ```
106pub(crate) fn add_hash(acc: &mut Assists, ctx: &AssistContext) -> Option<()> {
107 let token = ctx.find_token_at_offset(RAW_STRING)?;
108 let target = token.text_range();
109 acc.add(AssistId("add_hash", AssistKind::Refactor), "Add #", target, |edit| {
110 edit.insert(token.text_range().start() + TextSize::of('r'), "#");
111 edit.insert(token.text_range().end(), "#");
112 })
113}
114
115// Assist: remove_hash
116//
117// Removes a hash from a raw string literal.
118//
119// ```
120// fn main() {
121// r#"Hello,<|> World!"#;
122// }
123// ```
124// ->
125// ```
126// fn main() {
127// r"Hello, World!";
128// }
129// ```
130pub(crate) fn remove_hash(acc: &mut Assists, ctx: &AssistContext) -> Option<()> {
131 let token = ctx.find_token_at_offset(RAW_STRING).and_then(ast::RawString::cast)?;
132
133 let text = token.text().as_str();
134 if !text.starts_with("r#") && text.ends_with('#') {
135 return None;
136 }
137
138 let existing_hashes = text.chars().skip(1).take_while(|&it| it == '#').count();
139
140 let text_range = token.syntax().text_range();
141 let internal_text = &text[token.text_range_between_quotes()? - text_range.start()];
142
143 if existing_hashes == required_hashes(internal_text) {
144 mark::hit!(cant_remove_required_hash);
145 return None;
146 }
147
148 acc.add(AssistId("remove_hash", AssistKind::RefactorRewrite), "Remove #", text_range, |edit| {
149 edit.delete(TextRange::at(text_range.start() + TextSize::of('r'), TextSize::of('#')));
150 edit.delete(TextRange::new(text_range.end() - TextSize::of('#'), text_range.end()));
151 })
152}
153
154fn required_hashes(s: &str) -> usize {
155 let mut res = 0usize;
156 for idx in s.match_indices('"').map(|(i, _)| i) {
157 let (_, sub) = s.split_at(idx + 1);
158 let n_hashes = sub.chars().take_while(|c| *c == '#').count();
159 res = res.max(n_hashes + 1)
160 }
161 res
162}
163
164#[test]
165fn test_required_hashes() {
166 assert_eq!(0, required_hashes("abc"));
167 assert_eq!(0, required_hashes("###"));
168 assert_eq!(1, required_hashes("\""));
169 assert_eq!(2, required_hashes("\"#abc"));
170 assert_eq!(0, required_hashes("#abc"));
171 assert_eq!(3, required_hashes("#ab\"##c"));
172 assert_eq!(5, required_hashes("#ab\"##\"####c"));
173}
174
175#[cfg(test)]
176mod tests {
177 use test_utils::mark;
178
179 use crate::tests::{check_assist, check_assist_not_applicable, check_assist_target};
180
181 use super::*;
182
183 #[test]
184 fn make_raw_string_target() {
185 check_assist_target(
186 make_raw_string,
187 r#"
188 fn f() {
189 let s = <|>"random\nstring";
190 }
191 "#,
192 r#""random\nstring""#,
193 );
194 }
195
196 #[test]
197 fn make_raw_string_works() {
198 check_assist(
199 make_raw_string,
200 r#"
201fn f() {
202 let s = <|>"random\nstring";
203}
204"#,
205 r##"
206fn f() {
207 let s = r#"random
208string"#;
209}
210"##,
211 )
212 }
213
214 #[test]
215 fn make_raw_string_works_inside_macros() {
216 check_assist(
217 make_raw_string,
218 r#"
219 fn f() {
220 format!(<|>"x = {}", 92)
221 }
222 "#,
223 r##"
224 fn f() {
225 format!(r#"x = {}"#, 92)
226 }
227 "##,
228 )
229 }
230
231 #[test]
232 fn make_raw_string_hashes_inside_works() {
233 check_assist(
234 make_raw_string,
235 r###"
236fn f() {
237 let s = <|>"#random##\nstring";
238}
239"###,
240 r####"
241fn f() {
242 let s = r#"#random##
243string"#;
244}
245"####,
246 )
247 }
248
249 #[test]
250 fn make_raw_string_closing_hashes_inside_works() {
251 check_assist(
252 make_raw_string,
253 r###"
254fn f() {
255 let s = <|>"#random\"##\nstring";
256}
257"###,
258 r####"
259fn f() {
260 let s = r###"#random"##
261string"###;
262}
263"####,
264 )
265 }
266
267 #[test]
268 fn make_raw_string_nothing_to_unescape_works() {
269 check_assist(
270 make_raw_string,
271 r#"
272 fn f() {
273 let s = <|>"random string";
274 }
275 "#,
276 r##"
277 fn f() {
278 let s = r#"random string"#;
279 }
280 "##,
281 )
282 }
283
284 #[test]
285 fn make_raw_string_not_works_on_partial_string() {
286 check_assist_not_applicable(
287 make_raw_string,
288 r#"
289 fn f() {
290 let s = "foo<|>
291 }
292 "#,
293 )
294 }
295
296 #[test]
297 fn make_usual_string_not_works_on_partial_string() {
298 check_assist_not_applicable(
299 make_usual_string,
300 r#"
301 fn main() {
302 let s = r#"bar<|>
303 }
304 "#,
305 )
306 }
307
308 #[test]
309 fn add_hash_target() {
310 check_assist_target(
311 add_hash,
312 r#"
313 fn f() {
314 let s = <|>r"random string";
315 }
316 "#,
317 r#"r"random string""#,
318 );
319 }
320
321 #[test]
322 fn add_hash_works() {
323 check_assist(
324 add_hash,
325 r#"
326 fn f() {
327 let s = <|>r"random string";
328 }
329 "#,
330 r##"
331 fn f() {
332 let s = r#"random string"#;
333 }
334 "##,
335 )
336 }
337
338 #[test]
339 fn add_more_hash_works() {
340 check_assist(
341 add_hash,
342 r##"
343 fn f() {
344 let s = <|>r#"random"string"#;
345 }
346 "##,
347 r###"
348 fn f() {
349 let s = r##"random"string"##;
350 }
351 "###,
352 )
353 }
354
355 #[test]
356 fn add_hash_not_works() {
357 check_assist_not_applicable(
358 add_hash,
359 r#"
360 fn f() {
361 let s = <|>"random string";
362 }
363 "#,
364 );
365 }
366
367 #[test]
368 fn remove_hash_target() {
369 check_assist_target(
370 remove_hash,
371 r##"
372 fn f() {
373 let s = <|>r#"random string"#;
374 }
375 "##,
376 r##"r#"random string"#"##,
377 );
378 }
379
380 #[test]
381 fn remove_hash_works() {
382 check_assist(
383 remove_hash,
384 r##"fn f() { let s = <|>r#"random string"#; }"##,
385 r#"fn f() { let s = r"random string"; }"#,
386 )
387 }
388
389 #[test]
390 fn cant_remove_required_hash() {
391 mark::check!(cant_remove_required_hash);
392 check_assist_not_applicable(
393 remove_hash,
394 r##"
395 fn f() {
396 let s = <|>r#"random"str"ing"#;
397 }
398 "##,
399 )
400 }
401
402 #[test]
403 fn remove_more_hash_works() {
404 check_assist(
405 remove_hash,
406 r###"
407 fn f() {
408 let s = <|>r##"random string"##;
409 }
410 "###,
411 r##"
412 fn f() {
413 let s = r#"random string"#;
414 }
415 "##,
416 )
417 }
418
419 #[test]
420 fn remove_hash_doesnt_work() {
421 check_assist_not_applicable(remove_hash, r#"fn f() { let s = <|>"random string"; }"#);
422 }
423
424 #[test]
425 fn remove_hash_no_hash_doesnt_work() {
426 check_assist_not_applicable(remove_hash, r#"fn f() { let s = <|>r"random string"; }"#);
427 }
428
429 #[test]
430 fn make_usual_string_target() {
431 check_assist_target(
432 make_usual_string,
433 r##"
434 fn f() {
435 let s = <|>r#"random string"#;
436 }
437 "##,
438 r##"r#"random string"#"##,
439 );
440 }
441
442 #[test]
443 fn make_usual_string_works() {
444 check_assist(
445 make_usual_string,
446 r##"
447 fn f() {
448 let s = <|>r#"random string"#;
449 }
450 "##,
451 r#"
452 fn f() {
453 let s = "random string";
454 }
455 "#,
456 )
457 }
458
459 #[test]
460 fn make_usual_string_with_quote_works() {
461 check_assist(
462 make_usual_string,
463 r##"
464 fn f() {
465 let s = <|>r#"random"str"ing"#;
466 }
467 "##,
468 r#"
469 fn f() {
470 let s = "random\"str\"ing";
471 }
472 "#,
473 )
474 }
475
476 #[test]
477 fn make_usual_string_more_hash_works() {
478 check_assist(
479 make_usual_string,
480 r###"
481 fn f() {
482 let s = <|>r##"random string"##;
483 }
484 "###,
485 r##"
486 fn f() {
487 let s = "random string";
488 }
489 "##,
490 )
491 }
492
493 #[test]
494 fn make_usual_string_not_works() {
495 check_assist_not_applicable(
496 make_usual_string,
497 r#"
498 fn f() {
499 let s = <|>"random string";
500 }
501 "#,
502 );
503 }
504}
diff --git a/crates/ra_assists/src/handlers/remove_dbg.rs b/crates/ra_assists/src/handlers/remove_dbg.rs
deleted file mode 100644
index f3dcca534..000000000
--- a/crates/ra_assists/src/handlers/remove_dbg.rs
+++ /dev/null
@@ -1,205 +0,0 @@
1use syntax::{
2 ast::{self, AstNode},
3 TextRange, TextSize, T,
4};
5
6use crate::{AssistContext, AssistId, AssistKind, Assists};
7
8// Assist: remove_dbg
9//
10// Removes `dbg!()` macro call.
11//
12// ```
13// fn main() {
14// <|>dbg!(92);
15// }
16// ```
17// ->
18// ```
19// fn main() {
20// 92;
21// }
22// ```
23pub(crate) fn remove_dbg(acc: &mut Assists, ctx: &AssistContext) -> Option<()> {
24 let macro_call = ctx.find_node_at_offset::<ast::MacroCall>()?;
25
26 if !is_valid_macrocall(&macro_call, "dbg")? {
27 return None;
28 }
29
30 let is_leaf = macro_call.syntax().next_sibling().is_none();
31
32 let macro_end = if macro_call.semicolon_token().is_some() {
33 macro_call.syntax().text_range().end() - TextSize::of(';')
34 } else {
35 macro_call.syntax().text_range().end()
36 };
37
38 // macro_range determines what will be deleted and replaced with macro_content
39 let macro_range = TextRange::new(macro_call.syntax().text_range().start(), macro_end);
40 let paste_instead_of_dbg = {
41 let text = macro_call.token_tree()?.syntax().text();
42
43 // leafiness determines if we should include the parenthesis or not
44 let slice_index: TextRange = if is_leaf {
45 // leaf means - we can extract the contents of the dbg! in text
46 TextRange::new(TextSize::of('('), text.len() - TextSize::of(')'))
47 } else {
48 // not leaf - means we should keep the parens
49 TextRange::up_to(text.len())
50 };
51 text.slice(slice_index).to_string()
52 };
53
54 let target = macro_call.syntax().text_range();
55 acc.add(AssistId("remove_dbg", AssistKind::Refactor), "Remove dbg!()", target, |builder| {
56 builder.replace(macro_range, paste_instead_of_dbg);
57 })
58}
59
60/// Verifies that the given macro_call actually matches the given name
61/// and contains proper ending tokens
62fn is_valid_macrocall(macro_call: &ast::MacroCall, macro_name: &str) -> Option<bool> {
63 let path = macro_call.path()?;
64 let name_ref = path.segment()?.name_ref()?;
65
66 // Make sure it is actually a dbg-macro call, dbg followed by !
67 let excl = path.syntax().next_sibling_or_token()?;
68
69 if name_ref.text() != macro_name || excl.kind() != T![!] {
70 return None;
71 }
72
73 let node = macro_call.token_tree()?.syntax().clone();
74 let first_child = node.first_child_or_token()?;
75 let last_child = node.last_child_or_token()?;
76
77 match (first_child.kind(), last_child.kind()) {
78 (T!['('], T![')']) | (T!['['], T![']']) | (T!['{'], T!['}']) => Some(true),
79 _ => Some(false),
80 }
81}
82
83#[cfg(test)]
84mod tests {
85 use super::*;
86 use crate::tests::{check_assist, check_assist_not_applicable, check_assist_target};
87
88 #[test]
89 fn test_remove_dbg() {
90 check_assist(remove_dbg, "<|>dbg!(1 + 1)", "1 + 1");
91
92 check_assist(remove_dbg, "dbg!<|>((1 + 1))", "(1 + 1)");
93
94 check_assist(remove_dbg, "dbg!(1 <|>+ 1)", "1 + 1");
95
96 check_assist(remove_dbg, "let _ = <|>dbg!(1 + 1)", "let _ = 1 + 1");
97
98 check_assist(
99 remove_dbg,
100 "
101fn foo(n: usize) {
102 if let Some(_) = dbg!(n.<|>checked_sub(4)) {
103 // ...
104 }
105}
106",
107 "
108fn foo(n: usize) {
109 if let Some(_) = n.checked_sub(4) {
110 // ...
111 }
112}
113",
114 );
115 }
116
117 #[test]
118 fn test_remove_dbg_with_brackets_and_braces() {
119 check_assist(remove_dbg, "dbg![<|>1 + 1]", "1 + 1");
120 check_assist(remove_dbg, "dbg!{<|>1 + 1}", "1 + 1");
121 }
122
123 #[test]
124 fn test_remove_dbg_not_applicable() {
125 check_assist_not_applicable(remove_dbg, "<|>vec![1, 2, 3]");
126 check_assist_not_applicable(remove_dbg, "<|>dbg(5, 6, 7)");
127 check_assist_not_applicable(remove_dbg, "<|>dbg!(5, 6, 7");
128 }
129
130 #[test]
131 fn test_remove_dbg_target() {
132 check_assist_target(
133 remove_dbg,
134 "
135fn foo(n: usize) {
136 if let Some(_) = dbg!(n.<|>checked_sub(4)) {
137 // ...
138 }
139}
140",
141 "dbg!(n.checked_sub(4))",
142 );
143 }
144
145 #[test]
146 fn test_remove_dbg_keep_semicolon() {
147 // https://github.com/rust-analyzer/rust-analyzer/issues/5129#issuecomment-651399779
148 // not quite though
149 // adding a comment at the end of the line makes
150 // the ast::MacroCall to include the semicolon at the end
151 check_assist(
152 remove_dbg,
153 r#"let res = <|>dbg!(1 * 20); // needless comment"#,
154 r#"let res = 1 * 20; // needless comment"#,
155 );
156 }
157
158 #[test]
159 fn test_remove_dbg_keep_expression() {
160 check_assist(
161 remove_dbg,
162 r#"let res = <|>dbg!(a + b).foo();"#,
163 r#"let res = (a + b).foo();"#,
164 );
165 }
166
167 #[test]
168 fn test_remove_dbg_from_inside_fn() {
169 check_assist_target(
170 remove_dbg,
171 r#"
172fn square(x: u32) -> u32 {
173 x * x
174}
175
176fn main() {
177 let x = square(dbg<|>!(5 + 10));
178 println!("{}", x);
179}"#,
180 "dbg!(5 + 10)",
181 );
182
183 check_assist(
184 remove_dbg,
185 r#"
186fn square(x: u32) -> u32 {
187 x * x
188}
189
190fn main() {
191 let x = square(dbg<|>!(5 + 10));
192 println!("{}", x);
193}"#,
194 r#"
195fn square(x: u32) -> u32 {
196 x * x
197}
198
199fn main() {
200 let x = square(5 + 10);
201 println!("{}", x);
202}"#,
203 );
204 }
205}
diff --git a/crates/ra_assists/src/handlers/remove_mut.rs b/crates/ra_assists/src/handlers/remove_mut.rs
deleted file mode 100644
index 44f41daa9..000000000
--- a/crates/ra_assists/src/handlers/remove_mut.rs
+++ /dev/null
@@ -1,37 +0,0 @@
1use syntax::{SyntaxKind, TextRange, T};
2
3use crate::{AssistContext, AssistId, AssistKind, Assists};
4
5// Assist: remove_mut
6//
7// Removes the `mut` keyword.
8//
9// ```
10// impl Walrus {
11// fn feed(&mut<|> self, amount: u32) {}
12// }
13// ```
14// ->
15// ```
16// impl Walrus {
17// fn feed(&self, amount: u32) {}
18// }
19// ```
20pub(crate) fn remove_mut(acc: &mut Assists, ctx: &AssistContext) -> Option<()> {
21 let mut_token = ctx.find_token_at_offset(T![mut])?;
22 let delete_from = mut_token.text_range().start();
23 let delete_to = match mut_token.next_token() {
24 Some(it) if it.kind() == SyntaxKind::WHITESPACE => it.text_range().end(),
25 _ => mut_token.text_range().end(),
26 };
27
28 let target = mut_token.text_range();
29 acc.add(
30 AssistId("remove_mut", AssistKind::Refactor),
31 "Remove `mut` keyword",
32 target,
33 |builder| {
34 builder.delete(TextRange::new(delete_from, delete_to));
35 },
36 )
37}
diff --git a/crates/ra_assists/src/handlers/reorder_fields.rs b/crates/ra_assists/src/handlers/reorder_fields.rs
deleted file mode 100644
index 527f457a7..000000000
--- a/crates/ra_assists/src/handlers/reorder_fields.rs
+++ /dev/null
@@ -1,220 +0,0 @@
1use itertools::Itertools;
2use rustc_hash::FxHashMap;
3
4use hir::{Adt, ModuleDef, PathResolution, Semantics, Struct};
5use ide_db::RootDatabase;
6use syntax::{algo, ast, match_ast, AstNode, SyntaxKind, SyntaxKind::*, SyntaxNode};
7
8use crate::{AssistContext, AssistId, AssistKind, Assists};
9
10// Assist: reorder_fields
11//
12// Reorder the fields of record literals and record patterns in the same order as in
13// the definition.
14//
15// ```
16// struct Foo {foo: i32, bar: i32};
17// const test: Foo = <|>Foo {bar: 0, foo: 1}
18// ```
19// ->
20// ```
21// struct Foo {foo: i32, bar: i32};
22// const test: Foo = Foo {foo: 1, bar: 0}
23// ```
24//
25pub(crate) fn reorder_fields(acc: &mut Assists, ctx: &AssistContext) -> Option<()> {
26 reorder::<ast::RecordExpr>(acc, ctx).or_else(|| reorder::<ast::RecordPat>(acc, ctx))
27}
28
29fn reorder<R: AstNode>(acc: &mut Assists, ctx: &AssistContext) -> Option<()> {
30 let record = ctx.find_node_at_offset::<R>()?;
31 let path = record.syntax().children().find_map(ast::Path::cast)?;
32
33 let ranks = compute_fields_ranks(&path, &ctx)?;
34
35 let fields = get_fields(&record.syntax());
36 let sorted_fields = sorted_by_rank(&fields, |node| {
37 *ranks.get(&get_field_name(node)).unwrap_or(&usize::max_value())
38 });
39
40 if sorted_fields == fields {
41 return None;
42 }
43
44 let target = record.syntax().text_range();
45 acc.add(
46 AssistId("reorder_fields", AssistKind::RefactorRewrite),
47 "Reorder record fields",
48 target,
49 |edit| {
50 for (old, new) in fields.iter().zip(&sorted_fields) {
51 algo::diff(old, new).into_text_edit(edit.text_edit_builder());
52 }
53 },
54 )
55}
56
57fn get_fields_kind(node: &SyntaxNode) -> Vec<SyntaxKind> {
58 match node.kind() {
59 RECORD_EXPR => vec![RECORD_EXPR_FIELD],
60 RECORD_PAT => vec![RECORD_PAT_FIELD, IDENT_PAT],
61 _ => vec![],
62 }
63}
64
65fn get_field_name(node: &SyntaxNode) -> String {
66 let res = match_ast! {
67 match node {
68 ast::RecordExprField(field) => field.field_name().map(|it| it.to_string()),
69 ast::RecordPatField(field) => field.field_name().map(|it| it.to_string()),
70 _ => None,
71 }
72 };
73 res.unwrap_or_default()
74}
75
76fn get_fields(record: &SyntaxNode) -> Vec<SyntaxNode> {
77 let kinds = get_fields_kind(record);
78 record.children().flat_map(|n| n.children()).filter(|n| kinds.contains(&n.kind())).collect()
79}
80
81fn sorted_by_rank(
82 fields: &[SyntaxNode],
83 get_rank: impl Fn(&SyntaxNode) -> usize,
84) -> Vec<SyntaxNode> {
85 fields.iter().cloned().sorted_by_key(get_rank).collect()
86}
87
88fn struct_definition(path: &ast::Path, sema: &Semantics<RootDatabase>) -> Option<Struct> {
89 match sema.resolve_path(path) {
90 Some(PathResolution::Def(ModuleDef::Adt(Adt::Struct(s)))) => Some(s),
91 _ => None,
92 }
93}
94
95fn compute_fields_ranks(path: &ast::Path, ctx: &AssistContext) -> Option<FxHashMap<String, usize>> {
96 Some(
97 struct_definition(path, &ctx.sema)?
98 .fields(ctx.db())
99 .iter()
100 .enumerate()
101 .map(|(idx, field)| (field.name(ctx.db()).to_string(), idx))
102 .collect(),
103 )
104}
105
106#[cfg(test)]
107mod tests {
108 use crate::tests::{check_assist, check_assist_not_applicable};
109
110 use super::*;
111
112 #[test]
113 fn not_applicable_if_sorted() {
114 check_assist_not_applicable(
115 reorder_fields,
116 r#"
117 struct Foo {
118 foo: i32,
119 bar: i32,
120 }
121
122 const test: Foo = <|>Foo { foo: 0, bar: 0 };
123 "#,
124 )
125 }
126
127 #[test]
128 fn trivial_empty_fields() {
129 check_assist_not_applicable(
130 reorder_fields,
131 r#"
132 struct Foo {};
133 const test: Foo = <|>Foo {}
134 "#,
135 )
136 }
137
138 #[test]
139 fn reorder_struct_fields() {
140 check_assist(
141 reorder_fields,
142 r#"
143 struct Foo {foo: i32, bar: i32};
144 const test: Foo = <|>Foo {bar: 0, foo: 1}
145 "#,
146 r#"
147 struct Foo {foo: i32, bar: i32};
148 const test: Foo = Foo {foo: 1, bar: 0}
149 "#,
150 )
151 }
152
153 #[test]
154 fn reorder_struct_pattern() {
155 check_assist(
156 reorder_fields,
157 r#"
158 struct Foo { foo: i64, bar: i64, baz: i64 }
159
160 fn f(f: Foo) -> {
161 match f {
162 <|>Foo { baz: 0, ref mut bar, .. } => (),
163 _ => ()
164 }
165 }
166 "#,
167 r#"
168 struct Foo { foo: i64, bar: i64, baz: i64 }
169
170 fn f(f: Foo) -> {
171 match f {
172 Foo { ref mut bar, baz: 0, .. } => (),
173 _ => ()
174 }
175 }
176 "#,
177 )
178 }
179
180 #[test]
181 fn reorder_with_extra_field() {
182 check_assist(
183 reorder_fields,
184 r#"
185 struct Foo {
186 foo: String,
187 bar: String,
188 }
189
190 impl Foo {
191 fn new() -> Foo {
192 let foo = String::new();
193 <|>Foo {
194 bar: foo.clone(),
195 extra: "Extra field",
196 foo,
197 }
198 }
199 }
200 "#,
201 r#"
202 struct Foo {
203 foo: String,
204 bar: String,
205 }
206
207 impl Foo {
208 fn new() -> Foo {
209 let foo = String::new();
210 Foo {
211 foo,
212 bar: foo.clone(),
213 extra: "Extra field",
214 }
215 }
216 }
217 "#,
218 )
219 }
220}
diff --git a/crates/ra_assists/src/handlers/replace_if_let_with_match.rs b/crates/ra_assists/src/handlers/replace_if_let_with_match.rs
deleted file mode 100644
index 79097621e..000000000
--- a/crates/ra_assists/src/handlers/replace_if_let_with_match.rs
+++ /dev/null
@@ -1,257 +0,0 @@
1use syntax::{
2 ast::{
3 self,
4 edit::{AstNodeEdit, IndentLevel},
5 make,
6 },
7 AstNode,
8};
9
10use crate::{
11 utils::{unwrap_trivial_block, TryEnum},
12 AssistContext, AssistId, AssistKind, Assists,
13};
14
15// Assist: replace_if_let_with_match
16//
17// Replaces `if let` with an else branch with a `match` expression.
18//
19// ```
20// enum Action { Move { distance: u32 }, Stop }
21//
22// fn handle(action: Action) {
23// <|>if let Action::Move { distance } = action {
24// foo(distance)
25// } else {
26// bar()
27// }
28// }
29// ```
30// ->
31// ```
32// enum Action { Move { distance: u32 }, Stop }
33//
34// fn handle(action: Action) {
35// match action {
36// Action::Move { distance } => foo(distance),
37// _ => bar(),
38// }
39// }
40// ```
41pub(crate) fn replace_if_let_with_match(acc: &mut Assists, ctx: &AssistContext) -> Option<()> {
42 let if_expr: ast::IfExpr = ctx.find_node_at_offset()?;
43 let cond = if_expr.condition()?;
44 let pat = cond.pat()?;
45 let expr = cond.expr()?;
46 let then_block = if_expr.then_branch()?;
47 let else_block = match if_expr.else_branch()? {
48 ast::ElseBranch::Block(it) => it,
49 ast::ElseBranch::IfExpr(_) => return None,
50 };
51
52 let target = if_expr.syntax().text_range();
53 acc.add(
54 AssistId("replace_if_let_with_match", AssistKind::RefactorRewrite),
55 "Replace with match",
56 target,
57 move |edit| {
58 let match_expr = {
59 let then_arm = {
60 let then_block = then_block.reset_indent().indent(IndentLevel(1));
61 let then_expr = unwrap_trivial_block(then_block);
62 make::match_arm(vec![pat.clone()], then_expr)
63 };
64 let else_arm = {
65 let pattern = ctx
66 .sema
67 .type_of_pat(&pat)
68 .and_then(|ty| TryEnum::from_ty(&ctx.sema, &ty))
69 .map(|it| it.sad_pattern())
70 .unwrap_or_else(|| make::wildcard_pat().into());
71 let else_expr = unwrap_trivial_block(else_block);
72 make::match_arm(vec![pattern], else_expr)
73 };
74 let match_expr =
75 make::expr_match(expr, make::match_arm_list(vec![then_arm, else_arm]));
76 match_expr.indent(IndentLevel::from_node(if_expr.syntax()))
77 };
78
79 edit.replace_ast::<ast::Expr>(if_expr.into(), match_expr);
80 },
81 )
82}
83
84#[cfg(test)]
85mod tests {
86 use super::*;
87
88 use crate::tests::{check_assist, check_assist_target};
89
90 #[test]
91 fn test_replace_if_let_with_match_unwraps_simple_expressions() {
92 check_assist(
93 replace_if_let_with_match,
94 r#"
95impl VariantData {
96 pub fn is_struct(&self) -> bool {
97 if <|>let VariantData::Struct(..) = *self {
98 true
99 } else {
100 false
101 }
102 }
103} "#,
104 r#"
105impl VariantData {
106 pub fn is_struct(&self) -> bool {
107 match *self {
108 VariantData::Struct(..) => true,
109 _ => false,
110 }
111 }
112} "#,
113 )
114 }
115
116 #[test]
117 fn test_replace_if_let_with_match_doesnt_unwrap_multiline_expressions() {
118 check_assist(
119 replace_if_let_with_match,
120 r#"
121fn foo() {
122 if <|>let VariantData::Struct(..) = a {
123 bar(
124 123
125 )
126 } else {
127 false
128 }
129} "#,
130 r#"
131fn foo() {
132 match a {
133 VariantData::Struct(..) => {
134 bar(
135 123
136 )
137 }
138 _ => false,
139 }
140} "#,
141 )
142 }
143
144 #[test]
145 fn replace_if_let_with_match_target() {
146 check_assist_target(
147 replace_if_let_with_match,
148 r#"
149impl VariantData {
150 pub fn is_struct(&self) -> bool {
151 if <|>let VariantData::Struct(..) = *self {
152 true
153 } else {
154 false
155 }
156 }
157} "#,
158 "if let VariantData::Struct(..) = *self {
159 true
160 } else {
161 false
162 }",
163 );
164 }
165
166 #[test]
167 fn special_case_option() {
168 check_assist(
169 replace_if_let_with_match,
170 r#"
171enum Option<T> { Some(T), None }
172use Option::*;
173
174fn foo(x: Option<i32>) {
175 <|>if let Some(x) = x {
176 println!("{}", x)
177 } else {
178 println!("none")
179 }
180}
181 "#,
182 r#"
183enum Option<T> { Some(T), None }
184use Option::*;
185
186fn foo(x: Option<i32>) {
187 match x {
188 Some(x) => println!("{}", x),
189 None => println!("none"),
190 }
191}
192 "#,
193 );
194 }
195
196 #[test]
197 fn special_case_result() {
198 check_assist(
199 replace_if_let_with_match,
200 r#"
201enum Result<T, E> { Ok(T), Err(E) }
202use Result::*;
203
204fn foo(x: Result<i32, ()>) {
205 <|>if let Ok(x) = x {
206 println!("{}", x)
207 } else {
208 println!("none")
209 }
210}
211 "#,
212 r#"
213enum Result<T, E> { Ok(T), Err(E) }
214use Result::*;
215
216fn foo(x: Result<i32, ()>) {
217 match x {
218 Ok(x) => println!("{}", x),
219 Err(_) => println!("none"),
220 }
221}
222 "#,
223 );
224 }
225
226 #[test]
227 fn nested_indent() {
228 check_assist(
229 replace_if_let_with_match,
230 r#"
231fn main() {
232 if true {
233 <|>if let Ok(rel_path) = path.strip_prefix(root_path) {
234 let rel_path = RelativePathBuf::from_path(rel_path).ok()?;
235 Some((*id, rel_path))
236 } else {
237 None
238 }
239 }
240}
241"#,
242 r#"
243fn main() {
244 if true {
245 match path.strip_prefix(root_path) {
246 Ok(rel_path) => {
247 let rel_path = RelativePathBuf::from_path(rel_path).ok()?;
248 Some((*id, rel_path))
249 }
250 _ => None,
251 }
252 }
253}
254"#,
255 )
256 }
257}
diff --git a/crates/ra_assists/src/handlers/replace_let_with_if_let.rs b/crates/ra_assists/src/handlers/replace_let_with_if_let.rs
deleted file mode 100644
index ed6d0c29b..000000000
--- a/crates/ra_assists/src/handlers/replace_let_with_if_let.rs
+++ /dev/null
@@ -1,100 +0,0 @@
1use std::iter::once;
2
3use syntax::{
4 ast::{
5 self,
6 edit::{AstNodeEdit, IndentLevel},
7 make,
8 },
9 AstNode, T,
10};
11
12use crate::{utils::TryEnum, AssistContext, AssistId, AssistKind, Assists};
13
14// Assist: replace_let_with_if_let
15//
16// Replaces `let` with an `if-let`.
17//
18// ```
19// # enum Option<T> { Some(T), None }
20//
21// fn main(action: Action) {
22// <|>let x = compute();
23// }
24//
25// fn compute() -> Option<i32> { None }
26// ```
27// ->
28// ```
29// # enum Option<T> { Some(T), None }
30//
31// fn main(action: Action) {
32// if let Some(x) = compute() {
33// }
34// }
35//
36// fn compute() -> Option<i32> { None }
37// ```
38pub(crate) fn replace_let_with_if_let(acc: &mut Assists, ctx: &AssistContext) -> Option<()> {
39 let let_kw = ctx.find_token_at_offset(T![let])?;
40 let let_stmt = let_kw.ancestors().find_map(ast::LetStmt::cast)?;
41 let init = let_stmt.initializer()?;
42 let original_pat = let_stmt.pat()?;
43 let ty = ctx.sema.type_of_expr(&init)?;
44 let happy_variant = TryEnum::from_ty(&ctx.sema, &ty).map(|it| it.happy_case());
45
46 let target = let_kw.text_range();
47 acc.add(
48 AssistId("replace_let_with_if_let", AssistKind::RefactorRewrite),
49 "Replace with if-let",
50 target,
51 |edit| {
52 let with_placeholder: ast::Pat = match happy_variant {
53 None => make::wildcard_pat().into(),
54 Some(var_name) => make::tuple_struct_pat(
55 make::path_unqualified(make::path_segment(make::name_ref(var_name))),
56 once(make::wildcard_pat().into()),
57 )
58 .into(),
59 };
60 let block =
61 make::block_expr(None, None).indent(IndentLevel::from_node(let_stmt.syntax()));
62 let if_ = make::expr_if(make::condition(init, Some(with_placeholder)), block);
63 let stmt = make::expr_stmt(if_);
64
65 let placeholder = stmt.syntax().descendants().find_map(ast::WildcardPat::cast).unwrap();
66 let stmt = stmt.replace_descendant(placeholder.into(), original_pat);
67
68 edit.replace_ast(ast::Stmt::from(let_stmt), ast::Stmt::from(stmt));
69 },
70 )
71}
72
73#[cfg(test)]
74mod tests {
75 use crate::tests::check_assist;
76
77 use super::*;
78
79 #[test]
80 fn replace_let_unknown_enum() {
81 check_assist(
82 replace_let_with_if_let,
83 r"
84enum E<T> { X(T), Y(T) }
85
86fn main() {
87 <|>let x = E::X(92);
88}
89 ",
90 r"
91enum E<T> { X(T), Y(T) }
92
93fn main() {
94 if let x = E::X(92) {
95 }
96}
97 ",
98 )
99 }
100}
diff --git a/crates/ra_assists/src/handlers/replace_qualified_name_with_use.rs b/crates/ra_assists/src/handlers/replace_qualified_name_with_use.rs
deleted file mode 100644
index 011bf1106..000000000
--- a/crates/ra_assists/src/handlers/replace_qualified_name_with_use.rs
+++ /dev/null
@@ -1,688 +0,0 @@
1use hir;
2use syntax::{algo::SyntaxRewriter, ast, match_ast, AstNode, SmolStr, SyntaxNode};
3
4use crate::{
5 utils::{find_insert_use_container, insert_use_statement},
6 AssistContext, AssistId, AssistKind, Assists,
7};
8
9// Assist: replace_qualified_name_with_use
10//
11// Adds a use statement for a given fully-qualified name.
12//
13// ```
14// fn process(map: std::collections::<|>HashMap<String, String>) {}
15// ```
16// ->
17// ```
18// use std::collections::HashMap;
19//
20// fn process(map: HashMap<String, String>) {}
21// ```
22pub(crate) fn replace_qualified_name_with_use(
23 acc: &mut Assists,
24 ctx: &AssistContext,
25) -> Option<()> {
26 let path: ast::Path = ctx.find_node_at_offset()?;
27 // We don't want to mess with use statements
28 if path.syntax().ancestors().find_map(ast::Use::cast).is_some() {
29 return None;
30 }
31
32 let hir_path = ctx.sema.lower_path(&path)?;
33 let segments = collect_hir_path_segments(&hir_path)?;
34 if segments.len() < 2 {
35 return None;
36 }
37
38 let target = path.syntax().text_range();
39 acc.add(
40 AssistId("replace_qualified_name_with_use", AssistKind::RefactorRewrite),
41 "Replace qualified path with use",
42 target,
43 |builder| {
44 let path_to_import = hir_path.mod_path().clone();
45 let container = match find_insert_use_container(path.syntax(), ctx) {
46 Some(c) => c,
47 None => return,
48 };
49 insert_use_statement(path.syntax(), &path_to_import, ctx, builder.text_edit_builder());
50
51 // Now that we've brought the name into scope, re-qualify all paths that could be
52 // affected (that is, all paths inside the node we added the `use` to).
53 let mut rewriter = SyntaxRewriter::default();
54 let syntax = container.either(|l| l.syntax().clone(), |r| r.syntax().clone());
55 shorten_paths(&mut rewriter, syntax, path);
56 builder.rewrite(rewriter);
57 },
58 )
59}
60
61fn collect_hir_path_segments(path: &hir::Path) -> Option<Vec<SmolStr>> {
62 let mut ps = Vec::<SmolStr>::with_capacity(10);
63 match path.kind() {
64 hir::PathKind::Abs => ps.push("".into()),
65 hir::PathKind::Crate => ps.push("crate".into()),
66 hir::PathKind::Plain => {}
67 hir::PathKind::Super(0) => ps.push("self".into()),
68 hir::PathKind::Super(lvl) => {
69 let mut chain = "super".to_string();
70 for _ in 0..*lvl {
71 chain += "::super";
72 }
73 ps.push(chain.into());
74 }
75 hir::PathKind::DollarCrate(_) => return None,
76 }
77 ps.extend(path.segments().iter().map(|it| it.name.to_string().into()));
78 Some(ps)
79}
80
81/// Adds replacements to `re` that shorten `path` in all descendants of `node`.
82fn shorten_paths(rewriter: &mut SyntaxRewriter<'static>, node: SyntaxNode, path: ast::Path) {
83 for child in node.children() {
84 match_ast! {
85 match child {
86 // Don't modify `use` items, as this can break the `use` item when injecting a new
87 // import into the use tree.
88 ast::Use(_it) => continue,
89 // Don't descend into submodules, they don't have the same `use` items in scope.
90 ast::Module(_it) => continue,
91
92 ast::Path(p) => {
93 match maybe_replace_path(rewriter, p.clone(), path.clone()) {
94 Some(()) => {},
95 None => shorten_paths(rewriter, p.syntax().clone(), path.clone()),
96 }
97 },
98 _ => shorten_paths(rewriter, child, path.clone()),
99 }
100 }
101 }
102}
103
104fn maybe_replace_path(
105 rewriter: &mut SyntaxRewriter<'static>,
106 path: ast::Path,
107 target: ast::Path,
108) -> Option<()> {
109 if !path_eq(path.clone(), target) {
110 return None;
111 }
112
113 // Shorten `path`, leaving only its last segment.
114 if let Some(parent) = path.qualifier() {
115 rewriter.delete(parent.syntax());
116 }
117 if let Some(double_colon) = path.coloncolon_token() {
118 rewriter.delete(&double_colon);
119 }
120
121 Some(())
122}
123
124fn path_eq(lhs: ast::Path, rhs: ast::Path) -> bool {
125 let mut lhs_curr = lhs;
126 let mut rhs_curr = rhs;
127 loop {
128 match (lhs_curr.segment(), rhs_curr.segment()) {
129 (Some(lhs), Some(rhs)) if lhs.syntax().text() == rhs.syntax().text() => (),
130 _ => return false,
131 }
132
133 match (lhs_curr.qualifier(), rhs_curr.qualifier()) {
134 (Some(lhs), Some(rhs)) => {
135 lhs_curr = lhs;
136 rhs_curr = rhs;
137 }
138 (None, None) => return true,
139 _ => return false,
140 }
141 }
142}
143
144#[cfg(test)]
145mod tests {
146 use crate::tests::{check_assist, check_assist_not_applicable};
147
148 use super::*;
149
150 #[test]
151 fn test_replace_add_use_no_anchor() {
152 check_assist(
153 replace_qualified_name_with_use,
154 r"
155std::fmt::Debug<|>
156 ",
157 r"
158use std::fmt::Debug;
159
160Debug
161 ",
162 );
163 }
164 #[test]
165 fn test_replace_add_use_no_anchor_with_item_below() {
166 check_assist(
167 replace_qualified_name_with_use,
168 r"
169std::fmt::Debug<|>
170
171fn main() {
172}
173 ",
174 r"
175use std::fmt::Debug;
176
177Debug
178
179fn main() {
180}
181 ",
182 );
183 }
184
185 #[test]
186 fn test_replace_add_use_no_anchor_with_item_above() {
187 check_assist(
188 replace_qualified_name_with_use,
189 r"
190fn main() {
191}
192
193std::fmt::Debug<|>
194 ",
195 r"
196use std::fmt::Debug;
197
198fn main() {
199}
200
201Debug
202 ",
203 );
204 }
205
206 #[test]
207 fn test_replace_add_use_no_anchor_2seg() {
208 check_assist(
209 replace_qualified_name_with_use,
210 r"
211std::fmt<|>::Debug
212 ",
213 r"
214use std::fmt;
215
216fmt::Debug
217 ",
218 );
219 }
220
221 #[test]
222 fn test_replace_add_use() {
223 check_assist(
224 replace_qualified_name_with_use,
225 r"
226use stdx;
227
228impl std::fmt::Debug<|> for Foo {
229}
230 ",
231 r"
232use stdx;
233use std::fmt::Debug;
234
235impl Debug for Foo {
236}
237 ",
238 );
239 }
240
241 #[test]
242 fn test_replace_file_use_other_anchor() {
243 check_assist(
244 replace_qualified_name_with_use,
245 r"
246impl std::fmt::Debug<|> for Foo {
247}
248 ",
249 r"
250use std::fmt::Debug;
251
252impl Debug for Foo {
253}
254 ",
255 );
256 }
257
258 #[test]
259 fn test_replace_add_use_other_anchor_indent() {
260 check_assist(
261 replace_qualified_name_with_use,
262 r"
263 impl std::fmt::Debug<|> for Foo {
264 }
265 ",
266 r"
267 use std::fmt::Debug;
268
269 impl Debug for Foo {
270 }
271 ",
272 );
273 }
274
275 #[test]
276 fn test_replace_split_different() {
277 check_assist(
278 replace_qualified_name_with_use,
279 r"
280use std::fmt;
281
282impl std::io<|> for Foo {
283}
284 ",
285 r"
286use std::{io, fmt};
287
288impl io for Foo {
289}
290 ",
291 );
292 }
293
294 #[test]
295 fn test_replace_split_self_for_use() {
296 check_assist(
297 replace_qualified_name_with_use,
298 r"
299use std::fmt;
300
301impl std::fmt::Debug<|> for Foo {
302}
303 ",
304 r"
305use std::fmt::{self, Debug, };
306
307impl Debug for Foo {
308}
309 ",
310 );
311 }
312
313 #[test]
314 fn test_replace_split_self_for_target() {
315 check_assist(
316 replace_qualified_name_with_use,
317 r"
318use std::fmt::Debug;
319
320impl std::fmt<|> for Foo {
321}
322 ",
323 r"
324use std::fmt::{self, Debug};
325
326impl fmt for Foo {
327}
328 ",
329 );
330 }
331
332 #[test]
333 fn test_replace_add_to_nested_self_nested() {
334 check_assist(
335 replace_qualified_name_with_use,
336 r"
337use std::fmt::{Debug, nested::{Display}};
338
339impl std::fmt::nested<|> for Foo {
340}
341",
342 r"
343use std::fmt::{Debug, nested::{Display, self}};
344
345impl nested for Foo {
346}
347",
348 );
349 }
350
351 #[test]
352 fn test_replace_add_to_nested_self_already_included() {
353 check_assist(
354 replace_qualified_name_with_use,
355 r"
356use std::fmt::{Debug, nested::{self, Display}};
357
358impl std::fmt::nested<|> for Foo {
359}
360",
361 r"
362use std::fmt::{Debug, nested::{self, Display}};
363
364impl nested for Foo {
365}
366",
367 );
368 }
369
370 #[test]
371 fn test_replace_add_to_nested_nested() {
372 check_assist(
373 replace_qualified_name_with_use,
374 r"
375use std::fmt::{Debug, nested::{Display}};
376
377impl std::fmt::nested::Debug<|> for Foo {
378}
379",
380 r"
381use std::fmt::{Debug, nested::{Display, Debug}};
382
383impl Debug for Foo {
384}
385",
386 );
387 }
388
389 #[test]
390 fn test_replace_split_common_target_longer() {
391 check_assist(
392 replace_qualified_name_with_use,
393 r"
394use std::fmt::Debug;
395
396impl std::fmt::nested::Display<|> for Foo {
397}
398",
399 r"
400use std::fmt::{nested::Display, Debug};
401
402impl Display for Foo {
403}
404",
405 );
406 }
407
408 #[test]
409 fn test_replace_split_common_use_longer() {
410 check_assist(
411 replace_qualified_name_with_use,
412 r"
413use std::fmt::nested::Debug;
414
415impl std::fmt::Display<|> for Foo {
416}
417",
418 r"
419use std::fmt::{Display, nested::Debug};
420
421impl Display for Foo {
422}
423",
424 );
425 }
426
427 #[test]
428 fn test_replace_use_nested_import() {
429 check_assist(
430 replace_qualified_name_with_use,
431 r"
432use crate::{
433 ty::{Substs, Ty},
434 AssocItem,
435};
436
437fn foo() { crate::ty::lower<|>::trait_env() }
438",
439 r"
440use crate::{
441 ty::{Substs, Ty, lower},
442 AssocItem,
443};
444
445fn foo() { lower::trait_env() }
446",
447 );
448 }
449
450 #[test]
451 fn test_replace_alias() {
452 check_assist(
453 replace_qualified_name_with_use,
454 r"
455use std::fmt as foo;
456
457impl foo::Debug<|> for Foo {
458}
459",
460 r"
461use std::fmt as foo;
462
463impl Debug for Foo {
464}
465",
466 );
467 }
468
469 #[test]
470 fn test_replace_not_applicable_one_segment() {
471 check_assist_not_applicable(
472 replace_qualified_name_with_use,
473 r"
474impl foo<|> for Foo {
475}
476",
477 );
478 }
479
480 #[test]
481 fn test_replace_not_applicable_in_use() {
482 check_assist_not_applicable(
483 replace_qualified_name_with_use,
484 r"
485use std::fmt<|>;
486",
487 );
488 }
489
490 #[test]
491 fn test_replace_add_use_no_anchor_in_mod_mod() {
492 check_assist(
493 replace_qualified_name_with_use,
494 r"
495mod foo {
496 mod bar {
497 std::fmt::Debug<|>
498 }
499}
500 ",
501 r"
502mod foo {
503 mod bar {
504 use std::fmt::Debug;
505
506 Debug
507 }
508}
509 ",
510 );
511 }
512
513 #[test]
514 fn inserts_imports_after_inner_attributes() {
515 check_assist(
516 replace_qualified_name_with_use,
517 r"
518#![allow(dead_code)]
519
520fn main() {
521 std::fmt::Debug<|>
522}
523 ",
524 r"
525#![allow(dead_code)]
526use std::fmt::Debug;
527
528fn main() {
529 Debug
530}
531 ",
532 );
533 }
534
535 #[test]
536 fn replaces_all_affected_paths() {
537 check_assist(
538 replace_qualified_name_with_use,
539 r"
540fn main() {
541 std::fmt::Debug<|>;
542 let x: std::fmt::Debug = std::fmt::Debug;
543}
544 ",
545 r"
546use std::fmt::Debug;
547
548fn main() {
549 Debug;
550 let x: Debug = Debug;
551}
552 ",
553 );
554 }
555
556 #[test]
557 fn replaces_all_affected_paths_mod() {
558 check_assist(
559 replace_qualified_name_with_use,
560 r"
561mod m {
562 fn f() {
563 std::fmt::Debug<|>;
564 let x: std::fmt::Debug = std::fmt::Debug;
565 }
566 fn g() {
567 std::fmt::Debug;
568 }
569}
570
571fn f() {
572 std::fmt::Debug;
573}
574 ",
575 r"
576mod m {
577 use std::fmt::Debug;
578
579 fn f() {
580 Debug;
581 let x: Debug = Debug;
582 }
583 fn g() {
584 Debug;
585 }
586}
587
588fn f() {
589 std::fmt::Debug;
590}
591 ",
592 );
593 }
594
595 #[test]
596 fn does_not_replace_in_submodules() {
597 check_assist(
598 replace_qualified_name_with_use,
599 r"
600fn main() {
601 std::fmt::Debug<|>;
602}
603
604mod sub {
605 fn f() {
606 std::fmt::Debug;
607 }
608}
609 ",
610 r"
611use std::fmt::Debug;
612
613fn main() {
614 Debug;
615}
616
617mod sub {
618 fn f() {
619 std::fmt::Debug;
620 }
621}
622 ",
623 );
624 }
625
626 #[test]
627 fn does_not_replace_in_use() {
628 check_assist(
629 replace_qualified_name_with_use,
630 r"
631use std::fmt::Display;
632
633fn main() {
634 std::fmt<|>;
635}
636 ",
637 r"
638use std::fmt::{self, Display};
639
640fn main() {
641 fmt;
642}
643 ",
644 );
645 }
646
647 #[test]
648 fn does_not_replace_pub_use() {
649 check_assist(
650 replace_qualified_name_with_use,
651 r"
652pub use std::fmt;
653
654impl std::io<|> for Foo {
655}
656 ",
657 r"
658use std::io;
659
660pub use std::fmt;
661
662impl io for Foo {
663}
664 ",
665 );
666 }
667
668 #[test]
669 fn does_not_replace_pub_crate_use() {
670 check_assist(
671 replace_qualified_name_with_use,
672 r"
673pub(crate) use std::fmt;
674
675impl std::io<|> for Foo {
676}
677 ",
678 r"
679use std::io;
680
681pub(crate) use std::fmt;
682
683impl io for Foo {
684}
685 ",
686 );
687 }
688}
diff --git a/crates/ra_assists/src/handlers/replace_unwrap_with_match.rs b/crates/ra_assists/src/handlers/replace_unwrap_with_match.rs
deleted file mode 100644
index 9705f11b7..000000000
--- a/crates/ra_assists/src/handlers/replace_unwrap_with_match.rs
+++ /dev/null
@@ -1,187 +0,0 @@
1use std::iter;
2
3use syntax::{
4 ast::{
5 self,
6 edit::{AstNodeEdit, IndentLevel},
7 make,
8 },
9 AstNode,
10};
11
12use crate::{
13 utils::{render_snippet, Cursor, TryEnum},
14 AssistContext, AssistId, AssistKind, Assists,
15};
16
17// Assist: replace_unwrap_with_match
18//
19// Replaces `unwrap` a `match` expression. Works for Result and Option.
20//
21// ```
22// enum Result<T, E> { Ok(T), Err(E) }
23// fn main() {
24// let x: Result<i32, i32> = Result::Ok(92);
25// let y = x.<|>unwrap();
26// }
27// ```
28// ->
29// ```
30// enum Result<T, E> { Ok(T), Err(E) }
31// fn main() {
32// let x: Result<i32, i32> = Result::Ok(92);
33// let y = match x {
34// Ok(a) => a,
35// $0_ => unreachable!(),
36// };
37// }
38// ```
39pub(crate) fn replace_unwrap_with_match(acc: &mut Assists, ctx: &AssistContext) -> Option<()> {
40 let method_call: ast::MethodCallExpr = ctx.find_node_at_offset()?;
41 let name = method_call.name_ref()?;
42 if name.text() != "unwrap" {
43 return None;
44 }
45 let caller = method_call.expr()?;
46 let ty = ctx.sema.type_of_expr(&caller)?;
47 let happy_variant = TryEnum::from_ty(&ctx.sema, &ty)?.happy_case();
48 let target = method_call.syntax().text_range();
49 acc.add(
50 AssistId("replace_unwrap_with_match", AssistKind::RefactorRewrite),
51 "Replace unwrap with match",
52 target,
53 |builder| {
54 let ok_path = make::path_unqualified(make::path_segment(make::name_ref(happy_variant)));
55 let it = make::ident_pat(make::name("a")).into();
56 let ok_tuple = make::tuple_struct_pat(ok_path, iter::once(it)).into();
57
58 let bind_path = make::path_unqualified(make::path_segment(make::name_ref("a")));
59 let ok_arm = make::match_arm(iter::once(ok_tuple), make::expr_path(bind_path));
60
61 let unreachable_call = make::expr_unreachable();
62 let err_arm =
63 make::match_arm(iter::once(make::wildcard_pat().into()), unreachable_call);
64
65 let match_arm_list = make::match_arm_list(vec![ok_arm, err_arm]);
66 let match_expr = make::expr_match(caller.clone(), match_arm_list)
67 .indent(IndentLevel::from_node(method_call.syntax()));
68
69 let range = method_call.syntax().text_range();
70 match ctx.config.snippet_cap {
71 Some(cap) => {
72 let err_arm = match_expr
73 .syntax()
74 .descendants()
75 .filter_map(ast::MatchArm::cast)
76 .last()
77 .unwrap();
78 let snippet =
79 render_snippet(cap, match_expr.syntax(), Cursor::Before(err_arm.syntax()));
80 builder.replace_snippet(cap, range, snippet)
81 }
82 None => builder.replace(range, match_expr.to_string()),
83 }
84 },
85 )
86}
87
88#[cfg(test)]
89mod tests {
90 use crate::tests::{check_assist, check_assist_target};
91
92 use super::*;
93
94 #[test]
95 fn test_replace_result_unwrap_with_match() {
96 check_assist(
97 replace_unwrap_with_match,
98 r"
99enum Result<T, E> { Ok(T), Err(E) }
100fn i<T>(a: T) -> T { a }
101fn main() {
102 let x: Result<i32, i32> = Result::Ok(92);
103 let y = i(x).<|>unwrap();
104}
105 ",
106 r"
107enum Result<T, E> { Ok(T), Err(E) }
108fn i<T>(a: T) -> T { a }
109fn main() {
110 let x: Result<i32, i32> = Result::Ok(92);
111 let y = match i(x) {
112 Ok(a) => a,
113 $0_ => unreachable!(),
114 };
115}
116 ",
117 )
118 }
119
120 #[test]
121 fn test_replace_option_unwrap_with_match() {
122 check_assist(
123 replace_unwrap_with_match,
124 r"
125enum Option<T> { Some(T), None }
126fn i<T>(a: T) -> T { a }
127fn main() {
128 let x = Option::Some(92);
129 let y = i(x).<|>unwrap();
130}
131 ",
132 r"
133enum Option<T> { Some(T), None }
134fn i<T>(a: T) -> T { a }
135fn main() {
136 let x = Option::Some(92);
137 let y = match i(x) {
138 Some(a) => a,
139 $0_ => unreachable!(),
140 };
141}
142 ",
143 );
144 }
145
146 #[test]
147 fn test_replace_result_unwrap_with_match_chaining() {
148 check_assist(
149 replace_unwrap_with_match,
150 r"
151enum Result<T, E> { Ok(T), Err(E) }
152fn i<T>(a: T) -> T { a }
153fn main() {
154 let x: Result<i32, i32> = Result::Ok(92);
155 let y = i(x).<|>unwrap().count_zeroes();
156}
157 ",
158 r"
159enum Result<T, E> { Ok(T), Err(E) }
160fn i<T>(a: T) -> T { a }
161fn main() {
162 let x: Result<i32, i32> = Result::Ok(92);
163 let y = match i(x) {
164 Ok(a) => a,
165 $0_ => unreachable!(),
166 }.count_zeroes();
167}
168 ",
169 )
170 }
171
172 #[test]
173 fn replace_unwrap_with_match_target() {
174 check_assist_target(
175 replace_unwrap_with_match,
176 r"
177enum Option<T> { Some(T), None }
178fn i<T>(a: T) -> T { a }
179fn main() {
180 let x = Option::Some(92);
181 let y = i(x).<|>unwrap();
182}
183 ",
184 r"i(x).unwrap()",
185 );
186 }
187}
diff --git a/crates/ra_assists/src/handlers/split_import.rs b/crates/ra_assists/src/handlers/split_import.rs
deleted file mode 100644
index 15e67eaa1..000000000
--- a/crates/ra_assists/src/handlers/split_import.rs
+++ /dev/null
@@ -1,79 +0,0 @@
1use std::iter::successors;
2
3use syntax::{ast, AstNode, T};
4
5use crate::{AssistContext, AssistId, AssistKind, Assists};
6
7// Assist: split_import
8//
9// Wraps the tail of import into braces.
10//
11// ```
12// use std::<|>collections::HashMap;
13// ```
14// ->
15// ```
16// use std::{collections::HashMap};
17// ```
18pub(crate) fn split_import(acc: &mut Assists, ctx: &AssistContext) -> Option<()> {
19 let colon_colon = ctx.find_token_at_offset(T![::])?;
20 let path = ast::Path::cast(colon_colon.parent())?.qualifier()?;
21 let top_path = successors(Some(path.clone()), |it| it.parent_path()).last()?;
22
23 let use_tree = top_path.syntax().ancestors().find_map(ast::UseTree::cast)?;
24
25 let new_tree = use_tree.split_prefix(&path);
26 if new_tree == use_tree {
27 return None;
28 }
29
30 let target = colon_colon.text_range();
31 acc.add(AssistId("split_import", AssistKind::RefactorRewrite), "Split import", target, |edit| {
32 edit.replace_ast(use_tree, new_tree);
33 })
34}
35
36#[cfg(test)]
37mod tests {
38 use crate::tests::{check_assist, check_assist_not_applicable, check_assist_target};
39
40 use super::*;
41
42 #[test]
43 fn test_split_import() {
44 check_assist(
45 split_import,
46 "use crate::<|>db::RootDatabase;",
47 "use crate::{db::RootDatabase};",
48 )
49 }
50
51 #[test]
52 fn split_import_works_with_trees() {
53 check_assist(
54 split_import,
55 "use crate:<|>:db::{RootDatabase, FileSymbol}",
56 "use crate::{db::{RootDatabase, FileSymbol}}",
57 )
58 }
59
60 #[test]
61 fn split_import_target() {
62 check_assist_target(split_import, "use crate::<|>db::{RootDatabase, FileSymbol}", "::");
63 }
64
65 #[test]
66 fn issue4044() {
67 check_assist_not_applicable(split_import, "use crate::<|>:::self;")
68 }
69
70 #[test]
71 fn test_empty_use() {
72 check_assist_not_applicable(
73 split_import,
74 r"
75use std::<|>
76fn main() {}",
77 );
78 }
79}
diff --git a/crates/ra_assists/src/handlers/unwrap_block.rs b/crates/ra_assists/src/handlers/unwrap_block.rs
deleted file mode 100644
index 3851aeb3e..000000000
--- a/crates/ra_assists/src/handlers/unwrap_block.rs
+++ /dev/null
@@ -1,517 +0,0 @@
1use syntax::{
2 ast::{
3 self,
4 edit::{AstNodeEdit, IndentLevel},
5 },
6 AstNode, TextRange, T,
7};
8
9use crate::{utils::unwrap_trivial_block, AssistContext, AssistId, AssistKind, Assists};
10
11// Assist: unwrap_block
12//
13// This assist removes if...else, for, while and loop control statements to just keep the body.
14//
15// ```
16// fn foo() {
17// if true {<|>
18// println!("foo");
19// }
20// }
21// ```
22// ->
23// ```
24// fn foo() {
25// println!("foo");
26// }
27// ```
28pub(crate) fn unwrap_block(acc: &mut Assists, ctx: &AssistContext) -> Option<()> {
29 let assist_id = AssistId("unwrap_block", AssistKind::RefactorRewrite);
30 let assist_label = "Unwrap block";
31
32 let l_curly_token = ctx.find_token_at_offset(T!['{'])?;
33 let mut block = ast::BlockExpr::cast(l_curly_token.parent())?;
34 let mut parent = block.syntax().parent()?;
35 if ast::MatchArm::can_cast(parent.kind()) {
36 parent = parent.ancestors().find(|it| ast::MatchExpr::can_cast(it.kind()))?
37 }
38
39 let parent = ast::Expr::cast(parent)?;
40
41 match parent.clone() {
42 ast::Expr::ForExpr(_) | ast::Expr::WhileExpr(_) | ast::Expr::LoopExpr(_) => (),
43 ast::Expr::MatchExpr(_) => block = block.dedent(IndentLevel(1)),
44 ast::Expr::IfExpr(if_expr) => {
45 let then_branch = if_expr.then_branch()?;
46 if then_branch == block {
47 if let Some(ancestor) = if_expr.syntax().parent().and_then(ast::IfExpr::cast) {
48 // For `else if` blocks
49 let ancestor_then_branch = ancestor.then_branch()?;
50
51 let target = then_branch.syntax().text_range();
52 return acc.add(assist_id, assist_label, target, |edit| {
53 let range_to_del_else_if = TextRange::new(
54 ancestor_then_branch.syntax().text_range().end(),
55 l_curly_token.text_range().start(),
56 );
57 let range_to_del_rest = TextRange::new(
58 then_branch.syntax().text_range().end(),
59 if_expr.syntax().text_range().end(),
60 );
61
62 edit.delete(range_to_del_rest);
63 edit.delete(range_to_del_else_if);
64 edit.replace(
65 target,
66 update_expr_string(then_branch.to_string(), &[' ', '{']),
67 );
68 });
69 }
70 } else {
71 let target = block.syntax().text_range();
72 return acc.add(assist_id, assist_label, target, |edit| {
73 let range_to_del = TextRange::new(
74 then_branch.syntax().text_range().end(),
75 l_curly_token.text_range().start(),
76 );
77
78 edit.delete(range_to_del);
79 edit.replace(target, update_expr_string(block.to_string(), &[' ', '{']));
80 });
81 }
82 }
83 _ => return None,
84 };
85
86 let unwrapped = unwrap_trivial_block(block);
87 let target = unwrapped.syntax().text_range();
88 acc.add(assist_id, assist_label, target, |builder| {
89 builder.replace(
90 parent.syntax().text_range(),
91 update_expr_string(unwrapped.to_string(), &[' ', '{', '\n']),
92 );
93 })
94}
95
96fn update_expr_string(expr_str: String, trim_start_pat: &[char]) -> String {
97 let expr_string = expr_str.trim_start_matches(trim_start_pat);
98 let mut expr_string_lines: Vec<&str> = expr_string.lines().collect();
99 expr_string_lines.pop(); // Delete last line
100
101 expr_string_lines
102 .into_iter()
103 .map(|line| line.replacen(" ", "", 1)) // Delete indentation
104 .collect::<Vec<String>>()
105 .join("\n")
106}
107
108#[cfg(test)]
109mod tests {
110 use crate::tests::{check_assist, check_assist_not_applicable};
111
112 use super::*;
113
114 #[test]
115 fn simple_if() {
116 check_assist(
117 unwrap_block,
118 r#"
119 fn main() {
120 bar();
121 if true {<|>
122 foo();
123
124 //comment
125 bar();
126 } else {
127 println!("bar");
128 }
129 }
130 "#,
131 r#"
132 fn main() {
133 bar();
134 foo();
135
136 //comment
137 bar();
138 }
139 "#,
140 );
141 }
142
143 #[test]
144 fn simple_if_else() {
145 check_assist(
146 unwrap_block,
147 r#"
148 fn main() {
149 bar();
150 if true {
151 foo();
152
153 //comment
154 bar();
155 } else {<|>
156 println!("bar");
157 }
158 }
159 "#,
160 r#"
161 fn main() {
162 bar();
163 if true {
164 foo();
165
166 //comment
167 bar();
168 }
169 println!("bar");
170 }
171 "#,
172 );
173 }
174
175 #[test]
176 fn simple_if_else_if() {
177 check_assist(
178 unwrap_block,
179 r#"
180 fn main() {
181 //bar();
182 if true {
183 println!("true");
184
185 //comment
186 //bar();
187 } else if false {<|>
188 println!("bar");
189 } else {
190 println!("foo");
191 }
192 }
193 "#,
194 r#"
195 fn main() {
196 //bar();
197 if true {
198 println!("true");
199
200 //comment
201 //bar();
202 }
203 println!("bar");
204 }
205 "#,
206 );
207 }
208
209 #[test]
210 fn simple_if_else_if_nested() {
211 check_assist(
212 unwrap_block,
213 r#"
214 fn main() {
215 //bar();
216 if true {
217 println!("true");
218
219 //comment
220 //bar();
221 } else if false {
222 println!("bar");
223 } else if true {<|>
224 println!("foo");
225 }
226 }
227 "#,
228 r#"
229 fn main() {
230 //bar();
231 if true {
232 println!("true");
233
234 //comment
235 //bar();
236 } else if false {
237 println!("bar");
238 }
239 println!("foo");
240 }
241 "#,
242 );
243 }
244
245 #[test]
246 fn simple_if_else_if_nested_else() {
247 check_assist(
248 unwrap_block,
249 r#"
250 fn main() {
251 //bar();
252 if true {
253 println!("true");
254
255 //comment
256 //bar();
257 } else if false {
258 println!("bar");
259 } else if true {
260 println!("foo");
261 } else {<|>
262 println!("else");
263 }
264 }
265 "#,
266 r#"
267 fn main() {
268 //bar();
269 if true {
270 println!("true");
271
272 //comment
273 //bar();
274 } else if false {
275 println!("bar");
276 } else if true {
277 println!("foo");
278 }
279 println!("else");
280 }
281 "#,
282 );
283 }
284
285 #[test]
286 fn simple_if_else_if_nested_middle() {
287 check_assist(
288 unwrap_block,
289 r#"
290 fn main() {
291 //bar();
292 if true {
293 println!("true");
294
295 //comment
296 //bar();
297 } else if false {
298 println!("bar");
299 } else if true {<|>
300 println!("foo");
301 } else {
302 println!("else");
303 }
304 }
305 "#,
306 r#"
307 fn main() {
308 //bar();
309 if true {
310 println!("true");
311
312 //comment
313 //bar();
314 } else if false {
315 println!("bar");
316 }
317 println!("foo");
318 }
319 "#,
320 );
321 }
322
323 #[test]
324 fn simple_if_bad_cursor_position() {
325 check_assist_not_applicable(
326 unwrap_block,
327 r#"
328 fn main() {
329 bar();<|>
330 if true {
331 foo();
332
333 //comment
334 bar();
335 } else {
336 println!("bar");
337 }
338 }
339 "#,
340 );
341 }
342
343 #[test]
344 fn simple_for() {
345 check_assist(
346 unwrap_block,
347 r#"
348 fn main() {
349 for i in 0..5 {<|>
350 if true {
351 foo();
352
353 //comment
354 bar();
355 } else {
356 println!("bar");
357 }
358 }
359 }
360 "#,
361 r#"
362 fn main() {
363 if true {
364 foo();
365
366 //comment
367 bar();
368 } else {
369 println!("bar");
370 }
371 }
372 "#,
373 );
374 }
375
376 #[test]
377 fn simple_if_in_for() {
378 check_assist(
379 unwrap_block,
380 r#"
381 fn main() {
382 for i in 0..5 {
383 if true {<|>
384 foo();
385
386 //comment
387 bar();
388 } else {
389 println!("bar");
390 }
391 }
392 }
393 "#,
394 r#"
395 fn main() {
396 for i in 0..5 {
397 foo();
398
399 //comment
400 bar();
401 }
402 }
403 "#,
404 );
405 }
406
407 #[test]
408 fn simple_loop() {
409 check_assist(
410 unwrap_block,
411 r#"
412 fn main() {
413 loop {<|>
414 if true {
415 foo();
416
417 //comment
418 bar();
419 } else {
420 println!("bar");
421 }
422 }
423 }
424 "#,
425 r#"
426 fn main() {
427 if true {
428 foo();
429
430 //comment
431 bar();
432 } else {
433 println!("bar");
434 }
435 }
436 "#,
437 );
438 }
439
440 #[test]
441 fn simple_while() {
442 check_assist(
443 unwrap_block,
444 r#"
445 fn main() {
446 while true {<|>
447 if true {
448 foo();
449
450 //comment
451 bar();
452 } else {
453 println!("bar");
454 }
455 }
456 }
457 "#,
458 r#"
459 fn main() {
460 if true {
461 foo();
462
463 //comment
464 bar();
465 } else {
466 println!("bar");
467 }
468 }
469 "#,
470 );
471 }
472
473 #[test]
474 fn unwrap_match_arm() {
475 check_assist(
476 unwrap_block,
477 r#"
478fn main() {
479 match rel_path {
480 Ok(rel_path) => {<|>
481 let rel_path = RelativePathBuf::from_path(rel_path).ok()?;
482 Some((*id, rel_path))
483 }
484 Err(_) => None,
485 }
486}
487"#,
488 r#"
489fn main() {
490 let rel_path = RelativePathBuf::from_path(rel_path).ok()?;
491 Some((*id, rel_path))
492}
493"#,
494 );
495 }
496
497 #[test]
498 fn simple_if_in_while_bad_cursor_position() {
499 check_assist_not_applicable(
500 unwrap_block,
501 r#"
502 fn main() {
503 while true {
504 if true {
505 foo();<|>
506
507 //comment
508 bar();
509 } else {
510 println!("bar");
511 }
512 }
513 }
514 "#,
515 );
516 }
517}