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

Conversation

A4-Tacks
Copy link
Contributor

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
    }
}

@rustbot rustbot added the S-waiting-on-review Status: Awaiting review from the assignee but also interested parties. label Jun 23, 2025
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?

"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;
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
S-waiting-on-review Status: Awaiting review from the assignee but also interested parties.
Projects
None yet
Development

Successfully merging this pull request may close these issues.

3 participants