Automatically generate Rust code on compilation

Backstory: I am porting some C# library to Rust. The library uses some T4 script to generate C# code compile-time to be included in build, by using another C# code. The code itself is reading several files from build environment and populates several non-trivial classes with read data and their relationship.

Is something like that possible in Rust? So far I reckon:

  • One can use build.rs to execute Rust code compile-time, but I wonder if outputing a new Rust source from read data in this step is a good strategy
  • I can use some macro magic. Honestely I worked very little with Rust macros and I would welcome a small proof-of-concept example of how can I read file inside a macro, execute some Rust code and output result as Rust code

It's a good strategy. This is half of what build.rs is for (the other half is compiling, and configuring linking for, non-Rust code). Note that the output files must be placed in $OUT_DIR, not src/.

Macros can be used too, but macros are not really supposed to have any outside inputs and so do not have a clean way to declare their dependencies like build scripts do.

6 Likes