rust-custom-derive
rust-custom-derive copied to clipboard
Deriving non-trait methods in newtype_derive?
I'm working on a proposal to move to newtypes for a crate which makes use of type aliases, and one thing that's come up (see rust-bio/rust-bio#69) is the need to have a way to automatically provide impl's of newtype methods that aren't a part of any traits (e.g. Vec::len or Vec::shrink_to_fit).
I've sketched out a super simple macro to do this (https://github.com/rust-bio/rust-bio/issues/69#issuecomment-232136748), but we're also talking about using newtype_derive for some of the traits we'd like to make available (Index, for one).
Does it seem like it's in scope to provide this functionality as part of newtype_derive? I had pictured something along the lines of:
custom_derive! {
#[derive(
NewtypeFn(len -> usize),
NewtypeFnMut(shrink_to_fit),
NewtypeIndex(u8))]
pub struct NewTypeFromVec(Vec<u8>);
};
I'm not sure about how well it would cover trait implementations like Iterator (perhaps something analogous to Index?), although that'd be something I would be interested in exploring as well.
Thoughts?
The issue with piecemeal forwarding of methods is that you're going to run out of recursion space really fast. I actually did something similar-sounding with https://github.com/DanielKeep/rust-numeric-float. In particular, see src/macros/std_impls.rs for NumericImpl!, which is invoked using custom_derive!.
Also, I'm a little leery of trying to define fully general forwarding macros, because it's just such a mess. There's dealing with the many forms of self, dealing with static functions, generics, where clauses, etc., etc.... it's not much work to write a quick macro that deals with the particular cases you care about, but likely a monumental effort to make it work well for everyone, so I'd prefer to pass for now. Also, I'm still a little burnt out from the horror that was parsing generics in stable macros...
But, hey, if you come up with a macro that works well in (more or less) all cases, said macro can just be dropped into the crate. Hooray for composition! :P