Skip to content

Add ide-assist; Generate AsRef impl from Borrow #20065

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
251 changes: 251 additions & 0 deletions crates/ide-assists/src/handlers/generate_asref_impl_from_borrow.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,251 @@
use syntax::ast::edit_in_place::Indent;
use syntax::ast::make;
use syntax::ast::{self, AstNode, HasName};
use syntax::ted;
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

As this is a new assist and relatively simple, could this be implemented with new SyntaxEditor infra?


use crate::{AssistContext, AssistId, Assists};

// Assist: generate_asref_impl_from_borrow
//
// Generate `AsRef` implement from `Borrow`.
//
// ```
// struct Foo<T>(T);
//
// impl<T> $0Borrow<T> for Foo<T> {
// fn borrow(&self) -> &T {
// &self.0
// }
// }
// ```
// ->
// ```
// struct Foo<T>(T);
//
// $0impl<T> AsRef<T> for Foo<T> {
// fn as_ref(&self) -> &T {
// &self.0
// }
// }
//
// impl<T> Borrow<T> for Foo<T> {
// fn borrow(&self) -> &T {
// &self.0
// }
// }
// ```
//
// ---
// Generate `AsMut` implement from `BorrowMut`.
//
// ```
// struct Foo<T>(T);
//
// impl<T> $0BorrowMut<T> for Foo<T> {
// fn borrow_mut(&mut self) -> &mut T {
// &mut self.0
// }
// }
// ```
// ->
// ```
// struct Foo<T>(T);
//
// $0impl<T> AsMut<T> for Foo<T> {
// fn as_mut(&mut self) -> &mut T {
// &mut self.0
// }
// }
//
// impl<T> BorrowMut<T> for Foo<T> {
// fn borrow_mut(&mut self) -> &mut T {
// &mut self.0
// }
// }
// ```
pub(crate) fn generate_asref_impl_from_borrow(
acc: &mut Assists,
ctx: &AssistContext<'_>,
) -> Option<()> {
let ty = ctx.find_node_at_offset::<ast::Type>()?;
let impl_ = ast::Impl::cast(ty.syntax().parent()?)?.clone_for_update();
let path = ast::PathType::cast(impl_.trait_()?.syntax().clone())?;
let indent = impl_.indent_level();

let name = path.path()?.segment()?.name_ref()?;

let (target_name, target_method_name) = match &*name.text() {
"Borrow" => ("AsRef", "as_ref"),
"BorrowMut" => ("AsMut", "as_mut"),
_ => return None,
};
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This would be better semantically like:

let impl_ = ctx.find_node_at_offset::<ast::Impl>()?;
let src_type = impl_.self_ty()?;
let ast_trait = impl_.trait_()?;
let module = ctx.sema.scope(impl_.syntax())?.module();
let trait_ = resolve_target_trait(&ctx.sema, &impl_)?;
if trait_ != FamousDefs(&ctx.sema, module.krate()).core_convert_Into()? {
return None;
}

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Using strings can be easily implemented without adding new methods to FamousDefs

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Yes, it's easier but might be incorrect, like if there are other traits with the same names.


let method = impl_.assoc_item_list()?.assoc_items().find_map(|it| match it {
ast::AssocItem::Fn(f) => Some(f),
_ => None,
})?;

let target = impl_.syntax().text_range();
acc.add(
AssistId::generate("generate_asref_impl_from_borrow"),
format!("Generate `{target_name}` implement from `{name}`"),
target,
|edit| {
ted::replace(name.syntax(), make::name_ref(target_name).syntax().clone_for_update());

if let Some(name) = method.name() {
ted::replace(
name.syntax(),
make::name(target_method_name).syntax().clone_for_update(),
);
}

edit.insert(target.start(), format!("$0{impl_}\n\n{indent}"));
},
)
}

#[cfg(test)]
mod tests {
use crate::tests::check_assist;

use super::*;

#[test]
fn test_generate_asref_impl_from_borrow() {
check_assist(
generate_asref_impl_from_borrow,
r#"
struct Foo<T>(T);

impl<T> $0Borrow<T> for Foo<T> {
fn borrow(&self) -> &T {
&self.0
}
}
"#,
r#"
struct Foo<T>(T);

$0impl<T> AsRef<T> for Foo<T> {
fn as_ref(&self) -> &T {
&self.0
}
}

impl<T> Borrow<T> for Foo<T> {
fn borrow(&self) -> &T {
&self.0
}
}
"#,
);
}

#[test]
fn test_generate_asmut_impl_from_borrow_mut() {
check_assist(
generate_asref_impl_from_borrow,
r#"
struct Foo<T>(T);

impl<T> $0BorrowMut<T> for Foo<T> {
fn borrow_mut(&mut self) -> &mut T {
&mut self.0
}
}
"#,
r#"
struct Foo<T>(T);

$0impl<T> AsMut<T> for Foo<T> {
fn as_mut(&mut self) -> &mut T {
&mut self.0
}
}

impl<T> BorrowMut<T> for Foo<T> {
fn borrow_mut(&mut self) -> &mut T {
&mut self.0
}
}
"#,
);
}

#[test]
fn test_generate_asref_impl_from_borrow_attributes() {
check_assist(
generate_asref_impl_from_borrow,
r#"
struct Foo<T>(T);

#[cfg(feature = "foo")]
impl<T> $0Borrow<T> for Foo<T> {
/// some docs
fn borrow(&self) -> &T {
&self.0
}
}
"#,
r#"
struct Foo<T>(T);

$0#[cfg(feature = "foo")]
impl<T> AsRef<T> for Foo<T> {
/// some docs
fn as_ref(&self) -> &T {
&self.0
}
}

#[cfg(feature = "foo")]
impl<T> Borrow<T> for Foo<T> {
/// some docs
fn borrow(&self) -> &T {
&self.0
}
}
"#,
);
}

#[test]
fn test_generate_asref_impl_from_borrow_indent() {
check_assist(
generate_asref_impl_from_borrow,
r#"
mod foo {
mod bar {
struct Foo<T>(T);

impl<T> $0Borrow<T> for Foo<T> {
fn borrow(&self) -> &T {
&self.0
}
}
}
}
"#,
r#"
mod foo {
mod bar {
struct Foo<T>(T);

$0impl<T> AsRef<T> for Foo<T> {
fn as_ref(&self) -> &T {
&self.0
}
}

impl<T> Borrow<T> for Foo<T> {
fn borrow(&self) -> &T {
&self.0
}
}
}
}
"#,
);
}
}
2 changes: 2 additions & 0 deletions crates/ide-assists/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -153,6 +153,7 @@ mod handlers {
mod flip_comma;
mod flip_or_pattern;
mod flip_trait_bound;
mod generate_asref_impl_from_borrow;
mod generate_constant;
mod generate_default_from_enum_variant;
mod generate_default_from_new;
Expand Down Expand Up @@ -302,6 +303,7 @@ mod handlers {
generate_impl::generate_impl,
generate_impl::generate_trait_impl,
generate_is_empty_from_len::generate_is_empty_from_len,
generate_asref_impl_from_borrow::generate_asref_impl_from_borrow,
generate_mut_trait_impl::generate_mut_trait_impl,
generate_new::generate_new,
generate_trait_from_impl::generate_trait_from_impl,
Expand Down
62 changes: 62 additions & 0 deletions crates/ide-assists/src/tests/generated.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1311,6 +1311,68 @@ fn foo<T: Copy + Clone>() { }
)
}

#[test]
fn doctest_generate_asref_impl_from_borrow() {
check_doc_test(
"generate_asref_impl_from_borrow",
r#####"
struct Foo<T>(T);

impl<T> $0Borrow<T> for Foo<T> {
fn borrow(&self) -> &T {
&self.0
}
}
"#####,
r#####"
struct Foo<T>(T);

$0impl<T> AsRef<T> for Foo<T> {
fn as_ref(&self) -> &T {
&self.0
}
}

impl<T> Borrow<T> for Foo<T> {
fn borrow(&self) -> &T {
&self.0
}
}
"#####,
)
}

#[test]
fn doctest_generate_asref_impl_from_borrow_1() {
check_doc_test(
"generate_asref_impl_from_borrow",
r#####"
struct Foo<T>(T);

impl<T> $0BorrowMut<T> for Foo<T> {
fn borrow_mut(&mut self) -> &mut T {
&mut self.0
}
}
"#####,
r#####"
struct Foo<T>(T);

$0impl<T> AsMut<T> for Foo<T> {
fn as_mut(&mut self) -> &mut T {
&mut self.0
}
}

impl<T> BorrowMut<T> for Foo<T> {
fn borrow_mut(&mut self) -> &mut T {
&mut self.0
}
}
"#####,
)
}

#[test]
fn doctest_generate_constant() {
check_doc_test(
Expand Down