aboutsummaryrefslogtreecommitdiff
path: root/crates/ra_assists/src/handlers/change_lifetime_anon_to_named.rs
diff options
context:
space:
mode:
authorAleksey Kladov <[email protected]>2020-06-01 14:36:51 +0100
committerAleksey Kladov <[email protected]>2020-06-01 14:41:16 +0100
commit285717de33c25422db60420030d46d10cf3b0121 (patch)
treed757ba7d5afc93ae3f0a22fbd0cc401f52e067b9 /crates/ra_assists/src/handlers/change_lifetime_anon_to_named.rs
parentd08232b10d7085e1f5be96b87cca880f6ee56c9e (diff)
Rename assist
Diffstat (limited to 'crates/ra_assists/src/handlers/change_lifetime_anon_to_named.rs')
-rw-r--r--crates/ra_assists/src/handlers/change_lifetime_anon_to_named.rs306
1 files changed, 0 insertions, 306 deletions
diff --git a/crates/ra_assists/src/handlers/change_lifetime_anon_to_named.rs b/crates/ra_assists/src/handlers/change_lifetime_anon_to_named.rs
deleted file mode 100644
index 0fdbc63dd..000000000
--- a/crates/ra_assists/src/handlers/change_lifetime_anon_to_named.rs
+++ /dev/null
@@ -1,306 +0,0 @@
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 = "change_lifetime_anon_to_named";
10static ASSIST_LABEL: &str = "Give anonymous lifetime a name";
11
12// Assist: change_lifetime_anon_to_named
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 change_lifetime_anon_to_named(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 change_lifetime_anon_to_named,
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 change_lifetime_anon_to_named,
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 change_lifetime_anon_to_named,
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 change_lifetime_anon_to_named,
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(change_lifetime_anon_to_named, r#"impl Cursor<'_><|> {"#);
205 check_assist_not_applicable(change_lifetime_anon_to_named, r#"impl Cursor<|><'_> {"#);
206 }
207
208 #[test]
209 fn test_not_applicable_lifetime_already_name() {
210 check_assist_not_applicable(change_lifetime_anon_to_named, r#"impl Cursor<'a<|>> {"#);
211 check_assist_not_applicable(
212 change_lifetime_anon_to_named,
213 r#"fn my_fun<'a>() -> X<'a<|>>"#,
214 );
215 }
216
217 #[test]
218 fn test_with_type_parameter() {
219 check_assist(
220 change_lifetime_anon_to_named,
221 r#"impl<T> Cursor<T, '_<|>>"#,
222 r#"impl<T, 'a> Cursor<T, 'a>"#,
223 );
224 }
225
226 #[test]
227 fn test_with_existing_lifetime_name_conflict() {
228 check_assist(
229 change_lifetime_anon_to_named,
230 r#"impl<'a, 'b> Cursor<'a, 'b, '_<|>>"#,
231 r#"impl<'a, 'b, 'c> Cursor<'a, 'b, 'c>"#,
232 );
233 }
234
235 #[test]
236 fn test_function_return_value_anon_lifetime_param() {
237 check_assist(
238 change_lifetime_anon_to_named,
239 r#"fn my_fun() -> X<'_<|>>"#,
240 r#"fn my_fun<'a>() -> X<'a>"#,
241 );
242 }
243
244 #[test]
245 fn test_function_return_value_anon_reference_lifetime() {
246 check_assist(
247 change_lifetime_anon_to_named,
248 r#"fn my_fun() -> &'_<|> X"#,
249 r#"fn my_fun<'a>() -> &'a X"#,
250 );
251 }
252
253 #[test]
254 fn test_function_param_anon_lifetime() {
255 check_assist(
256 change_lifetime_anon_to_named,
257 r#"fn my_fun(x: X<'_<|>>)"#,
258 r#"fn my_fun<'a>(x: X<'a>)"#,
259 );
260 }
261
262 #[test]
263 fn test_function_add_lifetime_to_params() {
264 check_assist(
265 change_lifetime_anon_to_named,
266 r#"fn my_fun(f: &Foo) -> X<'_<|>>"#,
267 r#"fn my_fun<'a>(f: &'a Foo) -> X<'a>"#,
268 );
269 }
270
271 #[test]
272 fn test_function_add_lifetime_to_params_in_presence_of_other_lifetime() {
273 check_assist(
274 change_lifetime_anon_to_named,
275 r#"fn my_fun<'other>(f: &Foo, b: &'other Bar) -> X<'_<|>>"#,
276 r#"fn my_fun<'other, 'a>(f: &'a Foo, b: &'other Bar) -> X<'a>"#,
277 );
278 }
279
280 #[test]
281 fn test_function_not_applicable_without_self_and_multiple_unnamed_param_lifetimes() {
282 // this is not permitted under lifetime elision rules
283 check_assist_not_applicable(
284 change_lifetime_anon_to_named,
285 r#"fn my_fun(f: &Foo, b: &Bar) -> X<'_<|>>"#,
286 );
287 }
288
289 #[test]
290 fn test_function_add_lifetime_to_self_ref_param() {
291 check_assist(
292 change_lifetime_anon_to_named,
293 r#"fn my_fun<'other>(&self, f: &Foo, b: &'other Bar) -> X<'_<|>>"#,
294 r#"fn my_fun<'other, 'a>(&'a self, f: &Foo, b: &'other Bar) -> X<'a>"#,
295 );
296 }
297
298 #[test]
299 fn test_function_add_lifetime_to_param_with_non_ref_self() {
300 check_assist(
301 change_lifetime_anon_to_named,
302 r#"fn my_fun<'other>(self, f: &Foo, b: &'other Bar) -> X<'_<|>>"#,
303 r#"fn my_fun<'other, 'a>(self, f: &'a Foo, b: &'other Bar) -> X<'a>"#,
304 );
305 }
306}