]> git.lizzy.rs Git - rust.git/blob - crates/ra_assists/src/assists/add_missing_impl_members.rs
check style for assist docs
[rust.git] / crates / ra_assists / src / assists / add_missing_impl_members.rs
1 use hir::{db::HirDatabase, HasSource};
2 use ra_syntax::{
3     ast::{self, edit, make, AstNode, NameOwner},
4     SmolStr,
5 };
6
7 use crate::{Assist, AssistCtx, AssistId};
8
9 #[derive(PartialEq)]
10 enum AddMissingImplMembersMode {
11     DefaultMethodsOnly,
12     NoDefaultMethods,
13 }
14
15 // Assist: add_impl_missing_members
16 //
17 // Adds scaffold for required impl members.
18 //
19 // ```
20 // trait T {
21 //     Type X;
22 //     fn foo(&self);
23 //     fn bar(&self) {}
24 // }
25 //
26 // impl T for () {<|>
27 //
28 // }
29 // ```
30 // ->
31 // ```
32 // trait T {
33 //     Type X;
34 //     fn foo(&self);
35 //     fn bar(&self) {}
36 // }
37 //
38 // impl T for () {
39 //     fn foo(&self) { unimplemented!() }
40 //
41 // }
42 // ```
43 pub(crate) fn add_missing_impl_members(ctx: AssistCtx<impl HirDatabase>) -> Option<Assist> {
44     add_missing_impl_members_inner(
45         ctx,
46         AddMissingImplMembersMode::NoDefaultMethods,
47         "add_impl_missing_members",
48         "add missing impl members",
49     )
50 }
51
52 // Assist: add_impl_default_members
53 //
54 // Adds scaffold for overriding default impl members.
55 //
56 // ```
57 // trait T {
58 //     Type X;
59 //     fn foo(&self);
60 //     fn bar(&self) {}
61 // }
62 //
63 // impl T for () {
64 //     Type X = ();
65 //     fn foo(&self) {}<|>
66 //
67 // }
68 // ```
69 // ->
70 // ```
71 // trait T {
72 //     Type X;
73 //     fn foo(&self);
74 //     fn bar(&self) {}
75 // }
76 //
77 // impl T for () {
78 //     Type X = ();
79 //     fn foo(&self) {}
80 //     fn bar(&self) {}
81 //
82 // }
83 // ```
84 pub(crate) fn add_missing_default_members(ctx: AssistCtx<impl HirDatabase>) -> Option<Assist> {
85     add_missing_impl_members_inner(
86         ctx,
87         AddMissingImplMembersMode::DefaultMethodsOnly,
88         "add_impl_default_members",
89         "add impl default members",
90     )
91 }
92
93 fn add_missing_impl_members_inner(
94     mut ctx: AssistCtx<impl HirDatabase>,
95     mode: AddMissingImplMembersMode,
96     assist_id: &'static str,
97     label: &'static str,
98 ) -> Option<Assist> {
99     let impl_node = ctx.node_at_offset::<ast::ImplBlock>()?;
100     let impl_item_list = impl_node.item_list()?;
101
102     let trait_def = {
103         let file_id = ctx.frange.file_id;
104         let analyzer = hir::SourceAnalyzer::new(ctx.db, file_id, impl_node.syntax(), None);
105
106         resolve_target_trait_def(ctx.db, &analyzer, &impl_node)?
107     };
108
109     let def_name = |item: &ast::ImplItem| -> Option<SmolStr> {
110         match item {
111             ast::ImplItem::FnDef(def) => def.name(),
112             ast::ImplItem::TypeAliasDef(def) => def.name(),
113             ast::ImplItem::ConstDef(def) => def.name(),
114         }
115         .map(|it| it.text().clone())
116     };
117
118     let trait_items = trait_def.item_list()?.impl_items();
119     let impl_items = impl_item_list.impl_items().collect::<Vec<_>>();
120
121     let missing_items: Vec<_> = trait_items
122         .filter(|t| def_name(t).is_some())
123         .filter(|t| match t {
124             ast::ImplItem::FnDef(def) => match mode {
125                 AddMissingImplMembersMode::DefaultMethodsOnly => def.body().is_some(),
126                 AddMissingImplMembersMode::NoDefaultMethods => def.body().is_none(),
127             },
128             _ => mode == AddMissingImplMembersMode::NoDefaultMethods,
129         })
130         .filter(|t| impl_items.iter().all(|i| def_name(i) != def_name(t)))
131         .collect();
132     if missing_items.is_empty() {
133         return None;
134     }
135
136     ctx.add_action(AssistId(assist_id), label, |edit| {
137         let n_existing_items = impl_item_list.impl_items().count();
138         let items = missing_items
139             .into_iter()
140             .map(|it| match it {
141                 ast::ImplItem::FnDef(def) => ast::ImplItem::FnDef(add_body(def)),
142                 _ => it,
143             })
144             .map(|it| edit::strip_attrs_and_docs(&it));
145         let new_impl_item_list = impl_item_list.append_items(items);
146         let cursor_position = {
147             let first_new_item = new_impl_item_list.impl_items().nth(n_existing_items).unwrap();
148             first_new_item.syntax().text_range().start()
149         };
150
151         edit.replace_ast(impl_item_list, new_impl_item_list);
152         edit.set_cursor(cursor_position);
153     });
154
155     ctx.build()
156 }
157
158 fn add_body(fn_def: ast::FnDef) -> ast::FnDef {
159     if fn_def.body().is_none() {
160         fn_def.with_body(make::block_from_expr(make::expr_unimplemented()))
161     } else {
162         fn_def
163     }
164 }
165
166 /// Given an `ast::ImplBlock`, resolves the target trait (the one being
167 /// implemented) to a `ast::TraitDef`.
168 fn resolve_target_trait_def(
169     db: &impl HirDatabase,
170     analyzer: &hir::SourceAnalyzer,
171     impl_block: &ast::ImplBlock,
172 ) -> Option<ast::TraitDef> {
173     let ast_path = impl_block
174         .target_trait()
175         .map(|it| it.syntax().clone())
176         .and_then(ast::PathType::cast)?
177         .path()?;
178
179     match analyzer.resolve_path(db, &ast_path) {
180         Some(hir::PathResolution::Def(hir::ModuleDef::Trait(def))) => Some(def.source(db).ast),
181         _ => None,
182     }
183 }
184
185 #[cfg(test)]
186 mod tests {
187     use super::*;
188     use crate::helpers::{check_assist, check_assist_not_applicable};
189
190     #[test]
191     fn test_add_missing_impl_members() {
192         check_assist(
193             add_missing_impl_members,
194             "
195 trait Foo {
196     type Output;
197
198     const CONST: usize = 42;
199
200     fn foo(&self);
201     fn bar(&self);
202     fn baz(&self);
203 }
204
205 struct S;
206
207 impl Foo for S {
208     fn bar(&self) {}
209 <|>
210 }",
211             "
212 trait Foo {
213     type Output;
214
215     const CONST: usize = 42;
216
217     fn foo(&self);
218     fn bar(&self);
219     fn baz(&self);
220 }
221
222 struct S;
223
224 impl Foo for S {
225     fn bar(&self) {}
226     <|>type Output;
227     const CONST: usize = 42;
228     fn foo(&self) { unimplemented!() }
229     fn baz(&self) { unimplemented!() }
230
231 }",
232         );
233     }
234
235     #[test]
236     fn test_copied_overriden_members() {
237         check_assist(
238             add_missing_impl_members,
239             "
240 trait Foo {
241     fn foo(&self);
242     fn bar(&self) -> bool { true }
243     fn baz(&self) -> u32 { 42 }
244 }
245
246 struct S;
247
248 impl Foo for S {
249     fn bar(&self) {}
250 <|>
251 }",
252             "
253 trait Foo {
254     fn foo(&self);
255     fn bar(&self) -> bool { true }
256     fn baz(&self) -> u32 { 42 }
257 }
258
259 struct S;
260
261 impl Foo for S {
262     fn bar(&self) {}
263     <|>fn foo(&self) { unimplemented!() }
264
265 }",
266         );
267     }
268
269     #[test]
270     fn test_empty_impl_block() {
271         check_assist(
272             add_missing_impl_members,
273             "
274 trait Foo { fn foo(&self); }
275 struct S;
276 impl Foo for S { <|> }",
277             "
278 trait Foo { fn foo(&self); }
279 struct S;
280 impl Foo for S {
281     <|>fn foo(&self) { unimplemented!() }
282 }",
283         );
284     }
285
286     #[test]
287     fn test_cursor_after_empty_impl_block() {
288         check_assist(
289             add_missing_impl_members,
290             "
291 trait Foo { fn foo(&self); }
292 struct S;
293 impl Foo for S {}<|>",
294             "
295 trait Foo { fn foo(&self); }
296 struct S;
297 impl Foo for S {
298     <|>fn foo(&self) { unimplemented!() }
299 }",
300         )
301     }
302
303     #[test]
304     fn test_empty_trait() {
305         check_assist_not_applicable(
306             add_missing_impl_members,
307             "
308 trait Foo;
309 struct S;
310 impl Foo for S { <|> }",
311         )
312     }
313
314     #[test]
315     fn test_ignore_unnamed_trait_members_and_default_methods() {
316         check_assist_not_applicable(
317             add_missing_impl_members,
318             "
319 trait Foo {
320     fn (arg: u32);
321     fn valid(some: u32) -> bool { false }
322 }
323 struct S;
324 impl Foo for S { <|> }",
325         )
326     }
327
328     #[test]
329     fn test_with_docstring_and_attrs() {
330         check_assist(
331             add_missing_impl_members,
332             r#"
333 #[doc(alias = "test alias")]
334 trait Foo {
335     /// doc string
336     type Output;
337
338     #[must_use]
339     fn foo(&self);
340 }
341 struct S;
342 impl Foo for S {}<|>"#,
343             r#"
344 #[doc(alias = "test alias")]
345 trait Foo {
346     /// doc string
347     type Output;
348
349     #[must_use]
350     fn foo(&self);
351 }
352 struct S;
353 impl Foo for S {
354     <|>type Output;
355     fn foo(&self) { unimplemented!() }
356 }"#,
357         )
358     }
359
360     #[test]
361     fn test_default_methods() {
362         check_assist(
363             add_missing_default_members,
364             "
365 trait Foo {
366     type Output;
367
368     const CONST: usize = 42;
369
370     fn valid(some: u32) -> bool { false }
371     fn foo(some: u32) -> bool;
372 }
373 struct S;
374 impl Foo for S { <|> }",
375             "
376 trait Foo {
377     type Output;
378
379     const CONST: usize = 42;
380
381     fn valid(some: u32) -> bool { false }
382     fn foo(some: u32) -> bool;
383 }
384 struct S;
385 impl Foo for S {
386     <|>fn valid(some: u32) -> bool { false }
387 }",
388         )
389     }
390 }