Skip to content

A lightweight WebAssembly runtime that is fast, secure, and standards-compliant

component: add `include_component_type` bindgen! option (#14013)

Lann6d8e92301b57
diff --git a/Cargo.lock b/Cargo.lock
index 4d6b455b20..72d86667c2 100644
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -5088,6 +5088,7 @@ dependencies = [
"bitflags 2.11.1",
"heck",
"indexmap 2.14.0",
+ "wit-component 0.254.0",
"wit-parser 0.254.0",
]
diff --git a/crates/component-macro/Cargo.toml b/crates/component-macro/Cargo.toml
index 5936974dbd..5ac980d08a 100644
--- a/crates/component-macro/Cargo.toml
+++ b/crates/component-macro/Cargo.toml
@@ -38,6 +38,7 @@ serde = { workspace = true, features = ["derive"] }
serde_json = { workspace = true }
prettyplease = "0.2.31"
similar = { workspace = true }
+wit-parser = { workspace = true, features = ["decoding"] }
[features]
async = ['wasmtime-wit-bindgen/async']
diff --git a/crates/component-macro/src/bindgen.rs b/crates/component-macro/src/bindgen.rs
index 4cdf0afe84..852521c3ac 100644
--- a/crates/component-macro/src/bindgen.rs
+++ b/crates/component-macro/src/bindgen.rs
@@ -152,6 +152,7 @@ impl Parse for Config {
opts.anyhow = val;
}
Opt::IncludeGeneratedCodeFromFile(i) => include_generated_code_from_file = i,
+ Opt::IncludeComponentType(val) => opts.include_component_type = val,
Opt::Imports(config, span) => {
if imports_configured {
return Err(Error::new(span, "cannot specify imports configuration"));
@@ -263,6 +264,7 @@ mod kw {
syn::custom_keyword!(wasmtime_crate);
syn::custom_keyword!(anyhow);
syn::custom_keyword!(include_generated_code_from_file);
+ syn::custom_keyword!(include_component_type);
syn::custom_keyword!(debug);
syn::custom_keyword!(imports);
syn::custom_keyword!(exports);
@@ -287,6 +289,7 @@ enum Opt {
WasmtimeCrate(syn::Path),
Anyhow(bool),
IncludeGeneratedCodeFromFile(bool),
+ IncludeComponentType(bool),
Debug(bool),
Imports(FunctionConfig, Span),
Exports(FunctionConfig, Span),
@@ -430,6 +433,12 @@ impl Parse for Opt {
Ok(Opt::IncludeGeneratedCodeFromFile(
input.parse::<syn::LitBool>()?.value,
))
+ } else if l.peek(kw::include_component_type) {
+ input.parse::<kw::include_component_type>()?;
+ input.parse::<Token![:]>()?;
+ Ok(Opt::IncludeComponentType(
+ input.parse::<syn::LitBool>()?.value,
+ ))
} else if l.peek(kw::imports) {
let span = input.parse::<kw::imports>()?.span;
input.parse::<Token![:]>()?;
diff --git a/crates/component-macro/tests/codegen.rs b/crates/component-macro/tests/codegen.rs
index bcb0e15829..f40ea9136e 100644
--- a/crates/component-macro/tests/codegen.rs
+++ b/crates/component-macro/tests/codegen.rs
@@ -1004,3 +1004,30 @@ mod named_imports {
});
}
}
+
+mod include_component_type {
+ wasmtime::component::bindgen!({
+ inline: "
+ package demo:pkg;
+
+ interface host {
+ greet: func(name: string) -> string;
+ }
+
+ world component-type-world {
+ import host;
+ export run: func() -> u32;
+ }
+ ",
+ include_component_type: true,
+ });
+
+ #[test]
+ fn component_type_decodes() {
+ let (resolve, world) = wit_parser::decoding::decode_world(COMPONENT_TYPE).unwrap();
+ let world = &resolve.worlds[world];
+ assert_eq!(world.name, "component-type-world");
+ assert_eq!(world.imports.len(), 1);
+ assert_eq!(world.exports.len(), 1);
+ }
+}
diff --git a/crates/wasmtime/src/runtime/component/mod.rs b/crates/wasmtime/src/runtime/component/mod.rs
index 591ee8f0a3..7bf166b757 100644
--- a/crates/wasmtime/src/runtime/component/mod.rs
+++ b/crates/wasmtime/src/runtime/component/mod.rs
@@ -522,6 +522,19 @@ pub(crate) use self::store::ComponentStoreData;
/// //
/// // This option defaults to false.
/// include_generated_code_from_file: false,
+///
+/// // Whether to generate a `COMPONENT_TYPE` constant containing a
+/// // binary-encoded description of the WIT world that bindings
+/// // were generated for.
+/// //
+/// // This can be decoded with the `wit_parser::decoding::decode_world`
+/// // function to recover the WIT `Resolve` and `WorldId` used to
+/// // generate the bindings, for example to type-check components
+/// // against the world without keeping the original WIT files around.
+/// //
+/// // This option defaults to false as the encoded world adds a
+/// // nontrivial amount of data to the generated code.
+/// include_component_type: false,
/// });
/// ```
pub use wasmtime_component_macro::bindgen;
diff --git a/crates/wit-bindgen/Cargo.toml b/crates/wit-bindgen/Cargo.toml
index f876ff462c..5a215b5edd 100644
--- a/crates/wit-bindgen/Cargo.toml
+++ b/crates/wit-bindgen/Cargo.toml
@@ -16,6 +16,7 @@ workspace = true
anyhow = { workspace = true }
heck = { workspace = true }
wit-parser = { workspace = true }
+wit-component = { workspace = true }
indexmap = { workspace = true, features = ['std'] }
bitflags = { workspace = true }
diff --git a/crates/wit-bindgen/src/lib.rs b/crates/wit-bindgen/src/lib.rs
index 8cf75078a6..5154f4491c 100644
--- a/crates/wit-bindgen/src/lib.rs
+++ b/crates/wit-bindgen/src/lib.rs
@@ -196,6 +196,15 @@ pub struct Opts {
pub imports: FunctionConfig,
/// TODO
pub exports: FunctionConfig,
+
+ /// Whether to emit a `COMPONENT_TYPE` constant containing a
+ /// binary-encoded description of the world that bindings were
+ /// generated for.
+ ///
+ /// This can be decoded with `wit_parser::decoding::decode_world` to recover
+ /// the `Resolve` and `WorldId` used to generate the bindings, without
+ /// requiring separate bookkeeping of the original WIT files.
+ pub include_component_type: bool,
}
#[derive(Debug, Clone)]
@@ -1153,6 +1162,26 @@ impl<_T: Send + 'static> {camel}Pre<_T> {{
let named_imports = mem::take(&mut self.named_import_modules);
self.emit_modules(named_imports);
+ if self.opts.include_component_type {
+ let encoded = wit_component::metadata::encode(
+ resolve,
+ world,
+ wit_component::StringEncoding::UTF8,
+ None,
+ )?;
+ uwriteln!(
+ self.src,
+ "/// A binary-encoded description of the WIT world that these \
+ bindings were generated from.\n\
+ ///\n\
+ /// This can be decoded with the `wit_parser::decoding::decode_world` \
+ function to recover the WIT `Resolve` and `WorldId` that were used \
+ to generate these bindings.\n\
+ pub const COMPONENT_TYPE: &[u8] = b\"{}\";",
+ encoded.escape_ascii(),
+ );
+ }
+
let mut src = mem::take(&mut self.src);
if self.opts.rustfmt {
let mut child = Command::new("rustfmt")