Skip to content

Commit 24e552f

Browse files
Merge #2663
2663: Fill in type params in 'add missing impl members' assist r=flodiebold a=flodiebold Co-authored-by: Florian Diebold <flodiebold@gmail.com>
2 parents 52b44ba + c39352f commit 24e552f

File tree

5 files changed

+151
-37
lines changed

5 files changed

+151
-37
lines changed

crates/ra_assists/src/assist_ctx.rs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -46,7 +46,7 @@ pub(crate) enum Assist {
4646
///
4747
/// Note, however, that we don't actually use such two-phase logic at the
4848
/// moment, because the LSP API is pretty awkward in this place, and it's much
49-
/// easier to just compute the edit eagerly :-)#[derive(Debug, Clone)]
49+
/// easier to just compute the edit eagerly :-)
5050
#[derive(Debug)]
5151
pub(crate) struct AssistCtx<'a, DB> {
5252
pub(crate) db: &'a DB,

crates/ra_assists/src/assists/add_missing_impl_members.rs

Lines changed: 117 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,5 @@
1+
use std::collections::HashMap;
2+
13
use hir::{db::HirDatabase, HasSource};
24
use ra_syntax::{
35
ast::{self, edit, make, AstNode, NameOwner},
@@ -17,26 +19,26 @@ enum AddMissingImplMembersMode {
1719
// Adds scaffold for required impl members.
1820
//
1921
// ```
20-
// trait T {
22+
// trait Trait<T> {
2123
// Type X;
22-
// fn foo(&self);
24+
// fn foo(&self) -> T;
2325
// fn bar(&self) {}
2426
// }
2527
//
26-
// impl T for () {<|>
28+
// impl Trait<u32> for () {<|>
2729
//
2830
// }
2931
// ```
3032
// ->
3133
// ```
32-
// trait T {
34+
// trait Trait<T> {
3335
// Type X;
34-
// fn foo(&self);
36+
// fn foo(&self) -> T;
3537
// fn bar(&self) {}
3638
// }
3739
//
38-
// impl T for () {
39-
// fn foo(&self) { unimplemented!() }
40+
// impl Trait<u32> for () {
41+
// fn foo(&self) -> u32 { unimplemented!() }
4042
//
4143
// }
4244
// ```
@@ -54,27 +56,27 @@ pub(crate) fn add_missing_impl_members(ctx: AssistCtx<impl HirDatabase>) -> Opti
5456
// Adds scaffold for overriding default impl members.
5557
//
5658
// ```
57-
// trait T {
59+
// trait Trait {
5860
// Type X;
5961
// fn foo(&self);
6062
// fn bar(&self) {}
6163
// }
6264
//
63-
// impl T for () {
65+
// impl Trait for () {
6466
// Type X = ();
6567
// fn foo(&self) {}<|>
6668
//
6769
// }
6870
// ```
6971
// ->
7072
// ```
71-
// trait T {
73+
// trait Trait {
7274
// Type X;
7375
// fn foo(&self);
7476
// fn bar(&self) {}
7577
// }
7678
//
77-
// impl T for () {
79+
// impl Trait for () {
7880
// Type X = ();
7981
// fn foo(&self) {}
8082
// fn bar(&self) {}
@@ -99,7 +101,7 @@ fn add_missing_impl_members_inner(
99101
let impl_node = ctx.find_node_at_offset::<ast::ImplBlock>()?;
100102
let impl_item_list = impl_node.item_list()?;
101103

102-
let trait_def = {
104+
let (trait_, trait_def) = {
103105
let analyzer = ctx.source_analyzer(impl_node.syntax(), None);
104106

105107
resolve_target_trait_def(ctx.db, &analyzer, &impl_node)?
@@ -132,10 +134,25 @@ fn add_missing_impl_members_inner(
132134
return None;
133135
}
134136

137+
let file_id = ctx.frange.file_id;
138+
let db = ctx.db;
139+
135140
ctx.add_assist(AssistId(assist_id), label, |edit| {
136141
let n_existing_items = impl_item_list.impl_items().count();
142+
let substs = get_syntactic_substs(impl_node).unwrap_or_default();
143+
let generic_def: hir::GenericDef = trait_.into();
144+
let substs_by_param: HashMap<_, _> = generic_def
145+
.params(db)
146+
.into_iter()
147+
// this is a trait impl, so we need to skip the first type parameter -- this is a bit hacky
148+
.skip(1)
149+
.zip(substs.into_iter())
150+
.collect();
137151
let items = missing_items
138152
.into_iter()
153+
.map(|it| {
154+
substitute_type_params(db, hir::InFile::new(file_id.into(), it), &substs_by_param)
155+
})
139156
.map(|it| match it {
140157
ast::ImplItem::FnDef(def) => ast::ImplItem::FnDef(add_body(def)),
141158
_ => it,
@@ -160,21 +177,73 @@ fn add_body(fn_def: ast::FnDef) -> ast::FnDef {
160177
}
161178
}
162179

180+
// FIXME: It would probably be nicer if we could get this via HIR (i.e. get the
181+
// trait ref, and then go from the types in the substs back to the syntax)
182+
// FIXME: This should be a general utility (not even just for assists)
183+
fn get_syntactic_substs(impl_block: ast::ImplBlock) -> Option<Vec<ast::TypeRef>> {
184+
let target_trait = impl_block.target_trait()?;
185+
let path_type = match target_trait {
186+
ast::TypeRef::PathType(path) => path,
187+
_ => return None,
188+
};
189+
let type_arg_list = path_type.path()?.segment()?.type_arg_list()?;
190+
let mut result = Vec::new();
191+
for type_arg in type_arg_list.type_args() {
192+
let type_arg: ast::TypeArg = type_arg;
193+
result.push(type_arg.type_ref()?);
194+
}
195+
Some(result)
196+
}
197+
198+
// FIXME: This should be a general utility (not even just for assists)
199+
fn substitute_type_params<N: AstNode>(
200+
db: &impl HirDatabase,
201+
node: hir::InFile<N>,
202+
substs: &HashMap<hir::TypeParam, ast::TypeRef>,
203+
) -> N {
204+
let type_param_replacements = node
205+
.value
206+
.syntax()
207+
.descendants()
208+
.filter_map(ast::TypeRef::cast)
209+
.filter_map(|n| {
210+
let path = match &n {
211+
ast::TypeRef::PathType(path_type) => path_type.path()?,
212+
_ => return None,
213+
};
214+
let analyzer = hir::SourceAnalyzer::new(db, node.with_value(n.syntax()), None);
215+
let resolution = analyzer.resolve_path(db, &path)?;
216+
match resolution {
217+
hir::PathResolution::TypeParam(tp) => Some((n, substs.get(&tp)?.clone())),
218+
_ => None,
219+
}
220+
})
221+
.collect::<Vec<_>>();
222+
223+
if type_param_replacements.is_empty() {
224+
node.value
225+
} else {
226+
edit::replace_descendants(&node.value, type_param_replacements.into_iter())
227+
}
228+
}
229+
163230
/// Given an `ast::ImplBlock`, resolves the target trait (the one being
164231
/// implemented) to a `ast::TraitDef`.
165232
fn resolve_target_trait_def(
166233
db: &impl HirDatabase,
167234
analyzer: &hir::SourceAnalyzer,
168235
impl_block: &ast::ImplBlock,
169-
) -> Option<ast::TraitDef> {
236+
) -> Option<(hir::Trait, ast::TraitDef)> {
170237
let ast_path = impl_block
171238
.target_trait()
172239
.map(|it| it.syntax().clone())
173240
.and_then(ast::PathType::cast)?
174241
.path()?;
175242

176243
match analyzer.resolve_path(db, &ast_path) {
177-
Some(hir::PathResolution::Def(hir::ModuleDef::Trait(def))) => Some(def.source(db).value),
244+
Some(hir::PathResolution::Def(hir::ModuleDef::Trait(def))) => {
245+
Some((def, def.source(db).value))
246+
}
178247
_ => None,
179248
}
180249
}
@@ -280,6 +349,40 @@ impl Foo for S {
280349
);
281350
}
282351

352+
#[test]
353+
fn fill_in_type_params_1() {
354+
check_assist(
355+
add_missing_impl_members,
356+
"
357+
trait Foo<T> { fn foo(&self, t: T) -> &T; }
358+
struct S;
359+
impl Foo<u32> for S { <|> }",
360+
"
361+
trait Foo<T> { fn foo(&self, t: T) -> &T; }
362+
struct S;
363+
impl Foo<u32> for S {
364+
<|>fn foo(&self, t: u32) -> &u32 { unimplemented!() }
365+
}",
366+
);
367+
}
368+
369+
#[test]
370+
fn fill_in_type_params_2() {
371+
check_assist(
372+
add_missing_impl_members,
373+
"
374+
trait Foo<T> { fn foo(&self, t: T) -> &T; }
375+
struct S;
376+
impl<U> Foo<U> for S { <|> }",
377+
"
378+
trait Foo<T> { fn foo(&self, t: T) -> &T; }
379+
struct S;
380+
impl<U> Foo<U> for S {
381+
<|>fn foo(&self, t: U) -> &U { unimplemented!() }
382+
}",
383+
);
384+
}
385+
283386
#[test]
284387
fn test_cursor_after_empty_impl_block() {
285388
check_assist(

crates/ra_assists/src/doc_tests/generated.rs

Lines changed: 11 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -101,26 +101,26 @@ fn doctest_add_impl_default_members() {
101101
check(
102102
"add_impl_default_members",
103103
r#####"
104-
trait T {
104+
trait Trait {
105105
Type X;
106106
fn foo(&self);
107107
fn bar(&self) {}
108108
}
109109
110-
impl T for () {
110+
impl Trait for () {
111111
Type X = ();
112112
fn foo(&self) {}<|>
113113
114114
}
115115
"#####,
116116
r#####"
117-
trait T {
117+
trait Trait {
118118
Type X;
119119
fn foo(&self);
120120
fn bar(&self) {}
121121
}
122122
123-
impl T for () {
123+
impl Trait for () {
124124
Type X = ();
125125
fn foo(&self) {}
126126
fn bar(&self) {}
@@ -135,25 +135,25 @@ fn doctest_add_impl_missing_members() {
135135
check(
136136
"add_impl_missing_members",
137137
r#####"
138-
trait T {
138+
trait Trait<T> {
139139
Type X;
140-
fn foo(&self);
140+
fn foo(&self) -> T;
141141
fn bar(&self) {}
142142
}
143143
144-
impl T for () {<|>
144+
impl Trait<u32> for () {<|>
145145
146146
}
147147
"#####,
148148
r#####"
149-
trait T {
149+
trait Trait<T> {
150150
Type X;
151-
fn foo(&self);
151+
fn foo(&self) -> T;
152152
fn bar(&self) {}
153153
}
154154
155-
impl T for () {
156-
fn foo(&self) { unimplemented!() }
155+
impl Trait<u32> for () {
156+
fn foo(&self) -> u32 { unimplemented!() }
157157
158158
}
159159
"#####,

crates/ra_hir/src/code_model.rs

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -644,6 +644,17 @@ impl_froms!(
644644
Const
645645
);
646646

647+
impl GenericDef {
648+
pub fn params(self, db: &impl HirDatabase) -> Vec<TypeParam> {
649+
let generics: Arc<hir_def::generics::GenericParams> = db.generic_params(self.into());
650+
generics
651+
.types
652+
.iter()
653+
.map(|(local_id, _)| TypeParam { id: TypeParamId { parent: self.into(), local_id } })
654+
.collect()
655+
}
656+
}
657+
647658
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
648659
pub struct Local {
649660
pub(crate) parent: DefWithBody,

docs/user/assists.md

Lines changed: 11 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -98,26 +98,26 @@ Adds scaffold for overriding default impl members.
9898

9999
```rust
100100
// BEFORE
101-
trait T {
101+
trait Trait {
102102
Type X;
103103
fn foo(&self);
104104
fn bar(&self) {}
105105
}
106106

107-
impl T for () {
107+
impl Trait for () {
108108
Type X = ();
109109
fn foo(&self) {}┃
110110

111111
}
112112

113113
// AFTER
114-
trait T {
114+
trait Trait {
115115
Type X;
116116
fn foo(&self);
117117
fn bar(&self) {}
118118
}
119119

120-
impl T for () {
120+
impl Trait for () {
121121
Type X = ();
122122
fn foo(&self) {}
123123
fn bar(&self) {}
@@ -131,25 +131,25 @@ Adds scaffold for required impl members.
131131

132132
```rust
133133
// BEFORE
134-
trait T {
134+
trait Trait<T> {
135135
Type X;
136-
fn foo(&self);
136+
fn foo(&self) -> T;
137137
fn bar(&self) {}
138138
}
139139

140-
impl T for () {┃
140+
impl Trait<u32> for () {┃
141141

142142
}
143143

144144
// AFTER
145-
trait T {
145+
trait Trait<T> {
146146
Type X;
147-
fn foo(&self);
147+
fn foo(&self) -> T;
148148
fn bar(&self) {}
149149
}
150150

151-
impl T for () {
152-
fn foo(&self) { unimplemented!() }
151+
impl Trait<u32> for () {
152+
fn foo(&self) -> u32 { unimplemented!() }
153153

154154
}
155155
```

0 commit comments

Comments
 (0)