Rust - derive macro generate struct impl based on another trait (procedurally)

I have a struct:

struct Foo {
    i: i32,

I have a trait:

trait FooTrait {
    fn foo(&self);

I want to create a derive macro, which, when attached to the struct, generates an impl like below:

impl FooTrait for Foo {
    fn foo(&self) {
        println!("generated code: {}", self.i);

When I attempted to achieve this, I'm facing the blocker that my derive macro doesn't seem to have a way to know the token stream of FooTrait, where I need to iterate through the methods of FooTrait, and generate the implementation for each trait method based on Foo!

How could I possibly achieve that?

NOTE: to make it clearer, this question is not really about how I simply use quote! to quote the trait impl and spell out foo directly - the hard part is that I want to procedurally iterate through the methods of FooTrait, and generate some boilerplate code for each trait method.

Looks no way to me. Derive macro handle tokens, not AST. You may need more powerful tool than derive macro, for example rustc drivers.

Derive macro doesn't have access to the trait definition, it only receives the struct it is applied on. So what do you want to iterate through?

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.