In order to share common code, we can create a trait for each original type, impl Deref and DerefMut, as well as accessor methods for each pub field.
Consumers of those types will depend on the trait instead of the type, so that the inner type can be swapped out easily.
This pattern has been done many times, so writing a proc macro to generate the trait will reduce a lot of manual work.
#[derive(Like)]
pub struct Something { .. }
// auto generates
pub trait SomethingLike {
fn something(&self) -> &Something;
}
// Would like to generate a proc macro crate for this:
#[proc_macro_derive(SomethingLike)]
fn something_like(token_stream: TokenStream) -> TokenStream { .. }
// -----------
// somewhere else:
#[derive(SomethingLike)] // <------ Would like the crate for this to be generated
pub struct SpecialSomething {
pub something: Something,
}
// auto generated:
impl SomethingLike for SpecialSomething {
fn something(&self) -> &Something { &self.something }
}
// impl Deref and DerefMut, etc.
Alternatives:
Write a cargo binary that parses syntax and outputs the crate
Write a naive proc macro crate that takes in the name of the Something. Would prefer to have Something's syntax tree, because wanted to generate accessor methods for each of the pub fields
Use reflection crate so that the syntax tree can be queried at runtime, get the proc macro crate to depend on something_crate, invoke methods on Something to figure out the AST, then generate the proc macro.
In GitLab by @azriel91 on Apr 11, 2019, 19:14
In order to share common code, we can create a trait for each original type, impl
Deref
andDerefMut
, as well as accessor methods for eachpub
field.Consumers of those types will depend on the trait instead of the type, so that the inner type can be swapped out easily.
This pattern has been done many times, so writing a proc macro to generate the trait will reduce a lot of manual work.
Alternatives:
Something
. Would prefer to haveSomething
's syntax tree, because wanted to generate accessor methods for each of the pub fieldsreflection
crate so that the syntax tree can be queried at runtime, get the proc macro crate to depend onsomething_crate
, invoke methods onSomething
to figure out the AST, then generate the proc macro.