wit-bindgen icon indicating copy to clipboard operation
wit-bindgen copied to clipboard

Add new functions to generate rust bindings in `build.rs`

Open tomasol opened this issue 3 months ago • 5 comments

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

tomasol avatar Nov 30 '25 19:11 tomasol

Thanks for the quick review! Additionally I would like to add a macro to include the generated file:

#[cfg(feature = "macros")]
#[macro_export]
macro_rules! include_wit {
    ($name:literal) => {
        include!(concat!(env!("OUT_DIR"), "/", $name, ".rs"));
    };
}

so that the bindings can be included simply with wit_bindgen::include_wit!("myworld");. Is it a good idea to add it to wit-bindgen ?

tomasol avatar Dec 11 '25 08:12 tomasol

Personally I'd say that should be left out of the crate and documented in the usage of this method. I (subjectively) don't feel that clears the threshold for inclusion just yet, but if it becomes a common/frequent way of using wit-bindgen it seems ok to add.

alexcrichton avatar Dec 11 '25 12:12 alexcrichton

Understood, in that case the PR is done.

tomasol avatar Dec 11 '25 13:12 tomasol

Looks like an intermittent failure, so let's try again

tschneidereit avatar Dec 11 '25 14:12 tschneidereit

Sigh, I think Github infra might be having a bad day. I'll try again tomorrow

tschneidereit avatar Dec 11 '25 17:12 tschneidereit