Skip to content

Commit ccb3e6a

Browse files
feature: add the "Recursively add derive" assist
This introduces a new assist that adds the derive attributes from a struct or enum to the types of its fields, recursively. It is recursive in the sense that the fields of field types are also considered. The derive attributes will be copied over if the field type meets the following criteria: * It resides within the same crate as the "top-level" type, to avoid editing the crate registry. * It does not already have the same derive attribute. * It does not have a manual implementation of the trait. The last criteria is a bit of a guess since it isn't possible to know what trait implementation(s) a derive macro generates. If a trait has the same name as the derive macro and the top-level type (which already has the derive attribute) implements it, it'll be used to check for manual impls. This seems to work well in practice.
1 parent 49080f2 commit ccb3e6a

File tree

5 files changed

+1072
-0
lines changed

5 files changed

+1072
-0
lines changed

crates/hir/src/lib.rs

Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -409,6 +409,20 @@ impl ModuleDef {
409409
acc
410410
}
411411

412+
pub fn as_trait(self) -> Option<Trait> {
413+
match self {
414+
ModuleDef::Trait(it) => Some(it),
415+
_ => None,
416+
}
417+
}
418+
419+
pub fn as_macro(self) -> Option<Macro> {
420+
match self {
421+
ModuleDef::Macro(it) => Some(it),
422+
_ => None,
423+
}
424+
}
425+
412426
pub fn as_def_with_body(self) -> Option<DefWithBody> {
413427
match self {
414428
ModuleDef::Function(it) => Some(it.into()),
@@ -2990,6 +3004,13 @@ impl ItemInNs {
29903004
}
29913005
}
29923006

3007+
pub fn as_macro(self) -> Option<Macro> {
3008+
match self {
3009+
ItemInNs::Types(_) | ItemInNs::Values(_) => None,
3010+
ItemInNs::Macros(id) => Some(id),
3011+
}
3012+
}
3013+
29933014
/// Returns the crate defining this item (or `None` if `self` is built-in).
29943015
pub fn krate(&self, db: &dyn HirDatabase) -> Option<Crate> {
29953016
match self {

crates/hir/src/semantics.rs

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -99,6 +99,13 @@ impl PathResolution {
9999
PathResolution::SelfType(impl_def) => Some(TypeNs::SelfType((*impl_def).into())),
100100
}
101101
}
102+
103+
pub fn as_module_def(&self) -> Option<ModuleDef> {
104+
match self {
105+
PathResolution::Def(it) => Some(*it),
106+
_ => None,
107+
}
108+
}
102109
}
103110

104111
#[derive(Debug)]

0 commit comments

Comments
 (0)