Hey all, I'm looking into https://github.com/rust-analyzer/rust-analyzer/issues/3766. I've got a basic version working that creates a Fom impl for the variant your cursor is over iff it's a tuple variant with one element. I thought it best to also disallow the assist if there's already a From impl for the enum with the matching type. Checking for the type is straight forward:
let e: hir::Enum = sema.to_def(&variant.parent_enum())?; let e_ty = e.ty(sema.db); let impls = ImplDef::all_in_crate(sema.db, krate).iter().filter(|i| i.target_ty(sema.db) == e_ty);
I'm a bit more stuck with matching the trait up. I tried a couple of things but to no avail:
ImplDef::target_traitmethod but that gives a
TypeRef. There doesn't seem to be much I can do with a
TypeReflooking at the API docs. I tried using similar logic to target_ty to resolve it to an actual
Typebut it couldn't find it.
ast::Pathand then use
Semantics::resolve_pathon that but it (understandably) doesn't find the path as the node isn't derived from the instance of semantics
ImportsLocatorwhich seems to take a string to search for and it finds
ModuleDefs (which could be a trait) which match. Although
Fromshould be in scope I thought this may turn something up, sadly there are no results at all. I note that the tests of auto_import define all the modules they import from, so perhaps this is expected?
Any pointers would be appreciated :)
Although From should be in scope I thought this may turn something up, sadly there are no results at all. I note that the tests of auto_import define all the modules they import from, so perhaps this is expected?
yes, unit tests only have what you define, they don't have std.
ImportsLocator is probably not the right thing to use here though. I think you should be able to build a HIR
::core::convert::From and resolve that using
semantics.scope(..).resolve_hir_path() to get the trait
ImplDef needs a method to get the resolved implemented trait; the way to get that is
instead of going through impls yourself, you could also use the trait solver. that would be the 'proper' way, but needs some more API plumbing... there's actually a special case implemented as
Interesting, thanks. I'll give those ideas ago and see if I can get either the naiive or the proper way working :)