Skip to content

Commit

Permalink
feature: add the "Recursively add derive" assist
Browse files Browse the repository at this point in the history
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.
  • Loading branch information
IvarWithoutBones committed Sep 17, 2024
1 parent aed2be6 commit f6b20fd
Show file tree
Hide file tree
Showing 6 changed files with 1,151 additions and 0 deletions.
21 changes: 21 additions & 0 deletions crates/hir/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -409,6 +409,20 @@ impl ModuleDef {
acc
}

pub fn as_trait(self) -> Option<Trait> {
match self {
ModuleDef::Trait(it) => Some(it),
_ => None,
}
}

pub fn as_macro(self) -> Option<Macro> {
match self {
ModuleDef::Macro(it) => Some(it),
_ => None,
}
}

pub fn as_def_with_body(self) -> Option<DefWithBody> {
match self {
ModuleDef::Function(it) => Some(it.into()),
Expand Down Expand Up @@ -2996,6 +3010,13 @@ impl ItemInNs {
}
}

pub fn as_macro(self) -> Option<Macro> {
match self {
ItemInNs::Types(_) | ItemInNs::Values(_) => None,
ItemInNs::Macros(id) => Some(id),
}
}

/// Returns the crate defining this item (or `None` if `self` is built-in).
pub fn krate(&self, db: &dyn HirDatabase) -> Option<Crate> {
match self {
Expand Down
7 changes: 7 additions & 0 deletions crates/hir/src/semantics.rs
Original file line number Diff line number Diff line change
Expand Up @@ -99,6 +99,13 @@ impl PathResolution {
PathResolution::SelfType(impl_def) => Some(TypeNs::SelfType((*impl_def).into())),
}
}

pub fn as_module_def(&self) -> Option<ModuleDef> {
match self {
PathResolution::Def(it) => Some(*it),
_ => None,
}
}
}

#[derive(Debug)]
Expand Down
Loading

0 comments on commit f6b20fd

Please sign in to comment.