Skip to main content

Code Generation

Code generation in the WebAssembly component model space is dominated largely by the wit-bindgen project. This library, which can be used as a CLI or via code to automate CI pipeline build steps, is used to generate language bindings for components. Currently, the following languages are supported:

  • Rust
  • C/C++
  • Java
  • C#
  • TinyGo

Language diversity and depth of support will continue to grow as the component model matures. Right now, this aspect of the component model is one of the most frequently changing so staying on contact with the various communities and sub-projects is important.

info

Note that neither the CLI nor the collection of wit-bindgen and adjacent libraries are stable at this time.

Code Generation in Rust

To set your WebAssembly component up for code generation, you'll need to start with the following pre-flight checklist:

  • Ensure you have the wasm32-wasi target installed: rustup target add wasm32-wasi
  • Ensure that your Cargo.toml indicates a crate-type of ["cdylib"]
  • Add wit-bindgen as a dependency: cargo add --git https://github.com/bytecodealliance/wit-bindgen wit-bindgen
/*
wit/robot.wit

package example:robot

world robot {
  import print: func(msg: string)

  export run: func()
}
*/
wit_bindgen::generate!("robot");

struct MyRobot;

impl Robot for MyRobot {
    fn run() {
        print("Exterminate!");
    }
}

// The following macro is generated by wit-bindgen and is always named `export_{world_name}`
export_robot!(MyHost);

The first thing we see is the use of the generate! macro. You can specify a handful of options here but if left with the defaults, all you need to do is give it the name of a world in the corresponding wit file. In this case, it will look in wit/robot.wit.

Next we define a struct on which to anchor the interface: MyRobot. The Robot trait is generated automatically by the macro and all we have to do is implement it in order to define our exports. Within each export like run, we can invoke any of the imports, e.g. print.

Lastly, there's some housekeeping that wit-bindgen needs to do, and that goes in a macro named export_{world name}. In this sample, that's export_robot!.

Wrapping Up

Make sure you check out the wasmCloud examples repository to keep up to date on what we're building and our adoption of the component model.