Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to make sure that a Rust attribute proc macro runs before the compiler tries parsing the item?

I’m trying to make a macro that adds some extra syntax to struct type declarations.
For simplicity, here’s a toy example: a macro that replaces "function call"-style type declarations with normal ones.

#[my_macro]
struct Point {
  x: LiteralType("f32"),
  y: LiteralType("f32"),
}

should turn into

struct Point {
  x: f32,
  y: f32,
}

From the output of my code and cargo expand, I can tell that my code produces the correct syntax.
However, before that happens, the compiler has already tried parsing the LiteralType("f32") syntax, failed and emitted an error saying as much, and now the whole build fails.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

I think I need to somehow force the compiler to run my macro’s code to completion before trying to parse it according to the regular Rust rules. I think it might be possible to do using functional macros, because those can accept syntax that’s much more unusual, but I’d prefer to stick with attribute macros because those provide a secondary input for attributes.

>Solution :

You cannot do that with attribute macros, they always validate their items.

But as you said, you can do that with function-like macros.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading