azriel91 / autexousious

Main repository for Will -- 2.5D moddable action adventure game
https://azriel.im/will
Apache License 2.0
44 stars 3 forks source link

Proc macro to generate "AsRef" traits #112

Open azriel91 opened 4 years ago

azriel91 commented 4 years ago

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 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:

azriel91 commented 4 years ago

In GitLab by @azriel91 on Jul 26, 2019, 09:33

unassigned @azriel91