Andy Thomason
Andy Thomason

Reputation: 328

How can I generate files from Rust procedural macros?

I am building an extension API for R in Rust. I annotate my functions with a procedural macro to generate C wrappers with the appropriate conversion and error handling:

use extendr_api::*;

#[export_function]
fn hello() -> &'static str {
    "hello"
}

This generates a C function hello__wrapper__ that is callable from R using the .Call mechanism.

In addition to this, we need to generate a NAMESPACE file for the R metatdata:

export(hello)
useDynLib(libhello, "__wrap__hello")

And a file lib.R

hello <- function() {
  .Call("__wrap__hello")
}

What is the simplest way to extend cargo or rustc to write this additional information? I'm guessing that writing a file from the procedural macro code is a bad idea.

Upvotes: 2

Views: 1828

Answers (1)

eric556
eric556

Reputation: 115

From what I understand, procedural macros generate code at compile time, but it has to be valid Rust code. I do not think that a procedural macro is the way to go in this case.

One possible solution is to create a script that will go through and find your exported functions in the Rust file and generate the 2 extra files you need. You could make a build script that runs before compiling if you want to do all the parsing in Rust, otherwise I would suggest something like Python.

Upvotes: 0

Related Questions