Skip to content

Commit 60d952e

Browse files
committed
Auto merge of rust-lang#14979 - DropDemBits:structure-snippets-migrate-1, r=Veykril
internal: Migrate some assists to use the structured snippet API Migrates the following assists: - `add_missing_impl_members` - `extract_type_alias` As an additional requirement, these assists are also migrated to use the mutable AST API, since otherwise there would be overlapping `Indel` spans
2 parents 425619d + dd5f055 commit 60d952e

File tree

5 files changed

+64
-61
lines changed

5 files changed

+64
-61
lines changed

crates/ide-assists/src/handlers/add_missing_impl_members.rs

Lines changed: 21 additions & 27 deletions
Original file line numberDiff line numberDiff line change
@@ -4,10 +4,7 @@ use syntax::ast::{self, make, AstNode};
44

55
use crate::{
66
assist_context::{AssistContext, Assists},
7-
utils::{
8-
add_trait_assoc_items_to_impl, filter_assoc_items, gen_trait_fn_body, render_snippet,
9-
Cursor, DefaultMethods,
10-
},
7+
utils::{add_trait_assoc_items_to_impl, filter_assoc_items, gen_trait_fn_body, DefaultMethods},
118
AssistId, AssistKind,
129
};
1310

@@ -130,7 +127,8 @@ fn add_missing_impl_members_inner(
130127
}
131128

132129
let target = impl_def.syntax().text_range();
133-
acc.add(AssistId(assist_id, AssistKind::QuickFix), label, target, |builder| {
130+
acc.add(AssistId(assist_id, AssistKind::QuickFix), label, target, |edit| {
131+
let new_impl_def = edit.make_mut(impl_def.clone());
134132
let missing_items = missing_items
135133
.into_iter()
136134
.map(|it| {
@@ -142,38 +140,34 @@ fn add_missing_impl_members_inner(
142140
it.clone_for_update()
143141
})
144142
.collect();
145-
let (new_impl_def, first_new_item) = add_trait_assoc_items_to_impl(
143+
let first_new_item = add_trait_assoc_items_to_impl(
146144
&ctx.sema,
147145
missing_items,
148146
trait_,
149-
impl_def.clone(),
147+
&new_impl_def,
150148
target_scope,
151149
);
152-
match ctx.config.snippet_cap {
153-
None => builder.replace(target, new_impl_def.to_string()),
154-
Some(cap) => {
155-
let mut cursor = Cursor::Before(first_new_item.syntax());
156-
let placeholder;
157-
if let DefaultMethods::No = mode {
158-
if let ast::AssocItem::Fn(func) = &first_new_item {
159-
if try_gen_trait_body(ctx, func, trait_ref, &impl_def).is_none() {
160-
if let Some(m) =
161-
func.syntax().descendants().find_map(ast::MacroCall::cast)
162-
{
163-
if m.syntax().text() == "todo!()" {
164-
placeholder = m;
165-
cursor = Cursor::Replace(placeholder.syntax());
166-
}
150+
151+
if let Some(cap) = ctx.config.snippet_cap {
152+
let mut placeholder = None;
153+
if let DefaultMethods::No = mode {
154+
if let ast::AssocItem::Fn(func) = &first_new_item {
155+
if try_gen_trait_body(ctx, func, trait_ref, &impl_def).is_none() {
156+
if let Some(m) = func.syntax().descendants().find_map(ast::MacroCall::cast)
157+
{
158+
if m.syntax().text() == "todo!()" {
159+
placeholder = Some(m);
167160
}
168161
}
169162
}
170163
}
171-
builder.replace_snippet(
172-
cap,
173-
target,
174-
render_snippet(cap, new_impl_def.syntax(), cursor),
175-
)
176164
}
165+
166+
if let Some(macro_call) = placeholder {
167+
edit.add_placeholder_snippet(cap, macro_call);
168+
} else {
169+
edit.add_tabstop_before(cap, first_new_item);
170+
};
177171
};
178172
})
179173
}

crates/ide-assists/src/handlers/extract_type_alias.rs

Lines changed: 28 additions & 21 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,9 @@
11
use either::Either;
22
use ide_db::syntax_helpers::node_ext::walk_ty;
3-
use syntax::ast::{self, edit::IndentLevel, make, AstNode, HasGenericParams, HasName};
3+
use syntax::{
4+
ast::{self, edit::IndentLevel, make, AstNode, HasGenericParams, HasName},
5+
ted,
6+
};
47

58
use crate::{AssistContext, AssistId, AssistKind, Assists};
69

@@ -34,14 +37,16 @@ pub(crate) fn extract_type_alias(acc: &mut Assists, ctx: &AssistContext<'_>) ->
3437
|| item.syntax(),
3538
|impl_| impl_.as_ref().either(AstNode::syntax, AstNode::syntax),
3639
);
37-
let insert_pos = node.text_range().start();
3840
let target = ty.syntax().text_range();
3941

4042
acc.add(
4143
AssistId("extract_type_alias", AssistKind::RefactorExtract),
4244
"Extract type as type alias",
4345
target,
44-
|builder| {
46+
|edit| {
47+
let node = edit.make_syntax_mut(node.clone());
48+
let target_ty = edit.make_mut(ty.clone());
49+
4550
let mut known_generics = match item.generic_param_list() {
4651
Some(it) => it.generic_params().collect(),
4752
None => Vec::new(),
@@ -56,27 +61,29 @@ pub(crate) fn extract_type_alias(acc: &mut Assists, ctx: &AssistContext<'_>) ->
5661
let generic_params =
5762
generics.map(|it| make::generic_param_list(it.into_iter().cloned()));
5863

64+
// Replace original type with the alias
5965
let ty_args = generic_params
6066
.as_ref()
6167
.map_or(String::new(), |it| it.to_generic_args().to_string());
62-
let replacement = format!("Type{ty_args}");
63-
builder.replace(target, replacement);
64-
65-
let indent = IndentLevel::from_node(node);
66-
let generic_params = generic_params.map_or(String::new(), |it| it.to_string());
67-
match ctx.config.snippet_cap {
68-
Some(cap) => {
69-
builder.insert_snippet(
70-
cap,
71-
insert_pos,
72-
format!("type $0Type{generic_params} = {ty};\n\n{indent}"),
73-
);
74-
}
75-
None => {
76-
builder.insert(
77-
insert_pos,
78-
format!("type Type{generic_params} = {ty};\n\n{indent}"),
79-
);
68+
// FIXME: replace with a `ast::make` constructor
69+
let new_ty = make::ty(&format!("Type{ty_args}")).clone_for_update();
70+
ted::replace(target_ty.syntax(), new_ty.syntax());
71+
72+
// Insert new alias
73+
let indent = IndentLevel::from_node(&node);
74+
let ty_alias = make::ty_alias("Type", generic_params, None, None, Some((ty, None)))
75+
.clone_for_update();
76+
ted::insert_all(
77+
ted::Position::before(node),
78+
vec![
79+
ty_alias.syntax().clone().into(),
80+
make::tokens::whitespace(&format!("\n\n{indent}")).into(),
81+
],
82+
);
83+
84+
if let Some(cap) = ctx.config.snippet_cap {
85+
if let Some(name) = ty_alias.name() {
86+
edit.add_tabstop_before(cap, name);
8087
}
8188
}
8289
},

crates/ide-assists/src/handlers/replace_derive_with_manual_impl.rs

Lines changed: 8 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -182,7 +182,11 @@ fn impl_def_from_trait(
182182
let impl_def = {
183183
use syntax::ast::Impl;
184184
let text = generate_trait_impl_text(adt, trait_path.to_string().as_str(), "");
185-
let parse = syntax::SourceFile::parse(&text);
185+
// FIXME: `generate_trait_impl_text` currently generates two newlines
186+
// at the front, but these leading newlines should really instead be
187+
// inserted at the same time the impl is inserted
188+
assert_eq!(&text[..2], "\n\n", "`generate_trait_impl_text` output changed");
189+
let parse = syntax::SourceFile::parse(&text[2..]);
186190
let node = match parse.tree().syntax().descendants().find_map(Impl::cast) {
187191
Some(it) => it,
188192
None => {
@@ -193,7 +197,7 @@ fn impl_def_from_trait(
193197
)
194198
}
195199
};
196-
let node = node.clone_subtree();
200+
let node = node.clone_for_update();
197201
assert_eq!(node.syntax().text_range().start(), 0.into());
198202
node
199203
};
@@ -209,8 +213,8 @@ fn impl_def_from_trait(
209213
it.clone_for_update()
210214
})
211215
.collect();
212-
let (impl_def, first_assoc_item) =
213-
add_trait_assoc_items_to_impl(sema, trait_items, trait_, impl_def, target_scope);
216+
let first_assoc_item =
217+
add_trait_assoc_items_to_impl(sema, trait_items, trait_, &impl_def, target_scope);
214218

215219
// Generate a default `impl` function body for the derived trait.
216220
if let ast::AssocItem::Fn(ref func) = first_assoc_item {

crates/ide-assists/src/utils.rs

Lines changed: 4 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -132,9 +132,9 @@ pub fn add_trait_assoc_items_to_impl(
132132
sema: &Semantics<'_, RootDatabase>,
133133
items: Vec<ast::AssocItem>,
134134
trait_: hir::Trait,
135-
impl_: ast::Impl,
135+
impl_: &ast::Impl,
136136
target_scope: hir::SemanticsScope<'_>,
137-
) -> (ast::Impl, ast::AssocItem) {
137+
) -> ast::AssocItem {
138138
let source_scope = sema.scope_for_def(trait_);
139139

140140
let transform = PathTransform::trait_impl(&target_scope, &source_scope, trait_, impl_.clone());
@@ -147,9 +147,7 @@ pub fn add_trait_assoc_items_to_impl(
147147
assoc_item
148148
});
149149

150-
let res = impl_.clone_for_update();
151-
152-
let assoc_item_list = res.get_or_create_assoc_item_list();
150+
let assoc_item_list = impl_.get_or_create_assoc_item_list();
153151
let mut first_item = None;
154152
for item in items {
155153
first_item.get_or_insert_with(|| item.clone());
@@ -172,7 +170,7 @@ pub fn add_trait_assoc_items_to_impl(
172170
assoc_item_list.add_item(item)
173171
}
174172

175-
(res, first_item.unwrap())
173+
first_item.unwrap()
176174
}
177175

178176
#[derive(Clone, Copy, Debug)]

crates/syntax/src/ast/make.rs

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -166,7 +166,7 @@ pub fn ty_alias(
166166
assignment: Option<(ast::Type, Option<ast::WhereClause>)>,
167167
) -> ast::TypeAlias {
168168
let mut s = String::new();
169-
s.push_str(&format!("type {} ", ident));
169+
s.push_str(&format!("type {}", ident));
170170

171171
if let Some(list) = generic_param_list {
172172
s.push_str(&list.to_string());
@@ -182,9 +182,9 @@ pub fn ty_alias(
182182

183183
if let Some(exp) = assignment {
184184
if let Some(cl) = exp.1 {
185-
s.push_str(&format!("= {} {}", &exp.0.to_string(), &cl.to_string()));
185+
s.push_str(&format!(" = {} {}", &exp.0.to_string(), &cl.to_string()));
186186
} else {
187-
s.push_str(&format!("= {}", &exp.0.to_string()));
187+
s.push_str(&format!(" = {}", &exp.0.to_string()));
188188
}
189189
}
190190

0 commit comments

Comments
 (0)