How to add code to AST of project, then compile result, without macros

Hello,

I would like to create a cargo plugin that adds functionnality at the begining and end
of every function in a project, then compiles the project, and runs it.

My idea is to:

  • Get the AST of a cargo project
  • Add functionnality at beggining and end of functions with quote
  • Compile the AST
    (The tool's purpose would be to insert code for instrumental profiling if that matters,
    so running cargo profile -> adds code then runs it)

I saw that syn can get the AST information of a file, and quote can manipulate that AST, but
I didn't find anything for compiling an AST.

Is it possible to do this without using macros? I would like this tool to
not have any modification of source code.

What do you mean you would like to not have any modification to source code? Macros do not modify the source code. You could enable the macro based on some cfg value, so that the macros only add the functionality when you are profiling the code and not in release mode fore example.

Why is adding macros a no-go for you?

You can use syn to modify the source and write it to an intermediate build directory and then compile that instead. Outside of that or shipping your own version of rustc I'm not aware of any mechanism for this sort of compilation hooks.

I want to create a command that compiles the program and adds timing events to all functions, without not have to add a macro on each of them.
The ideal use case is to create a cargo-profile binary, used like:
cargo profile <- In a rust crate

I found out that compiler plugins are deprecated now and i'm looking into the rustc_driver and rustc_interface libraries.

I'm looking into rustc_driver and rustc_interface to see if I can modify the compilation there, if that doesn't work out I'll try the syn crate and an intermediate compilation step :+1:
Do you know if the syn crate can modify source code after macro expansions?
(If macros call functions, I would want to add profiling information to them too)

Do you know if the syn crate can modify source code after macro expansions?

No, not on its own; macros can execute arbitrary code so they actually require an additional compilation step. You can use something like cargo expand to do just that.

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.