1 use rustc_hash::FxHashSet;
3 ast::{self, edit_in_place::GenericParamsOwnerEdit, make, GenericParamsOwner},
8 use crate::{assist_context::AssistBuilder, AssistContext, AssistId, AssistKind, Assists};
10 static ASSIST_NAME: &str = "introduce_named_lifetime";
11 static ASSIST_LABEL: &str = "Introduce named lifetime";
13 // Assist: introduce_named_lifetime
15 // Change an anonymous lifetime to a named lifetime.
18 // impl Cursor<'_$0> {
19 // fn node(self) -> &SyntaxNode {
21 // Cursor::Replace(node) | Cursor::Before(node) => node,
28 // impl<'a> Cursor<'a> {
29 // fn node(self) -> &SyntaxNode {
31 // Cursor::Replace(node) | Cursor::Before(node) => node,
36 // FIXME: How can we handle renaming any one of multiple anonymous lifetimes?
37 // FIXME: should also add support for the case fun(f: &Foo) -> &$0Foo
38 pub(crate) fn introduce_named_lifetime(acc: &mut Assists, ctx: &AssistContext) -> Option<()> {
40 ctx.find_node_at_offset::<ast::Lifetime>().filter(|lifetime| lifetime.text() == "'_")?;
41 let lifetime_loc = lifetime.lifetime_ident_token()?.text_range();
43 if let Some(fn_def) = lifetime.syntax().ancestors().find_map(ast::Fn::cast) {
44 generate_fn_def_assist(acc, fn_def, lifetime_loc, lifetime)
45 } else if let Some(impl_def) = lifetime.syntax().ancestors().find_map(ast::Impl::cast) {
46 generate_impl_def_assist(acc, impl_def, lifetime_loc, lifetime)
52 /// Generate the assist for the fn def case
53 fn generate_fn_def_assist(
56 lifetime_loc: TextRange,
57 lifetime: ast::Lifetime,
59 let param_list: ast::ParamList = fn_def.param_list()?;
60 let new_lifetime_param = generate_unique_lifetime_param_name(fn_def.generic_param_list())?;
62 // use the self if it's a reference and has no explicit lifetime
63 param_list.self_param().filter(|p| p.lifetime().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(NeedsLifetime::SelfParam(self_param))
69 // otherwise, if there's a single reference parameter without a named liftime, use that
70 let fn_params_without_lifetime: Vec<_> = param_list
72 .filter_map(|param| match param.ty() {
73 Some(ast::Type::RefType(ascribed_type)) if ascribed_type.lifetime().is_none() => {
74 Some(NeedsLifetime::RefType(ascribed_type))
79 match fn_params_without_lifetime.len() {
80 1 => Some(fn_params_without_lifetime.into_iter().nth(0)?),
82 // multiple unnnamed is invalid. assist is not applicable
86 acc.add(AssistId(ASSIST_NAME, AssistKind::Refactor), ASSIST_LABEL, lifetime_loc, |builder| {
87 let fn_def = builder.make_ast_mut(fn_def);
88 let lifetime = builder.make_ast_mut(lifetime);
89 let loc_needing_lifetime =
90 loc_needing_lifetime.and_then(|it| it.make_mut(builder).to_position());
92 add_lifetime_param(fn_def.get_or_create_generic_param_list(), new_lifetime_param);
95 make_ast_lifetime(new_lifetime_param).clone_for_update().syntax(),
97 loc_needing_lifetime.map(|position| {
98 ted::insert(position, make_ast_lifetime(new_lifetime_param).clone_for_update().syntax())
103 /// Generate the assist for the impl def case
104 fn generate_impl_def_assist(
107 lifetime_loc: TextRange,
108 lifetime: ast::Lifetime,
110 let new_lifetime_param = generate_unique_lifetime_param_name(impl_def.generic_param_list())?;
111 acc.add(AssistId(ASSIST_NAME, AssistKind::Refactor), ASSIST_LABEL, lifetime_loc, |builder| {
112 let impl_def = builder.make_ast_mut(impl_def);
113 let lifetime = builder.make_ast_mut(lifetime);
115 add_lifetime_param(impl_def.get_or_create_generic_param_list(), new_lifetime_param);
118 make_ast_lifetime(new_lifetime_param).clone_for_update().syntax(),
123 /// Given a type parameter list, generate a unique lifetime parameter name
124 /// which is not in the list
125 fn generate_unique_lifetime_param_name(
126 existing_type_param_list: Option<ast::GenericParamList>,
128 match existing_type_param_list {
129 Some(type_params) => {
130 let used_lifetime_params: FxHashSet<_> = type_params
132 .map(|p| p.syntax().text().to_string()[1..].to_owned())
134 (b'a'..=b'z').map(char::from).find(|c| !used_lifetime_params.contains(&c.to_string()))
140 fn add_lifetime_param(type_params: ast::GenericParamList, new_lifetime_param: char) {
142 make::generic_param(format!("'{}", new_lifetime_param), None).clone_for_update();
143 type_params.add_generic_param(generic_param);
146 fn make_ast_lifetime(new_lifetime_param: char) -> ast::Lifetime {
147 make::generic_param(format!("'{}", new_lifetime_param), None)
150 .find_map(ast::Lifetime::cast)
155 SelfParam(ast::SelfParam),
156 RefType(ast::RefType),
160 fn make_mut(self, builder: &mut AssistBuilder) -> Self {
162 Self::SelfParam(it) => Self::SelfParam(builder.make_ast_mut(it)),
163 Self::RefType(it) => Self::RefType(builder.make_ast_mut(it)),
167 fn to_position(self) -> Option<Position> {
169 Self::SelfParam(it) => Some(Position::after(it.amp_token()?)),
170 Self::RefType(it) => Some(Position::after(it.amp_token()?)),
178 use crate::tests::{check_assist, check_assist_not_applicable};
181 fn test_example_case() {
183 introduce_named_lifetime,
184 r#"impl Cursor<'_$0> {
185 fn node(self) -> &SyntaxNode {
187 Cursor::Replace(node) | Cursor::Before(node) => node,
191 r#"impl<'a> Cursor<'a> {
192 fn node(self) -> &SyntaxNode {
194 Cursor::Replace(node) | Cursor::Before(node) => node,
202 fn test_example_case_simplified() {
204 introduce_named_lifetime,
205 r#"impl Cursor<'_$0> {"#,
206 r#"impl<'a> Cursor<'a> {"#,
211 fn test_example_case_cursor_after_tick() {
213 introduce_named_lifetime,
214 r#"impl Cursor<'$0_> {"#,
215 r#"impl<'a> Cursor<'a> {"#,
220 fn test_impl_with_other_type_param() {
222 introduce_named_lifetime,
223 "impl<I> fmt::Display for SepByBuilder<'_$0, I>
226 I::Item: fmt::Display,
228 "impl<I, 'a> fmt::Display for SepByBuilder<'a, I>
231 I::Item: fmt::Display,
237 fn test_example_case_cursor_before_tick() {
239 introduce_named_lifetime,
240 r#"impl Cursor<$0'_> {"#,
241 r#"impl<'a> Cursor<'a> {"#,
246 fn test_not_applicable_cursor_position() {
247 check_assist_not_applicable(introduce_named_lifetime, r#"impl Cursor<'_>$0 {"#);
248 check_assist_not_applicable(introduce_named_lifetime, r#"impl Cursor$0<'_> {"#);
252 fn test_not_applicable_lifetime_already_name() {
253 check_assist_not_applicable(introduce_named_lifetime, r#"impl Cursor<'a$0> {"#);
254 check_assist_not_applicable(introduce_named_lifetime, r#"fn my_fun<'a>() -> X<'a$0>"#);
258 fn test_with_type_parameter() {
260 introduce_named_lifetime,
261 r#"impl<T> Cursor<T, '_$0>"#,
262 r#"impl<T, 'a> Cursor<T, 'a>"#,
267 fn test_with_existing_lifetime_name_conflict() {
269 introduce_named_lifetime,
270 r#"impl<'a, 'b> Cursor<'a, 'b, '_$0>"#,
271 r#"impl<'a, 'b, 'c> Cursor<'a, 'b, 'c>"#,
276 fn test_function_return_value_anon_lifetime_param() {
278 introduce_named_lifetime,
279 r#"fn my_fun() -> X<'_$0>"#,
280 r#"fn my_fun<'a>() -> X<'a>"#,
285 fn test_function_return_value_anon_reference_lifetime() {
287 introduce_named_lifetime,
288 r#"fn my_fun() -> &'_$0 X"#,
289 r#"fn my_fun<'a>() -> &'a X"#,
294 fn test_function_param_anon_lifetime() {
296 introduce_named_lifetime,
297 r#"fn my_fun(x: X<'_$0>)"#,
298 r#"fn my_fun<'a>(x: X<'a>)"#,
303 fn test_function_add_lifetime_to_params() {
305 introduce_named_lifetime,
306 r#"fn my_fun(f: &Foo) -> X<'_$0>"#,
307 r#"fn my_fun<'a>(f: &'a Foo) -> X<'a>"#,
312 fn test_function_add_lifetime_to_params_in_presence_of_other_lifetime() {
314 introduce_named_lifetime,
315 r#"fn my_fun<'other>(f: &Foo, b: &'other Bar) -> X<'_$0>"#,
316 r#"fn my_fun<'other, 'a>(f: &'a Foo, b: &'other Bar) -> X<'a>"#,
321 fn test_function_not_applicable_without_self_and_multiple_unnamed_param_lifetimes() {
322 // this is not permitted under lifetime elision rules
323 check_assist_not_applicable(
324 introduce_named_lifetime,
325 r#"fn my_fun(f: &Foo, b: &Bar) -> X<'_$0>"#,
330 fn test_function_add_lifetime_to_self_ref_param() {
332 introduce_named_lifetime,
333 r#"fn my_fun<'other>(&self, f: &Foo, b: &'other Bar) -> X<'_$0>"#,
334 r#"fn my_fun<'other, 'a>(&'a self, f: &Foo, b: &'other Bar) -> X<'a>"#,
339 fn test_function_add_lifetime_to_param_with_non_ref_self() {
341 introduce_named_lifetime,
342 r#"fn my_fun<'other>(self, f: &Foo, b: &'other Bar) -> X<'_$0>"#,
343 r#"fn my_fun<'other, 'a>(self, f: &'a Foo, b: &'other Bar) -> X<'a>"#,
348 fn test_function_add_lifetime_to_self_ref_mut() {
350 introduce_named_lifetime,
351 r#"fn foo(&mut self) -> &'_$0 ()"#,
352 r#"fn foo<'a>(&'a mut self) -> &'a ()"#,