Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Proc macro to generate "AsRef" traits #112

Open
azriel91 opened this issue Mar 12, 2020 · 1 comment
Open

Proc macro to generate "AsRef" traits #112

azriel91 opened this issue Mar 12, 2020 · 1 comment
Labels
M: code Code maintenance and quality.
Milestone

Comments

@azriel91
Copy link
Owner

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:

  • 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.
@azriel91 azriel91 added the M: code Code maintenance and quality. label Mar 12, 2020
@azriel91 azriel91 added this to the Backlog milestone Mar 12, 2020
@azriel91
Copy link
Owner Author

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

unassigned @azriel91

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
M: code Code maintenance and quality.
Projects
None yet
Development

No branches or pull requests

1 participant