Skip to content

Commit 144afa5

Browse files
committed
Switch introduce_named_lifetime assist to use mutable syntax tree
1 parent 27e80e9 commit 144afa5

File tree

3 files changed

+147
-36
lines changed

3 files changed

+147
-36
lines changed

crates/ide_assists/src/handlers/introduce_named_lifetime.rs

Lines changed: 76 additions & 36 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,8 @@
11
use rustc_hash::FxHashSet;
22
use syntax::{
3-
ast::{self, GenericParamsOwner, NameOwner},
4-
AstNode, TextRange, TextSize,
3+
ast::{self, edit_in_place::GenericParamsOwnerEdit, make, GenericParamsOwner},
4+
ted::{self, Position},
5+
AstNode, TextRange,
56
};
67

78
use crate::{assist_context::AssistBuilder, AssistContext, AssistId, AssistKind, Assists};
@@ -37,10 +38,12 @@ static ASSIST_LABEL: &str = "Introduce named lifetime";
3738
pub(crate) fn introduce_named_lifetime(acc: &mut Assists, ctx: &AssistContext) -> Option<()> {
3839
let lifetime =
3940
ctx.find_node_at_offset::<ast::Lifetime>().filter(|lifetime| lifetime.text() == "'_")?;
41+
let lifetime_loc = lifetime.lifetime_ident_token()?.text_range();
42+
4043
if let Some(fn_def) = lifetime.syntax().ancestors().find_map(ast::Fn::cast) {
41-
generate_fn_def_assist(acc, &fn_def, lifetime.lifetime_ident_token()?.text_range())
44+
generate_fn_def_assist(acc, fn_def, lifetime_loc, lifetime)
4245
} else if let Some(impl_def) = lifetime.syntax().ancestors().find_map(ast::Impl::cast) {
43-
generate_impl_def_assist(acc, &impl_def, lifetime.lifetime_ident_token()?.text_range())
46+
generate_impl_def_assist(acc, impl_def, lifetime_loc, lifetime)
4447
} else {
4548
None
4649
}
@@ -49,26 +52,26 @@ pub(crate) fn introduce_named_lifetime(acc: &mut Assists, ctx: &AssistContext) -
4952
/// Generate the assist for the fn def case
5053
fn generate_fn_def_assist(
5154
acc: &mut Assists,
52-
fn_def: &ast::Fn,
55+
fn_def: ast::Fn,
5356
lifetime_loc: TextRange,
57+
lifetime: ast::Lifetime,
5458
) -> Option<()> {
5559
let param_list: ast::ParamList = fn_def.param_list()?;
56-
let new_lifetime_param = generate_unique_lifetime_param_name(&fn_def.generic_param_list())?;
57-
let end_of_fn_ident = fn_def.name()?.ident_token()?.text_range().end();
60+
let new_lifetime_param = generate_unique_lifetime_param_name(fn_def.generic_param_list())?;
5861
let self_param =
5962
// use the self if it's a reference and has no explicit lifetime
6063
param_list.self_param().filter(|p| p.lifetime().is_none() && p.amp_token().is_some());
6164
// compute the location which implicitly has the same lifetime as the anonymous lifetime
6265
let loc_needing_lifetime = if let Some(self_param) = self_param {
6366
// if we have a self reference, use that
64-
Some(self_param.name()?.syntax().text_range().start())
67+
Some(NeedsLifetime::SelfParam(self_param))
6568
} else {
6669
// otherwise, if there's a single reference parameter without a named liftime, use that
6770
let fn_params_without_lifetime: Vec<_> = param_list
6871
.params()
6972
.filter_map(|param| match param.ty() {
7073
Some(ast::Type::RefType(ascribed_type)) if ascribed_type.lifetime().is_none() => {
71-
Some(ascribed_type.amp_token()?.text_range().end())
74+
Some(NeedsLifetime::RefType(ascribed_type))
7275
}
7376
_ => None,
7477
})
@@ -81,30 +84,46 @@ fn generate_fn_def_assist(
8184
}
8285
};
8386
acc.add(AssistId(ASSIST_NAME, AssistKind::Refactor), ASSIST_LABEL, lifetime_loc, |builder| {
84-
add_lifetime_param(fn_def, builder, end_of_fn_ident, new_lifetime_param);
85-
builder.replace(lifetime_loc, format!("'{}", new_lifetime_param));
86-
loc_needing_lifetime.map(|loc| builder.insert(loc, format!("'{} ", new_lifetime_param)));
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());
91+
92+
add_lifetime_param(fn_def.get_or_create_generic_param_list(), new_lifetime_param);
93+
ted::replace(
94+
lifetime.syntax(),
95+
make_ast_lifetime(new_lifetime_param).clone_for_update().syntax(),
96+
);
97+
loc_needing_lifetime.map(|position| {
98+
ted::insert(position, make_ast_lifetime(new_lifetime_param).clone_for_update().syntax())
99+
});
87100
})
88101
}
89102

90103
/// Generate the assist for the impl def case
91104
fn generate_impl_def_assist(
92105
acc: &mut Assists,
93-
impl_def: &ast::Impl,
106+
impl_def: ast::Impl,
94107
lifetime_loc: TextRange,
108+
lifetime: ast::Lifetime,
95109
) -> Option<()> {
96-
let new_lifetime_param = generate_unique_lifetime_param_name(&impl_def.generic_param_list())?;
97-
let end_of_impl_kw = impl_def.impl_token()?.text_range().end();
110+
let new_lifetime_param = generate_unique_lifetime_param_name(impl_def.generic_param_list())?;
98111
acc.add(AssistId(ASSIST_NAME, AssistKind::Refactor), ASSIST_LABEL, lifetime_loc, |builder| {
99-
add_lifetime_param(impl_def, builder, end_of_impl_kw, new_lifetime_param);
100-
builder.replace(lifetime_loc, format!("'{}", new_lifetime_param));
112+
let impl_def = builder.make_ast_mut(impl_def);
113+
let lifetime = builder.make_ast_mut(lifetime);
114+
115+
add_lifetime_param(impl_def.get_or_create_generic_param_list(), new_lifetime_param);
116+
ted::replace(
117+
lifetime.syntax(),
118+
make_ast_lifetime(new_lifetime_param).clone_for_update().syntax(),
119+
);
101120
})
102121
}
103122

104123
/// Given a type parameter list, generate a unique lifetime parameter name
105124
/// which is not in the list
106125
fn generate_unique_lifetime_param_name(
107-
existing_type_param_list: &Option<ast::GenericParamList>,
126+
existing_type_param_list: Option<ast::GenericParamList>,
108127
) -> Option<char> {
109128
match existing_type_param_list {
110129
Some(type_params) => {
@@ -118,25 +137,37 @@ fn generate_unique_lifetime_param_name(
118137
}
119138
}
120139

121-
/// Add the lifetime param to `builder`. If there are type parameters in `type_params_owner`, add it to the end. Otherwise
122-
/// add new type params brackets with the lifetime parameter at `new_type_params_loc`.
123-
fn add_lifetime_param<TypeParamsOwner: ast::GenericParamsOwner>(
124-
type_params_owner: &TypeParamsOwner,
125-
builder: &mut AssistBuilder,
126-
new_type_params_loc: TextSize,
127-
new_lifetime_param: char,
128-
) {
129-
match type_params_owner.generic_param_list() {
130-
// add the new lifetime parameter to an existing type param list
131-
Some(type_params) => {
132-
builder.insert(
133-
(u32::from(type_params.syntax().text_range().end()) - 1).into(),
134-
format!(", '{}", new_lifetime_param),
135-
);
140+
fn add_lifetime_param(type_params: ast::GenericParamList, new_lifetime_param: char) {
141+
let generic_param =
142+
make::generic_param(format!("'{}", new_lifetime_param), None).clone_for_update();
143+
type_params.add_generic_param(generic_param);
144+
}
145+
146+
fn make_ast_lifetime(new_lifetime_param: char) -> ast::Lifetime {
147+
make::generic_param(format!("'{}", new_lifetime_param), None)
148+
.syntax()
149+
.descendants()
150+
.find_map(ast::Lifetime::cast)
151+
.unwrap()
152+
}
153+
154+
enum NeedsLifetime {
155+
SelfParam(ast::SelfParam),
156+
RefType(ast::RefType),
157+
}
158+
159+
impl NeedsLifetime {
160+
fn make_mut(self, builder: &mut AssistBuilder) -> Self {
161+
match self {
162+
Self::SelfParam(it) => Self::SelfParam(builder.make_ast_mut(it)),
163+
Self::RefType(it) => Self::RefType(builder.make_ast_mut(it)),
136164
}
137-
// create a new type param list containing only the new lifetime parameter
138-
None => {
139-
builder.insert(new_type_params_loc, format!("<'{}>", new_lifetime_param));
165+
}
166+
167+
fn to_position(self) -> Option<Position> {
168+
match self {
169+
Self::SelfParam(it) => Some(Position::after(it.amp_token()?)),
170+
Self::RefType(it) => Some(Position::after(it.amp_token()?)),
140171
}
141172
}
142173
}
@@ -312,4 +343,13 @@ mod tests {
312343
r#"fn my_fun<'other, 'a>(self, f: &'a Foo, b: &'other Bar) -> X<'a>"#,
313344
);
314345
}
346+
347+
#[test]
348+
fn test_function_add_lifetime_to_self_ref_mut() {
349+
check_assist(
350+
introduce_named_lifetime,
351+
r#"fn foo(&mut self) -> &'_$0 ()"#,
352+
r#"fn foo<'a>(&'a mut self) -> &'a ()"#,
353+
);
354+
}
315355
}

crates/syntax/src/ast/edit_in_place.rs

Lines changed: 64 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -14,10 +14,21 @@ use crate::{
1414
use super::NameOwner;
1515

1616
pub trait GenericParamsOwnerEdit: ast::GenericParamsOwner + AstNodeEdit {
17+
fn get_or_create_generic_param_list(&self) -> ast::GenericParamList;
1718
fn get_or_create_where_clause(&self) -> ast::WhereClause;
1819
}
1920

2021
impl GenericParamsOwnerEdit for ast::Fn {
22+
fn get_or_create_generic_param_list(&self) -> ast::GenericParamList {
23+
match self.generic_param_list() {
24+
Some(it) => it,
25+
None => {
26+
let position = Position::after(self.name().unwrap().syntax);
27+
create_generic_param_list(position)
28+
}
29+
}
30+
}
31+
2132
fn get_or_create_where_clause(&self) -> WhereClause {
2233
if self.where_clause().is_none() {
2334
let position = if let Some(ty) = self.ret_type() {
@@ -34,6 +45,16 @@ impl GenericParamsOwnerEdit for ast::Fn {
3445
}
3546

3647
impl GenericParamsOwnerEdit for ast::Impl {
48+
fn get_or_create_generic_param_list(&self) -> ast::GenericParamList {
49+
match self.generic_param_list() {
50+
Some(it) => it,
51+
None => {
52+
let position = Position::after(self.impl_token().unwrap());
53+
create_generic_param_list(position)
54+
}
55+
}
56+
}
57+
3758
fn get_or_create_where_clause(&self) -> WhereClause {
3859
if self.where_clause().is_none() {
3960
let position = if let Some(items) = self.assoc_item_list() {
@@ -48,6 +69,10 @@ impl GenericParamsOwnerEdit for ast::Impl {
4869
}
4970

5071
impl GenericParamsOwnerEdit for ast::Trait {
72+
fn get_or_create_generic_param_list(&self) -> ast::GenericParamList {
73+
todo!()
74+
}
75+
5176
fn get_or_create_where_clause(&self) -> WhereClause {
5277
if self.where_clause().is_none() {
5378
let position = if let Some(items) = self.assoc_item_list() {
@@ -62,6 +87,10 @@ impl GenericParamsOwnerEdit for ast::Trait {
6287
}
6388

6489
impl GenericParamsOwnerEdit for ast::Struct {
90+
fn get_or_create_generic_param_list(&self) -> ast::GenericParamList {
91+
todo!()
92+
}
93+
6594
fn get_or_create_where_clause(&self) -> WhereClause {
6695
if self.where_clause().is_none() {
6796
let tfl = self.field_list().and_then(|fl| match fl {
@@ -84,6 +113,10 @@ impl GenericParamsOwnerEdit for ast::Struct {
84113
}
85114

86115
impl GenericParamsOwnerEdit for ast::Enum {
116+
fn get_or_create_generic_param_list(&self) -> ast::GenericParamList {
117+
todo!()
118+
}
119+
87120
fn get_or_create_where_clause(&self) -> WhereClause {
88121
if self.where_clause().is_none() {
89122
let position = if let Some(gpl) = self.generic_param_list() {
@@ -104,6 +137,37 @@ fn create_where_clause(position: Position) {
104137
ted::insert(position, where_clause.syntax());
105138
}
106139

140+
fn create_generic_param_list(position: Position) -> ast::GenericParamList {
141+
let gpl = make::generic_param_list(empty()).clone_for_update();
142+
ted::insert_raw(position, gpl.syntax());
143+
gpl
144+
}
145+
146+
impl ast::GenericParamList {
147+
pub fn add_generic_param(&self, generic_param: ast::GenericParam) {
148+
match self.generic_params().last() {
149+
Some(last_param) => {
150+
let mut elems = Vec::new();
151+
if !last_param
152+
.syntax()
153+
.siblings_with_tokens(Direction::Next)
154+
.any(|it| it.kind() == T![,])
155+
{
156+
elems.push(make::token(T![,]).into());
157+
elems.push(make::tokens::single_space().into());
158+
};
159+
elems.push(generic_param.syntax().clone().into());
160+
let after_last_param = Position::after(last_param.syntax());
161+
ted::insert_all(after_last_param, elems);
162+
}
163+
None => {
164+
let after_l_angle = Position::after(self.l_angle_token().unwrap());
165+
ted::insert(after_l_angle, generic_param.syntax())
166+
}
167+
}
168+
}
169+
}
170+
107171
impl ast::WhereClause {
108172
pub fn add_predicate(&self, predicate: ast::WherePred) {
109173
if let Some(pred) = self.predicates().last() {

crates/syntax/src/ted.rs

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -165,6 +165,13 @@ fn ws_between(left: &SyntaxElement, right: &SyntaxElement) -> Option<SyntaxToken
165165
if right.kind() == T![;] || right.kind() == T![,] {
166166
return None;
167167
}
168+
if left.kind() == T![<] || right.kind() == T![>] {
169+
return None;
170+
}
171+
if left.kind() == T![&] && right.kind() == SyntaxKind::LIFETIME {
172+
return None;
173+
}
174+
168175
if right.kind() == SyntaxKind::USE {
169176
let indent = IndentLevel::from_element(left);
170177
return Some(make::tokens::whitespace(&format!("\n{}", indent)));

0 commit comments

Comments
 (0)