rust/crates/ra_assists/src/handlers/add_missing_impl_members.rs

721 lines
15 KiB
Rust
Raw Normal View History

use hir::HasSource;
2019-08-22 13:31:21 -05:00
use ra_syntax::{
ast::{
self,
2020-05-09 07:40:11 -05:00
edit::{self, AstNodeEdit, IndentLevel},
make, AstNode, NameOwner,
},
2019-08-22 13:31:21 -05:00
SmolStr,
};
use crate::{
assist_context::{AssistContext, Assists},
ast_transform::{self, AstTransform, QualifyPaths, SubstituteTypeParams},
2020-05-19 18:53:21 -05:00
utils::{get_missing_assoc_items, render_snippet, resolve_target_trait, Cursor},
2020-06-28 17:36:05 -05:00
AssistId, AssistKind,
};
#[derive(PartialEq)]
2019-03-23 10:06:25 -05:00
enum AddMissingImplMembersMode {
DefaultMethodsOnly,
NoDefaultMethods,
}
2019-10-25 15:38:15 -05:00
// Assist: add_impl_missing_members
2019-10-26 09:27:47 -05:00
//
2019-10-26 11:08:13 -05:00
// Adds scaffold for required impl members.
2019-10-26 09:27:47 -05:00
//
2019-10-25 15:38:15 -05:00
// ```
// trait Trait<T> {
2019-10-25 15:38:15 -05:00
// Type X;
// fn foo(&self) -> T;
2019-10-25 15:38:15 -05:00
// fn bar(&self) {}
// }
//
// impl Trait<u32> for () {<|>
2019-10-25 15:38:15 -05:00
//
// }
// ```
// ->
// ```
// trait Trait<T> {
2019-10-25 15:38:15 -05:00
// Type X;
// fn foo(&self) -> T;
2019-10-25 15:38:15 -05:00
// fn bar(&self) {}
// }
//
// impl Trait<u32> for () {
// fn foo(&self) -> u32 {
// ${0:todo!()}
// }
2019-10-25 15:38:15 -05:00
//
// }
// ```
pub(crate) fn add_missing_impl_members(acc: &mut Assists, ctx: &AssistContext) -> Option<()> {
2019-03-23 10:06:25 -05:00
add_missing_impl_members_inner(
acc,
2019-03-23 10:06:25 -05:00
ctx,
AddMissingImplMembersMode::NoDefaultMethods,
"add_impl_missing_members",
2020-01-14 11:32:26 -06:00
"Implement missing members",
2019-03-23 10:06:25 -05:00
)
}
2019-10-25 15:38:15 -05:00
// Assist: add_impl_default_members
2019-10-26 11:08:13 -05:00
//
// Adds scaffold for overriding default impl members.
//
2019-10-25 15:38:15 -05:00
// ```
// trait Trait {
2019-10-25 15:38:15 -05:00
// Type X;
// fn foo(&self);
// fn bar(&self) {}
// }
//
// impl Trait for () {
2019-10-25 15:38:15 -05:00
// Type X = ();
// fn foo(&self) {}<|>
//
// }
// ```
// ->
// ```
// trait Trait {
2019-10-25 15:38:15 -05:00
// Type X;
// fn foo(&self);
// fn bar(&self) {}
// }
//
// impl Trait for () {
2019-10-25 15:38:15 -05:00
// Type X = ();
// fn foo(&self) {}
2020-05-19 18:53:21 -05:00
// $0fn bar(&self) {}
2019-10-25 15:38:15 -05:00
//
// }
// ```
pub(crate) fn add_missing_default_members(acc: &mut Assists, ctx: &AssistContext) -> Option<()> {
2019-03-23 10:06:25 -05:00
add_missing_impl_members_inner(
acc,
2019-03-23 10:06:25 -05:00
ctx,
AddMissingImplMembersMode::DefaultMethodsOnly,
"add_impl_default_members",
2020-01-14 11:32:26 -06:00
"Implement default members",
2019-03-23 10:06:25 -05:00
)
}
fn add_missing_impl_members_inner(
acc: &mut Assists,
ctx: &AssistContext,
2019-03-23 10:06:25 -05:00
mode: AddMissingImplMembersMode,
assist_id: &'static str,
label: &'static str,
) -> Option<()> {
let _p = ra_prof::profile("add_missing_impl_members_inner");
let impl_def = ctx.find_node_at_offset::<ast::ImplDef>()?;
let impl_item_list = impl_def.item_list()?;
let trait_ = resolve_target_trait(&ctx.sema, &impl_def)?;
2020-05-05 10:56:10 -05:00
let def_name = |item: &ast::AssocItem| -> Option<SmolStr> {
2019-08-19 06:11:09 -05:00
match item {
2020-05-05 10:56:10 -05:00
ast::AssocItem::FnDef(def) => def.name(),
ast::AssocItem::TypeAliasDef(def) => def.name(),
ast::AssocItem::ConstDef(def) => def.name(),
}
2019-07-19 03:24:41 -05:00
.map(|it| it.text().clone())
2019-03-07 09:20:37 -06:00
};
let missing_items = get_missing_assoc_items(&ctx.sema, &impl_def)
.iter()
.map(|i| match i {
2020-07-01 02:14:23 -05:00
hir::AssocItem::Function(i) => ast::AssocItem::FnDef(i.source(ctx.db()).value),
hir::AssocItem::TypeAlias(i) => ast::AssocItem::TypeAliasDef(i.source(ctx.db()).value),
hir::AssocItem::Const(i) => ast::AssocItem::ConstDef(i.source(ctx.db()).value),
})
.filter(|t| def_name(&t).is_some())
2019-08-19 06:11:09 -05:00
.filter(|t| match t {
2020-05-05 10:56:10 -05:00
ast::AssocItem::FnDef(def) => match mode {
AddMissingImplMembersMode::DefaultMethodsOnly => def.body().is_some(),
AddMissingImplMembersMode::NoDefaultMethods => def.body().is_none(),
2020-02-11 09:40:08 -06:00
},
_ => mode == AddMissingImplMembersMode::NoDefaultMethods,
})
.collect::<Vec<_>>();
if missing_items.is_empty() {
2019-03-06 18:48:31 -06:00
return None;
}
let target = impl_def.syntax().text_range();
2020-07-02 16:48:35 -05:00
acc.add(AssistId(assist_id, AssistKind::QuickFix), label, target, |builder| {
2020-05-05 10:56:10 -05:00
let n_existing_items = impl_item_list.assoc_items().count();
let source_scope = ctx.sema.scope_for_def(trait_);
let target_scope = ctx.sema.scope(impl_item_list.syntax());
2020-03-13 12:02:04 -05:00
let ast_transform = QualifyPaths::new(&target_scope, &source_scope)
.or(SubstituteTypeParams::for_trait_impl(&source_scope, trait_, impl_def));
2019-09-30 02:08:28 -05:00
let items = missing_items
.into_iter()
.map(|it| ast_transform::apply(&*ast_transform, it))
2019-09-30 02:08:28 -05:00
.map(|it| match it {
2020-05-05 10:56:10 -05:00
ast::AssocItem::FnDef(def) => ast::AssocItem::FnDef(add_body(def)),
ast::AssocItem::TypeAliasDef(def) => {
ast::AssocItem::TypeAliasDef(remove_bounds(def))
}
2019-09-30 02:08:28 -05:00
_ => it,
})
2020-03-24 06:56:07 -05:00
.map(|it| edit::remove_attrs_and_docs(&it));
let new_impl_item_list = impl_item_list.append_items(items);
2020-05-19 18:53:21 -05:00
let first_new_item = new_impl_item_list.assoc_items().nth(n_existing_items).unwrap();
let original_range = impl_item_list.syntax().text_range();
match ctx.config.snippet_cap {
None => builder.replace(original_range, new_impl_item_list.to_string()),
Some(cap) => {
let mut cursor = Cursor::Before(first_new_item.syntax());
let placeholder;
if let ast::AssocItem::FnDef(func) = &first_new_item {
if let Some(m) = func.syntax().descendants().find_map(ast::MacroCall::cast) {
if m.syntax().text() == "todo!()" {
placeholder = m;
cursor = Cursor::Replace(placeholder.syntax());
}
}
}
builder.replace_snippet(
2020-05-19 18:53:21 -05:00
cap,
original_range,
render_snippet(cap, new_impl_item_list.syntax(), cursor),
)
}
};
})
}
fn remove_bounds(ty_def: ast::TypeAliasDef) -> ast::TypeAliasDef {
if let Some(name) = ty_def.name() {
make::type_alias_def(name, None, ty_def.type_ref())
} else {
ty_def
}
}
2019-07-19 03:24:41 -05:00
fn add_body(fn_def: ast::FnDef) -> ast::FnDef {
if fn_def.body().is_some() {
return fn_def;
}
2020-05-09 07:40:11 -05:00
let body = make::block_expr(None, Some(make::expr_todo())).indent(IndentLevel(1));
fn_def.with_body(body)
}
#[cfg(test)]
mod tests {
2020-05-06 03:16:55 -05:00
use crate::tests::{check_assist, check_assist_not_applicable};
use super::*;
#[test]
fn test_add_missing_impl_members() {
check_assist(
add_missing_impl_members,
r#"
trait Foo {
type Output;
const CONST: usize = 42;
fn foo(&self);
2019-03-06 18:48:31 -06:00
fn bar(&self);
fn baz(&self);
}
struct S;
impl Foo for S {
2019-03-06 18:48:31 -06:00
fn bar(&self) {}
<|>
}"#,
r#"
trait Foo {
type Output;
const CONST: usize = 42;
fn foo(&self);
2019-03-06 18:48:31 -06:00
fn bar(&self);
fn baz(&self);
}
struct S;
impl Foo for S {
2019-03-06 18:48:31 -06:00
fn bar(&self) {}
2020-05-19 18:53:21 -05:00
$0type Output;
const CONST: usize = 42;
fn foo(&self) {
todo!()
}
fn baz(&self) {
todo!()
}
}"#,
);
}
#[test]
fn test_copied_overriden_members() {
check_assist(
add_missing_impl_members,
r#"
trait Foo {
fn foo(&self);
fn bar(&self) -> bool { true }
fn baz(&self) -> u32 { 42 }
}
struct S;
impl Foo for S {
fn bar(&self) {}
<|>
}"#,
r#"
trait Foo {
fn foo(&self);
fn bar(&self) -> bool { true }
fn baz(&self) -> u32 { 42 }
}
struct S;
impl Foo for S {
fn bar(&self) {}
fn foo(&self) {
${0:todo!()}
}
}"#,
);
}
#[test]
2020-02-29 14:24:40 -06:00
fn test_empty_impl_def() {
check_assist(
add_missing_impl_members,
r#"
trait Foo { fn foo(&self); }
struct S;
impl Foo for S { <|> }"#,
r#"
trait Foo { fn foo(&self); }
struct S;
impl Foo for S {
fn foo(&self) {
${0:todo!()}
}
}"#,
);
}
#[test]
fn fill_in_type_params_1() {
check_assist(
add_missing_impl_members,
r#"
trait Foo<T> { fn foo(&self, t: T) -> &T; }
struct S;
impl Foo<u32> for S { <|> }"#,
r#"
trait Foo<T> { fn foo(&self, t: T) -> &T; }
struct S;
impl Foo<u32> for S {
fn foo(&self, t: u32) -> &u32 {
${0:todo!()}
}
}"#,
);
}
#[test]
fn fill_in_type_params_2() {
check_assist(
add_missing_impl_members,
r#"
trait Foo<T> { fn foo(&self, t: T) -> &T; }
struct S;
impl<U> Foo<U> for S { <|> }"#,
r#"
trait Foo<T> { fn foo(&self, t: T) -> &T; }
struct S;
impl<U> Foo<U> for S {
fn foo(&self, t: U) -> &U {
${0:todo!()}
}
}"#,
);
}
#[test]
2020-02-29 14:24:40 -06:00
fn test_cursor_after_empty_impl_def() {
check_assist(
add_missing_impl_members,
r#"
trait Foo { fn foo(&self); }
struct S;
impl Foo for S {}<|>"#,
r#"
trait Foo { fn foo(&self); }
struct S;
impl Foo for S {
fn foo(&self) {
${0:todo!()}
}
}"#,
)
}
2019-12-30 06:53:43 -06:00
#[test]
fn test_qualify_path_1() {
check_assist(
add_missing_impl_members,
r#"
2019-12-30 06:53:43 -06:00
mod foo {
pub struct Bar;
2019-12-30 06:53:43 -06:00
trait Foo { fn foo(&self, bar: Bar); }
}
struct S;
impl foo::Foo for S { <|> }"#,
r#"
2019-12-30 06:53:43 -06:00
mod foo {
pub struct Bar;
2019-12-30 06:53:43 -06:00
trait Foo { fn foo(&self, bar: Bar); }
}
struct S;
impl foo::Foo for S {
fn foo(&self, bar: foo::Bar) {
${0:todo!()}
}
}"#,
2019-12-30 06:53:43 -06:00
);
}
2020-01-01 16:08:22 -06:00
#[test]
fn test_qualify_path_generic() {
check_assist(
add_missing_impl_members,
r#"
2020-01-01 16:08:22 -06:00
mod foo {
pub struct Bar<T>;
trait Foo { fn foo(&self, bar: Bar<u32>); }
}
struct S;
impl foo::Foo for S { <|> }"#,
r#"
2020-01-01 16:08:22 -06:00
mod foo {
pub struct Bar<T>;
trait Foo { fn foo(&self, bar: Bar<u32>); }
}
struct S;
impl foo::Foo for S {
fn foo(&self, bar: foo::Bar<u32>) {
${0:todo!()}
}
}"#,
2020-01-01 16:08:22 -06:00
);
}
#[test]
fn test_qualify_path_and_substitute_param() {
check_assist(
add_missing_impl_members,
r#"
2020-01-01 16:08:22 -06:00
mod foo {
pub struct Bar<T>;
trait Foo<T> { fn foo(&self, bar: Bar<T>); }
}
struct S;
impl foo::Foo<u32> for S { <|> }"#,
r#"
2020-01-01 16:08:22 -06:00
mod foo {
pub struct Bar<T>;
trait Foo<T> { fn foo(&self, bar: Bar<T>); }
}
struct S;
impl foo::Foo<u32> for S {
fn foo(&self, bar: foo::Bar<u32>) {
${0:todo!()}
}
}"#,
2020-01-01 16:08:22 -06:00
);
}
#[test]
fn test_substitute_param_no_qualify() {
// when substituting params, the substituted param should not be qualified!
check_assist(
add_missing_impl_members,
r#"
mod foo {
trait Foo<T> { fn foo(&self, bar: T); }
pub struct Param;
}
struct Param;
struct S;
impl foo::Foo<Param> for S { <|> }"#,
r#"
mod foo {
trait Foo<T> { fn foo(&self, bar: T); }
pub struct Param;
}
struct Param;
struct S;
impl foo::Foo<Param> for S {
fn foo(&self, bar: Param) {
${0:todo!()}
}
}"#,
);
}
2020-01-01 16:08:22 -06:00
#[test]
fn test_qualify_path_associated_item() {
check_assist(
add_missing_impl_members,
r#"
2020-01-01 16:08:22 -06:00
mod foo {
pub struct Bar<T>;
impl Bar<T> { type Assoc = u32; }
trait Foo { fn foo(&self, bar: Bar<u32>::Assoc); }
}
struct S;
impl foo::Foo for S { <|> }"#,
r#"
2020-01-01 16:08:22 -06:00
mod foo {
pub struct Bar<T>;
2020-01-03 12:58:56 -06:00
impl Bar<T> { type Assoc = u32; }
2020-01-01 16:08:22 -06:00
trait Foo { fn foo(&self, bar: Bar<u32>::Assoc); }
}
struct S;
impl foo::Foo for S {
fn foo(&self, bar: foo::Bar<u32>::Assoc) {
${0:todo!()}
}
}"#,
2020-01-01 16:08:22 -06:00
);
}
#[test]
fn test_qualify_path_nested() {
check_assist(
add_missing_impl_members,
r#"
2020-01-01 16:08:22 -06:00
mod foo {
pub struct Bar<T>;
pub struct Baz;
trait Foo { fn foo(&self, bar: Bar<Baz>); }
}
struct S;
impl foo::Foo for S { <|> }"#,
r#"
2020-01-01 16:08:22 -06:00
mod foo {
pub struct Bar<T>;
pub struct Baz;
trait Foo { fn foo(&self, bar: Bar<Baz>); }
}
struct S;
impl foo::Foo for S {
fn foo(&self, bar: foo::Bar<foo::Baz>) {
${0:todo!()}
}
}"#,
2020-01-01 16:08:22 -06:00
);
}
#[test]
fn test_qualify_path_fn_trait_notation() {
check_assist(
add_missing_impl_members,
r#"
2020-01-01 16:08:22 -06:00
mod foo {
pub trait Fn<Args> { type Output; }
trait Foo { fn foo(&self, bar: dyn Fn(u32) -> i32); }
}
struct S;
impl foo::Foo for S { <|> }"#,
r#"
2020-01-01 16:08:22 -06:00
mod foo {
pub trait Fn<Args> { type Output; }
trait Foo { fn foo(&self, bar: dyn Fn(u32) -> i32); }
}
struct S;
impl foo::Foo for S {
fn foo(&self, bar: dyn Fn(u32) -> i32) {
${0:todo!()}
}
}"#,
2020-01-01 16:08:22 -06:00
);
}
#[test]
fn test_empty_trait() {
check_assist_not_applicable(
add_missing_impl_members,
r#"
trait Foo;
struct S;
impl Foo for S { <|> }"#,
)
}
#[test]
fn test_ignore_unnamed_trait_members_and_default_methods() {
check_assist_not_applicable(
add_missing_impl_members,
r#"
trait Foo {
fn (arg: u32);
fn valid(some: u32) -> bool { false }
}
struct S;
impl Foo for S { <|> }"#,
)
}
#[test]
fn test_with_docstring_and_attrs() {
check_assist(
add_missing_impl_members,
r#"
#[doc(alias = "test alias")]
trait Foo {
/// doc string
type Output;
#[must_use]
fn foo(&self);
}
struct S;
impl Foo for S {}<|>"#,
r#"
#[doc(alias = "test alias")]
trait Foo {
/// doc string
type Output;
#[must_use]
fn foo(&self);
}
struct S;
impl Foo for S {
2020-05-19 18:53:21 -05:00
$0type Output;
fn foo(&self) {
todo!()
}
}"#,
)
}
2019-03-23 10:06:25 -05:00
#[test]
fn test_default_methods() {
check_assist(
add_missing_default_members,
r#"
2019-03-23 10:06:25 -05:00
trait Foo {
type Output;
const CONST: usize = 42;
2019-03-23 10:06:25 -05:00
fn valid(some: u32) -> bool { false }
fn foo(some: u32) -> bool;
}
struct S;
impl Foo for S { <|> }"#,
r#"
2019-03-23 10:06:25 -05:00
trait Foo {
type Output;
const CONST: usize = 42;
2019-03-23 10:06:25 -05:00
fn valid(some: u32) -> bool { false }
fn foo(some: u32) -> bool;
}
struct S;
impl Foo for S {
2020-05-19 18:53:21 -05:00
$0fn valid(some: u32) -> bool { false }
2020-05-13 08:06:42 -05:00
}"#,
)
}
#[test]
fn test_generic_single_default_parameter() {
check_assist(
add_missing_impl_members,
r#"
trait Foo<T = Self> {
fn bar(&self, other: &T);
}
struct S;
impl Foo for S { <|> }"#,
r#"
trait Foo<T = Self> {
fn bar(&self, other: &T);
}
struct S;
impl Foo for S {
fn bar(&self, other: &Self) {
${0:todo!()}
2020-05-13 08:06:42 -05:00
}
}"#,
)
}
#[test]
fn test_generic_default_parameter_is_second() {
check_assist(
add_missing_impl_members,
r#"
trait Foo<T1, T2 = Self> {
fn bar(&self, this: &T1, that: &T2);
}
struct S<T>;
impl Foo<T> for S<T> { <|> }"#,
r#"
trait Foo<T1, T2 = Self> {
fn bar(&self, this: &T1, that: &T2);
}
struct S<T>;
impl Foo<T> for S<T> {
fn bar(&self, this: &T, that: &Self) {
${0:todo!()}
2020-05-13 08:06:42 -05:00
}
}"#,
)
}
#[test]
fn test_assoc_type_bounds_are_removed() {
check_assist(
add_missing_impl_members,
r#"
trait Tr {
type Ty: Copy + 'static;
}
impl Tr for ()<|> {
}"#,
r#"
trait Tr {
type Ty: Copy + 'static;
}
impl Tr for () {
$0type Ty;
}"#,
2019-03-23 10:06:25 -05:00
)
}
}