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 3 commits 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
295 changes: 295 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,295 @@
use ide_db::{famous_defs::FamousDefs, traits::resolve_target_trait};
use syntax::{
ast::{self, AstNode, HasName, edit_in_place::Indent, make},
syntax_editor::Position,
};

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

// Assist: generate_asref_impl_from_borrow
//
// Generate `AsRef` implement from `Borrow`.
//
// ```
// //- minicore: borrow, as_ref
// use core::borrow::Borrow;
// struct Foo<T>(T);
//
// impl<T> $0Borrow<T> for Foo<T> {
// fn borrow(&self) -> &T {
// &self.0
// }
// }
// ```
// ->
// ```
// use core::borrow::Borrow;
// 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`.
//
// ```
// //- minicore: borrow_mut, as_mut
// use core::borrow::BorrowMut;
// struct Foo<T>(T);
//
// impl<T> $0BorrowMut<T> for Foo<T> {
// fn borrow_mut(&mut self) -> &mut T {
// &mut self.0
// }
// }
// ```
// ->
// ```
// use core::borrow::BorrowMut;
// 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()?)?;
let path = ast::PathType::cast(impl_.trait_()?.syntax().clone())?;
let indent = impl_.indent_level();

let name = path.path()?.segment()?.name_ref()?;
let scope = ctx.sema.scope(path.syntax())?;
let famous = FamousDefs(&ctx.sema, scope.krate());
let trait_ = resolve_target_trait(&ctx.sema, &impl_)?;

let (target_name, target_method_name) = out_trait(famous, trait_)?;

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| {
let mut editor = edit.make_editor(impl_.syntax());
editor.replace(name.syntax(), make::name_ref(target_name).syntax().clone_for_update());

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

editor.insert_all(
Position::after(impl_.syntax()),
vec![
make::tokens::whitespace(&format!("\n\n{indent}")).into(),
impl_.syntax().clone_for_update().into(),
],
);

if let Some(cap) = ctx.config.snippet_cap {
edit.add_tabstop_before(cap, impl_);
}

edit.add_file_edits(ctx.vfs_file_id(), editor);
},
)
}

fn out_trait(
famous: FamousDefs<'_, '_>,
trait_: hir::Trait,
) -> Option<(&'static str, &'static str)> {
if trait_ == famous.core_borrow_Borrow()? {
Some(("AsRef", "as_ref"))
} else if trait_ == famous.core_borrow_BorrowMut()? {
Some(("AsMut", "as_mut"))
} else {
None
}
}

#[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#"
//- minicore: borrow, as_ref
use core::borrow::Borrow;
struct Foo<T>(T);

impl<T> $0Borrow<T> for Foo<T> {
fn borrow(&self) -> &T {
&self.0
}
}
"#,
r#"
use core::borrow::Borrow;
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#"
//- minicore: borrow_mut, as_mut
use core::borrow::BorrowMut;
struct Foo<T>(T);

impl<T> $0BorrowMut<T> for Foo<T> {
fn borrow_mut(&mut self) -> &mut T {
&mut self.0
}
}
"#,
r#"
use core::borrow::BorrowMut;
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#"
//- minicore: borrow, as_ref
use core::borrow::Borrow;
struct Foo<T>(T);

#[cfg(feature = "foo")]
impl<T> $0Borrow<T> for Foo<T> {
/// some docs
fn borrow(&self) -> &T {
&self.0
}
}
"#,
r#"
use core::borrow::Borrow;
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#"
//- minicore: borrow, as_ref
mod foo {
mod bar {
use core::borrow::Borrow;
struct Foo<T>(T);

impl<T> $0Borrow<T> for Foo<T> {
fn borrow(&self) -> &T {
&self.0
}
}
}
}
"#,
r#"
mod foo {
mod bar {
use core::borrow::Borrow;
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
68 changes: 68 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,74 @@ fn foo<T: Copy + Clone>() { }
)
}

#[test]
fn doctest_generate_asref_impl_from_borrow() {
check_doc_test(
"generate_asref_impl_from_borrow",
r#####"
//- minicore: borrow, as_ref
use core::borrow::Borrow;
struct Foo<T>(T);

impl<T> $0Borrow<T> for Foo<T> {
fn borrow(&self) -> &T {
&self.0
}
}
"#####,
r#####"
use core::borrow::Borrow;
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#####"
//- minicore: borrow_mut, as_mut
use core::borrow::BorrowMut;
struct Foo<T>(T);

impl<T> $0BorrowMut<T> for Foo<T> {
fn borrow_mut(&mut self) -> &mut T {
&mut self.0
}
}
"#####,
r#####"
use core::borrow::BorrowMut;
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
Loading