aboutsummaryrefslogtreecommitdiff
path: root/crates/ra_assists
diff options
context:
space:
mode:
Diffstat (limited to 'crates/ra_assists')
-rw-r--r--crates/ra_assists/src/handlers/add_from_impl_for_enum.rs4
-rw-r--r--crates/ra_assists/src/handlers/introduce_named_lifetime.rs303
-rw-r--r--crates/ra_assists/src/handlers/reorder_fields.rs2
-rw-r--r--crates/ra_assists/src/lib.rs2
-rw-r--r--crates/ra_assists/src/tests/generated.rs44
5 files changed, 352 insertions, 3 deletions
diff --git a/crates/ra_assists/src/handlers/add_from_impl_for_enum.rs b/crates/ra_assists/src/handlers/add_from_impl_for_enum.rs
index 6a675e812..776bddf91 100644
--- a/crates/ra_assists/src/handlers/add_from_impl_for_enum.rs
+++ b/crates/ra_assists/src/handlers/add_from_impl_for_enum.rs
@@ -4,9 +4,9 @@ use test_utils::mark;
4 4
5use crate::{utils::FamousDefs, AssistContext, AssistId, Assists}; 5use crate::{utils::FamousDefs, AssistContext, AssistId, Assists};
6 6
7// Assist add_from_impl_for_enum 7// Assist: add_from_impl_for_enum
8// 8//
9// Adds a From impl for an enum variant with one tuple field 9// Adds a From impl for an enum variant with one tuple field.
10// 10//
11// ``` 11// ```
12// enum A { <|>One(u32) } 12// enum A { <|>One(u32) }
diff --git a/crates/ra_assists/src/handlers/introduce_named_lifetime.rs b/crates/ra_assists/src/handlers/introduce_named_lifetime.rs
new file mode 100644
index 000000000..beb5b7366
--- /dev/null
+++ b/crates/ra_assists/src/handlers/introduce_named_lifetime.rs
@@ -0,0 +1,303 @@
1use ra_syntax::{
2 ast::{self, NameOwner, TypeAscriptionOwner, TypeParamsOwner},
3 AstNode, SyntaxKind, TextRange, TextSize,
4};
5use rustc_hash::FxHashSet;
6
7use crate::{assist_context::AssistBuilder, AssistContext, AssistId, 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::FnDef::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::ImplDef::cast) {
44 // only allow naming the last anonymous lifetime
45 lifetime_token.next_token().filter(|tok| tok.kind() == SyntaxKind::R_ANGLE)?;
46 generate_impl_def_assist(acc, &impl_def, lifetime_token.text_range())
47 } else {
48 None
49 }
50}
51
52/// Generate the assist for the fn def case
53fn generate_fn_def_assist(
54 acc: &mut Assists,
55 fn_def: &ast::FnDef,
56 lifetime_loc: TextRange,
57) -> Option<()> {
58 let param_list: ast::ParamList = fn_def.param_list()?;
59 let new_lifetime_param = generate_unique_lifetime_param_name(&fn_def.type_param_list())?;
60 let end_of_fn_ident = fn_def.name()?.ident_token()?.text_range().end();
61 let self_param =
62 // use the self if it's a reference and has no explicit lifetime
63 param_list.self_param().filter(|p| p.lifetime_token().is_none() && p.amp_token().is_some());
64 // compute the location which implicitly has the same lifetime as the anonymous lifetime
65 let loc_needing_lifetime = if let Some(self_param) = self_param {
66 // if we have a self reference, use that
67 Some(self_param.self_token()?.text_range().start())
68 } else {
69 // otherwise, if there's a single reference parameter without a named liftime, use that
70 let fn_params_without_lifetime: Vec<_> = param_list
71 .params()
72 .filter_map(|param| match param.ascribed_type() {
73 Some(ast::TypeRef::ReferenceType(ascribed_type))
74 if ascribed_type.lifetime_token() == None =>
75 {
76 Some(ascribed_type.amp_token()?.text_range().end())
77 }
78 _ => None,
79 })
80 .collect();
81 match fn_params_without_lifetime.len() {
82 1 => Some(fn_params_without_lifetime.into_iter().nth(0)?),
83 0 => None,
84 // multiple unnnamed is invalid. assist is not applicable
85 _ => return None,
86 }
87 };
88 acc.add(AssistId(ASSIST_NAME), ASSIST_LABEL, lifetime_loc, |builder| {
89 add_lifetime_param(fn_def, builder, end_of_fn_ident, new_lifetime_param);
90 builder.replace(lifetime_loc, format!("'{}", new_lifetime_param));
91 loc_needing_lifetime.map(|loc| builder.insert(loc, format!("'{} ", new_lifetime_param)));
92 })
93}
94
95/// Generate the assist for the impl def case
96fn generate_impl_def_assist(
97 acc: &mut Assists,
98 impl_def: &ast::ImplDef,
99 lifetime_loc: TextRange,
100) -> Option<()> {
101 let new_lifetime_param = generate_unique_lifetime_param_name(&impl_def.type_param_list())?;
102 let end_of_impl_kw = impl_def.impl_token()?.text_range().end();
103 acc.add(AssistId(ASSIST_NAME), ASSIST_LABEL, lifetime_loc, |builder| {
104 add_lifetime_param(impl_def, builder, end_of_impl_kw, new_lifetime_param);
105 builder.replace(lifetime_loc, format!("'{}", new_lifetime_param));
106 })
107}
108
109/// Given a type parameter list, generate a unique lifetime parameter name
110/// which is not in the list
111fn generate_unique_lifetime_param_name(
112 existing_type_param_list: &Option<ast::TypeParamList>,
113) -> Option<char> {
114 match existing_type_param_list {
115 Some(type_params) => {
116 let used_lifetime_params: FxHashSet<_> = type_params
117 .lifetime_params()
118 .map(|p| p.syntax().text().to_string()[1..].to_owned())
119 .collect();
120 (b'a'..=b'z').map(char::from).find(|c| !used_lifetime_params.contains(&c.to_string()))
121 }
122 None => Some('a'),
123 }
124}
125
126/// Add the lifetime param to `builder`. If there are type parameters in `type_params_owner`, add it to the end. Otherwise
127/// add new type params brackets with the lifetime parameter at `new_type_params_loc`.
128fn add_lifetime_param<TypeParamsOwner: ast::TypeParamsOwner>(
129 type_params_owner: &TypeParamsOwner,
130 builder: &mut AssistBuilder,
131 new_type_params_loc: TextSize,
132 new_lifetime_param: char,
133) {
134 match type_params_owner.type_param_list() {
135 // add the new lifetime parameter to an existing type param list
136 Some(type_params) => {
137 builder.insert(
138 (u32::from(type_params.syntax().text_range().end()) - 1).into(),
139 format!(", '{}", new_lifetime_param),
140 );
141 }
142 // create a new type param list containing only the new lifetime parameter
143 None => {
144 builder.insert(new_type_params_loc, format!("<'{}>", new_lifetime_param));
145 }
146 }
147}
148
149#[cfg(test)]
150mod tests {
151 use super::*;
152 use crate::tests::{check_assist, check_assist_not_applicable};
153
154 #[test]
155 fn test_example_case() {
156 check_assist(
157 introduce_named_lifetime,
158 r#"impl Cursor<'_<|>> {
159 fn node(self) -> &SyntaxNode {
160 match self {
161 Cursor::Replace(node) | Cursor::Before(node) => node,
162 }
163 }
164 }"#,
165 r#"impl<'a> Cursor<'a> {
166 fn node(self) -> &SyntaxNode {
167 match self {
168 Cursor::Replace(node) | Cursor::Before(node) => node,
169 }
170 }
171 }"#,
172 );
173 }
174
175 #[test]
176 fn test_example_case_simplified() {
177 check_assist(
178 introduce_named_lifetime,
179 r#"impl Cursor<'_<|>> {"#,
180 r#"impl<'a> Cursor<'a> {"#,
181 );
182 }
183
184 #[test]
185 fn test_example_case_cursor_after_tick() {
186 check_assist(
187 introduce_named_lifetime,
188 r#"impl Cursor<'<|>_> {"#,
189 r#"impl<'a> Cursor<'a> {"#,
190 );
191 }
192
193 #[test]
194 fn test_example_case_cursor_before_tick() {
195 check_assist(
196 introduce_named_lifetime,
197 r#"impl Cursor<<|>'_> {"#,
198 r#"impl<'a> Cursor<'a> {"#,
199 );
200 }
201
202 #[test]
203 fn test_not_applicable_cursor_position() {
204 check_assist_not_applicable(introduce_named_lifetime, r#"impl Cursor<'_><|> {"#);
205 check_assist_not_applicable(introduce_named_lifetime, r#"impl Cursor<|><'_> {"#);
206 }
207
208 #[test]
209 fn test_not_applicable_lifetime_already_name() {
210 check_assist_not_applicable(introduce_named_lifetime, r#"impl Cursor<'a<|>> {"#);
211 check_assist_not_applicable(introduce_named_lifetime, r#"fn my_fun<'a>() -> X<'a<|>>"#);
212 }
213
214 #[test]
215 fn test_with_type_parameter() {
216 check_assist(
217 introduce_named_lifetime,
218 r#"impl<T> Cursor<T, '_<|>>"#,
219 r#"impl<T, 'a> Cursor<T, 'a>"#,
220 );
221 }
222
223 #[test]
224 fn test_with_existing_lifetime_name_conflict() {
225 check_assist(
226 introduce_named_lifetime,
227 r#"impl<'a, 'b> Cursor<'a, 'b, '_<|>>"#,
228 r#"impl<'a, 'b, 'c> Cursor<'a, 'b, 'c>"#,
229 );
230 }
231
232 #[test]
233 fn test_function_return_value_anon_lifetime_param() {
234 check_assist(
235 introduce_named_lifetime,
236 r#"fn my_fun() -> X<'_<|>>"#,
237 r#"fn my_fun<'a>() -> X<'a>"#,
238 );
239 }
240
241 #[test]
242 fn test_function_return_value_anon_reference_lifetime() {
243 check_assist(
244 introduce_named_lifetime,
245 r#"fn my_fun() -> &'_<|> X"#,
246 r#"fn my_fun<'a>() -> &'a X"#,
247 );
248 }
249
250 #[test]
251 fn test_function_param_anon_lifetime() {
252 check_assist(
253 introduce_named_lifetime,
254 r#"fn my_fun(x: X<'_<|>>)"#,
255 r#"fn my_fun<'a>(x: X<'a>)"#,
256 );
257 }
258
259 #[test]
260 fn test_function_add_lifetime_to_params() {
261 check_assist(
262 introduce_named_lifetime,
263 r#"fn my_fun(f: &Foo) -> X<'_<|>>"#,
264 r#"fn my_fun<'a>(f: &'a Foo) -> X<'a>"#,
265 );
266 }
267
268 #[test]
269 fn test_function_add_lifetime_to_params_in_presence_of_other_lifetime() {
270 check_assist(
271 introduce_named_lifetime,
272 r#"fn my_fun<'other>(f: &Foo, b: &'other Bar) -> X<'_<|>>"#,
273 r#"fn my_fun<'other, 'a>(f: &'a Foo, b: &'other Bar) -> X<'a>"#,
274 );
275 }
276
277 #[test]
278 fn test_function_not_applicable_without_self_and_multiple_unnamed_param_lifetimes() {
279 // this is not permitted under lifetime elision rules
280 check_assist_not_applicable(
281 introduce_named_lifetime,
282 r#"fn my_fun(f: &Foo, b: &Bar) -> X<'_<|>>"#,
283 );
284 }
285
286 #[test]
287 fn test_function_add_lifetime_to_self_ref_param() {
288 check_assist(
289 introduce_named_lifetime,
290 r#"fn my_fun<'other>(&self, f: &Foo, b: &'other Bar) -> X<'_<|>>"#,
291 r#"fn my_fun<'other, 'a>(&'a self, f: &Foo, b: &'other Bar) -> X<'a>"#,
292 );
293 }
294
295 #[test]
296 fn test_function_add_lifetime_to_param_with_non_ref_self() {
297 check_assist(
298 introduce_named_lifetime,
299 r#"fn my_fun<'other>(self, f: &Foo, b: &'other Bar) -> X<'_<|>>"#,
300 r#"fn my_fun<'other, 'a>(self, f: &'a Foo, b: &'other Bar) -> X<'a>"#,
301 );
302 }
303}
diff --git a/crates/ra_assists/src/handlers/reorder_fields.rs b/crates/ra_assists/src/handlers/reorder_fields.rs
index 30229edc2..897da2832 100644
--- a/crates/ra_assists/src/handlers/reorder_fields.rs
+++ b/crates/ra_assists/src/handlers/reorder_fields.rs
@@ -23,7 +23,7 @@ use crate::{AssistContext, AssistId, Assists};
23// ``` 23// ```
24// 24//
25pub(crate) fn reorder_fields(acc: &mut Assists, ctx: &AssistContext) -> Option<()> { 25pub(crate) fn reorder_fields(acc: &mut Assists, ctx: &AssistContext) -> Option<()> {
26 reorder::<ast::RecordLit>(acc, ctx.clone()).or_else(|| reorder::<ast::RecordPat>(acc, ctx)) 26 reorder::<ast::RecordLit>(acc, ctx).or_else(|| reorder::<ast::RecordPat>(acc, ctx))
27} 27}
28 28
29fn reorder<R: AstNode>(acc: &mut Assists, ctx: &AssistContext) -> Option<()> { 29fn reorder<R: AstNode>(acc: &mut Assists, ctx: &AssistContext) -> Option<()> {
diff --git a/crates/ra_assists/src/lib.rs b/crates/ra_assists/src/lib.rs
index 9933f7a50..88ce9b62e 100644
--- a/crates/ra_assists/src/lib.rs
+++ b/crates/ra_assists/src/lib.rs
@@ -122,6 +122,7 @@ mod handlers {
122 mod flip_comma; 122 mod flip_comma;
123 mod flip_trait_bound; 123 mod flip_trait_bound;
124 mod inline_local_variable; 124 mod inline_local_variable;
125 mod introduce_named_lifetime;
125 mod introduce_variable; 126 mod introduce_variable;
126 mod invert_if; 127 mod invert_if;
127 mod merge_imports; 128 mod merge_imports;
@@ -162,6 +163,7 @@ mod handlers {
162 flip_comma::flip_comma, 163 flip_comma::flip_comma,
163 flip_trait_bound::flip_trait_bound, 164 flip_trait_bound::flip_trait_bound,
164 inline_local_variable::inline_local_variable, 165 inline_local_variable::inline_local_variable,
166 introduce_named_lifetime::introduce_named_lifetime,
165 introduce_variable::introduce_variable, 167 introduce_variable::introduce_variable,
166 invert_if::invert_if, 168 invert_if::invert_if,
167 merge_imports::merge_imports, 169 merge_imports::merge_imports,
diff --git a/crates/ra_assists/src/tests/generated.rs b/crates/ra_assists/src/tests/generated.rs
index 250e56a69..d17504529 100644
--- a/crates/ra_assists/src/tests/generated.rs
+++ b/crates/ra_assists/src/tests/generated.rs
@@ -59,6 +59,25 @@ fn main() {
59} 59}
60 60
61#[test] 61#[test]
62fn doctest_add_from_impl_for_enum() {
63 check_doc_test(
64 "add_from_impl_for_enum",
65 r#####"
66enum A { <|>One(u32) }
67"#####,
68 r#####"
69enum A { One(u32) }
70
71impl From<u32> for A {
72 fn from(v: u32) -> Self {
73 A::One(v)
74 }
75}
76"#####,
77 )
78}
79
80#[test]
62fn doctest_add_function() { 81fn doctest_add_function() {
63 check_doc_test( 82 check_doc_test(
64 "add_function", 83 "add_function",
@@ -433,6 +452,31 @@ fn main() {
433} 452}
434 453
435#[test] 454#[test]
455fn doctest_introduce_named_lifetime() {
456 check_doc_test(
457 "introduce_named_lifetime",
458 r#####"
459impl Cursor<'_<|>> {
460 fn node(self) -> &SyntaxNode {
461 match self {
462 Cursor::Replace(node) | Cursor::Before(node) => node,
463 }
464 }
465}
466"#####,
467 r#####"
468impl<'a> Cursor<'a> {
469 fn node(self) -> &SyntaxNode {
470 match self {
471 Cursor::Replace(node) | Cursor::Before(node) => node,
472 }
473 }
474}
475"#####,
476 )
477}
478
479#[test]
436fn doctest_introduce_variable() { 480fn doctest_introduce_variable() {
437 check_doc_test( 481 check_doc_test(
438 "introduce_variable", 482 "introduce_variable",