What is the idiomatic way to transform a function

Function to Transform

fn index(foo: Foo) {
    foo.bar();
}

After Transformation

fn index(foo: Foo) -> Pin<Box<dyn Future<Output = ()>>> {
    Box::pin(async move {
        foo.bar();
    });
}

Macro will be
custom_macro!(index);

How the macro will be? Really confuse.
Thank you

This is impossible, since macro operate only on explicitly passed tokens, it can't find the function by name.

1 Like

Thank you @Cerber-Ursi
You save my time. Already wasted hours to debug.
Can you please give me any alternative for this ?

How about writing a normal macro, and then doing:

custom_macro!{
    fn index(foo: Foo) {
          foo.bar();
     }
}

What do you need to do, at the higher level? Currently, it's unclear why you can't just write the function in the second way from the start.

2 Likes

Hi @Cerber-Ursi @RedDocMD

What about this

let callback = custom_macro!({
  |foo: Foo| {
    foo.bar();
  }
})

Transform Callback Into

|foo: Foo| -> Pin<Box<dyn Future<Output = ()>>> {
  Box::pin(async move {
      foo.bar();
  })
}

Macro which I tried but does not work

($body:block) => {{
    let body = stringify!($body);
    let parse_body = parse_str::<Block>(body).unwrap();
    // println!("{:#?}", parse_body);

    |_: crate::Foo| -> Pin<Box<dyn Future<Output = ()>>> {
        Box::pin(async move {
            parse_body;
        })
    }
}};

Why do you try to go through the stringified tokens? This code, which is an exact description of the changes you've shown, should work:

($body:block) => {{
    |_: crate::Foo| -> Pin<Box<dyn Future<Output = ()>>> {
        Box::pin(async move {
            $body
        })
    }
}};
1 Like

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.