Skip to content

Conversation

@tomasol
Copy link

@tomasol tomasol commented Nov 30, 2025

Add RustWasm::generate_to_out_dir that parses the wit folder, selects a world, generates bindings and places them in a file in the OUT_DIR. generate_to_out_dir_modify allows modifying the generated file.

Sample build.rs

use anyhow::Result;
use std::borrow::Cow;
use wit_bindgen_rust::Opts;

fn main() -> Result<()> {
    Opts {
        generate_all: true,
        additional_derive_attributes: vec![
            "serde::Serialize".to_string(),
            "serde::Deserialize".to_string(),
        ],
        ..Default::default()
    }
    .build()
    .generate_to_out_dir_modify(Some("any"), |contents| {
        let contents = String::from_utf8(contents.to_vec()).unwrap();
        let re = regex::Regex::new(r"(pub\s+enum\s+\w+)").unwrap();
        Cow::Owned(
            re.replace_all(&contents, "#[serde(rename_all = \"kebab-case\")]\n$1")
                .into_owned()
                .into_bytes(),
        )
    })
}

Then the following snipped would include it:

mod generated {
    include!(concat!(env!("OUT_DIR"), "/wit_bindgen_generated.rs"));
}

Although this should be simplified as well.

Closes #1423

Add `RustWasm::generate_to_out_dir` that parses the `wit` folder,
selects a world, generates bindings and places them in a file in the
`OUT_DIR`. `generate_to_out_dir_modify` allows modifying the generated
file.
let mut files = Files::default();
self.generate(&resolve, world, &mut files)?;
let out_dir = std::env::var("OUT_DIR").expect("cargo sets OUT_DIR");
let dst = Path::new(&out_dir).join(GENERATED_FILE_NAME);
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Instead of using a hardcoded name could all the files be written with the name from the generator itself?

self.generate_to_out_dir_modify(world, |s| Cow::Borrowed(s))
}

pub fn generate_to_out_dir_modify(
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Mind adding some doc comments for these methods?

pub fn generate_to_out_dir_modify(
mut self,
world: Option<&str>,
modify: impl FnOnce(&[u8]) -> Cow<[u8]>,
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This isn't necessarily tightly integrated into the generation step, so could this be omitted and performed as part of the top-level build itself? For example the caller of generate_to_out_dir would read the output file, perform the transformation, and then write back out the contents.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

rust: Generating bindings in build.rs

2 participants