Stream: git-wasmtime

Topic: wasmtime / issue #9315 bindgen macro: "Use of Undeclared ...


view this post on Zulip Wasmtime GitHub notifications bot (Sep 26 2024 at 13:06):

esarver opened issue #9315:

Problem Description

I created a simple host.wit file to start playing with the component model in an embedded runtime. In this file, I created a world by the name host. I was following the examples in the wasmtime bindgen examples and got an error stating that HostImports did not exist but there was a similar trait named Host_Imports (see build output below). I changed my trait impl to the one shown below and got an error stating that bindgen was creating some code that referenced HostImports.

If I change the world name to anything else, the problem goes away.

Identified Problem Area

I found that there is a function in wasmtime/crates/wit-bindgen/src/rust.rs called to_rust_upper_camel_case that uses Host_ if the provided name is host. This is not being used consistently somewhere.

Project Files

Here are my project files that replicate the issue, along with the cargo expand output that shows the code with an issue (collapsed to improve readability of this ticket).

./Cargo.toml

[package]
name = "host"
version = "0.1.0"
edition = "2021"

[dependencies]
wasmtime = "25.0.1"
wit-bindgen = "0.32.0"

./wit/host.wit

package system:system;

world host {
    import print: func(msg: string);
    export run: func();
}

./src/main.rs

use wasmtime::*;

wasmtime::component::bindgen!("host");

struct State;

impl Host_Imports for State {
    fn print(&mut self, msg: String) {
        println!("{msg}");
    }
}

fn main() {
    println!("Hello, world!");
}

<details>
<summary>

Expanded main.rs

</summary>

#![feature(prelude_import)]
#[prelude_import]
use std::prelude::rust_2021::*;
#[macro_use]
extern crate std;
use wasmtime::*;
/// Auto-generated bindings for a pre-instantiated version of a
/// component which implements the world `host`.
///
/// This structure is created through [`Host_Pre::new`] which
/// takes a [`InstancePre`](wasmtime::component::InstancePre) that
/// has been created through a [`Linker`](wasmtime::component::Linker).
///
/// For more information see [`Host_`] as well.
pub struct Host_Pre<T> {
    instance_pre: wasmtime::component::InstancePre<T>,
    indices: Host_Indices,
}
impl<T> Clone for Host_Pre<T> {
    fn clone(&self) -> Self {
        Self {
            instance_pre: self.instance_pre.clone(),
            indices: self.indices.clone(),
        }
    }
}
impl<_T> Host_Pre<_T> {
    /// Creates a new copy of `Host_Pre` bindings which can then
    /// be used to instantiate into a particular store.
    ///
    /// This method may fail if the component behind `instance_pre`
    /// does not have the required exports.
    pub fn new(
        instance_pre: wasmtime::component::InstancePre<_T>,
    ) -> wasmtime::Result<Self> {
        let indices = Host_Indices::new(instance_pre.component())?;
        Ok(Self { instance_pre, indices })
    }
    pub fn engine(&self) -> &wasmtime::Engine {
        self.instance_pre.engine()
    }
    pub fn instance_pre(&self) -> &wasmtime::component::InstancePre<_T> {
        &self.instance_pre
    }
    /// Instantiates a new instance of [`Host_`] within the
    /// `store` provided.
    ///
    /// This function will use `self` as the pre-instantiated
    /// instance to perform instantiation. Afterwards the preloaded
    /// indices in `self` are used to lookup all exports on the
    /// resulting instance.
    pub fn instantiate(
        &self,
        mut store: impl wasmtime::AsContextMut<Data = _T>,
    ) -> wasmtime::Result<Host_> {
        let mut store = store.as_context_mut();
        let instance = self.instance_pre.instantiate(&mut store)?;
        self.indices.load(&mut store, &instance)
    }
}
/// Auto-generated bindings for index of the exports of
/// `host`.
///
/// This is an implementation detail of [`Host_Pre`] and can
/// be constructed if needed as well.
///
/// For more information see [`Host_`] as well.
pub struct Host_Indices {
    run: wasmtime::component::ComponentExportIndex,
}
#[automatically_derived]
impl ::core::clone::Clone for Host_Indices {
    #[inline]
    fn clone(&self) -> Host_Indices {
        Host_Indices {
            run: ::core::clone::Clone::clone(&self.run),
        }
    }
}
/// Auto-generated bindings for an instance a component which
/// implements the world `host`.
///
/// This structure can be created through a number of means
/// depending on your requirements and what you have on hand:
///
/// * The most convenient way is to use
///   [`Host_::instantiate`] which only needs a
///   [`Store`], [`Component`], and [`Linker`].
///
/// * Alternatively you can create a [`Host_Pre`] ahead of
///   time with a [`Component`] to front-load string lookups
///   of exports once instead of per-instantiation. This
///   method then uses [`Host_Pre::instantiate`] to
///   create a [`Host_`].
///
/// * If you've instantiated the instance yourself already
///   then you can use [`Host_::new`].
///
/// * You can also access the guts of instantiation through
///   [`Host_Indices::new_instance`] followed
///   by [`Host_Indices::load`] to crate an instance of this
///   type.
///
/// These methods are all equivalent to one another and move
/// around the tradeoff of what work is performed when.
///
/// [`Store`]: wasmtime::Store
/// [`Component`]: wasmtime::component::Component
/// [`Linker`]: wasmtime::component::Linker
pub struct Host_ {
    run: wasmtime::component::Func,
}
pub trait Host_Imports {
    fn print(&mut self, msg: wasmtime::component::__internal::String) -> ();
}
pub trait Host_ImportsGetHost<
    T,
>: Fn(T) -> <Self as Host_ImportsGetHost<T>>::Host + Send + Sync + Copy + 'static {
    type Host: Host_Imports;
}
impl<F, T, O> Host_ImportsGetHost<T> for F
where
    F: Fn(T) -> O + Send + Sync + Copy + 'static,
    O: Host_Imports,
{
    type Host = O;
}
impl<_T: Host_Imports + ?Sized> Host_Imports for &mut _T {
    fn print(&mut self, msg: wasmtime::component::__internal::String) -> () {
        Host_Imports::print(*self, msg)
    }
}
const _: () = {
    #[allow(unused_imports)]
    use wasmtime::component::__internal::anyhow;
    impl Host_Indices {
        /// Creates a new copy of `Host_Indices` bindings which can then
        /// be used to instantiate into a particular store.
        ///
        /// This method may fail if the component does not have the
        /// required exports.
        pub fn new(
            component: &wasmtime::component::Component,
        ) -> wasmtime::Result<Self> {
            let _component = component;
            let run = _component
                .export_index(None, "run")
                .ok_or_else(|| ::anyhow::__private::must_use({
                    let error = ::anyhow::__private::format_err(
                        format_args!("no function export `run` found"),
                    );
                    error
                }))?
                .1;
            Ok(Host_Indices { run })
        }
        /// Creates a new instance of [`Host_Indices`] from an
        /// instantiated component.
        ///
        /// This method of creating a [`Host_`] will perform string
        /// lookups for all exports when this method is called. This
        /// will only succeed if the provided instance matches the
        /// requirements of [`Host_`].
        pub fn new_instance(
            mut store: impl wasmtime::AsContextMut,
            instance: &wasmtime::component::Instance,
        ) -> wasmtime::Result<Self> {
            let _instance = instance;
            let run = _instance
                .get_export(&mut store, None, "run")
                .ok_or_else(|| ::anyhow::__private::must_use({
                    let error = ::anyhow::__private::format_err(
                        format_args!("no function export `run` found"),
                    );
                    error
                }))?;
            Ok(Host_Indices { run })
        }
        /// Uses the indices stored in `self` to load an instance
        /// of [`Host_`] from the instance provided.
        ///
        /// Note that at this time this method will additionally
        /// perform type-checks of all exports.
        pub fn load(
            &self,
            mut store: impl wasmtime::AsContextMut,
            instance: &wasmtime::component::Instance,
        ) -> wasmtime::Result<Host_> {
            let _instance = instance;
            let run = *_instance.get_typed_func::<(), ()>(&mut store, &self.run)?.func();
            Ok(Host_ { run })
        }
    }
    impl Host_ {
        /// Convenience wrapper around [`Host_Pre::new`] and
        /// [`Host_Pre::instantiate`].
        pub fn instantiate<_T>(
            mut store: impl wasmtime::AsContextMut<Data = _T>,
            component: &wasmtime::component::Component,
            linker: &wasmtime::component::Linker<_T>,
        ) -> wasmtime::Result<Host_> {
            let pre = linker.instantiate_pre(component)?;
            Host_Pre::new(pre)?.instantiate(store)
        }
        /// Convenience wrapper around [`Host_Indices::new_instance`] and
        /// [`Host_Indices::load`].
        pub fn new(
            mut store: impl wasmtime::AsContextMut,
            instance: &wasmtime::component::Instance,
        ) -> wasmtime::Result<Host_> {
            let indices = Host_Indices::new_instance(&mut store, instance)?;
            indices
[message truncated]

view this post on Zulip Wasmtime GitHub notifications bot (Sep 26 2024 at 13:33):

esarver commented on issue #9315:

The issue appears to be in wasmtime/crates/wit-bindgen/src/lib.rs

I'll try making a quick change to see if I can get it to work and then submit a PR.

view this post on Zulip Wasmtime GitHub notifications bot (Sep 26 2024 at 13:34):

esarver edited a comment on issue #9315:

The issue appears to be in wasmtime/crates/wit-bindgen/src/lib.rs:2608

I'll try making a quick change to see if I can get it to work and then submit a PR.

view this post on Zulip Wasmtime GitHub notifications bot (Sep 28 2024 at 16:20):

alexcrichton closed issue #9315:

Problem Description

I created a simple host.wit file to start playing with the component model in an embedded runtime. In this file, I created a world by the name host. I was following the examples in the wasmtime bindgen examples and got an error stating that HostImports did not exist but there was a similar trait named Host_Imports (see build output below). I changed my trait impl to the one shown below and got an error stating that bindgen was creating some code that referenced HostImports.

If I change the world name to anything else, the problem goes away.

Identified Problem Area

I found that there is a function in wasmtime/crates/wit-bindgen/src/rust.rs called to_rust_upper_camel_case that uses Host_ if the provided name is host. This is not being used consistently somewhere.

Project Files

Here are my project files that replicate the issue, along with the cargo expand output that shows the code with an issue (collapsed to improve readability of this ticket).

./Cargo.toml

[package]
name = "host"
version = "0.1.0"
edition = "2021"

[dependencies]
wasmtime = "25.0.1"
wit-bindgen = "0.32.0"

./wit/host.wit

package system:system;

world host {
    import print: func(msg: string);
    export run: func();
}

./src/main.rs

use wasmtime::*;

wasmtime::component::bindgen!("host");

struct State;

impl Host_Imports for State {
    fn print(&mut self, msg: String) {
        println!("{msg}");
    }
}

fn main() {
    println!("Hello, world!");
}

<details>
<summary>

Expanded main.rs

</summary>

#![feature(prelude_import)]
#[prelude_import]
use std::prelude::rust_2021::*;
#[macro_use]
extern crate std;
use wasmtime::*;
/// Auto-generated bindings for a pre-instantiated version of a
/// component which implements the world `host`.
///
/// This structure is created through [`Host_Pre::new`] which
/// takes a [`InstancePre`](wasmtime::component::InstancePre) that
/// has been created through a [`Linker`](wasmtime::component::Linker).
///
/// For more information see [`Host_`] as well.
pub struct Host_Pre<T> {
    instance_pre: wasmtime::component::InstancePre<T>,
    indices: Host_Indices,
}
impl<T> Clone for Host_Pre<T> {
    fn clone(&self) -> Self {
        Self {
            instance_pre: self.instance_pre.clone(),
            indices: self.indices.clone(),
        }
    }
}
impl<_T> Host_Pre<_T> {
    /// Creates a new copy of `Host_Pre` bindings which can then
    /// be used to instantiate into a particular store.
    ///
    /// This method may fail if the component behind `instance_pre`
    /// does not have the required exports.
    pub fn new(
        instance_pre: wasmtime::component::InstancePre<_T>,
    ) -> wasmtime::Result<Self> {
        let indices = Host_Indices::new(instance_pre.component())?;
        Ok(Self { instance_pre, indices })
    }
    pub fn engine(&self) -> &wasmtime::Engine {
        self.instance_pre.engine()
    }
    pub fn instance_pre(&self) -> &wasmtime::component::InstancePre<_T> {
        &self.instance_pre
    }
    /// Instantiates a new instance of [`Host_`] within the
    /// `store` provided.
    ///
    /// This function will use `self` as the pre-instantiated
    /// instance to perform instantiation. Afterwards the preloaded
    /// indices in `self` are used to lookup all exports on the
    /// resulting instance.
    pub fn instantiate(
        &self,
        mut store: impl wasmtime::AsContextMut<Data = _T>,
    ) -> wasmtime::Result<Host_> {
        let mut store = store.as_context_mut();
        let instance = self.instance_pre.instantiate(&mut store)?;
        self.indices.load(&mut store, &instance)
    }
}
/// Auto-generated bindings for index of the exports of
/// `host`.
///
/// This is an implementation detail of [`Host_Pre`] and can
/// be constructed if needed as well.
///
/// For more information see [`Host_`] as well.
pub struct Host_Indices {
    run: wasmtime::component::ComponentExportIndex,
}
#[automatically_derived]
impl ::core::clone::Clone for Host_Indices {
    #[inline]
    fn clone(&self) -> Host_Indices {
        Host_Indices {
            run: ::core::clone::Clone::clone(&self.run),
        }
    }
}
/// Auto-generated bindings for an instance a component which
/// implements the world `host`.
///
/// This structure can be created through a number of means
/// depending on your requirements and what you have on hand:
///
/// * The most convenient way is to use
///   [`Host_::instantiate`] which only needs a
///   [`Store`], [`Component`], and [`Linker`].
///
/// * Alternatively you can create a [`Host_Pre`] ahead of
///   time with a [`Component`] to front-load string lookups
///   of exports once instead of per-instantiation. This
///   method then uses [`Host_Pre::instantiate`] to
///   create a [`Host_`].
///
/// * If you've instantiated the instance yourself already
///   then you can use [`Host_::new`].
///
/// * You can also access the guts of instantiation through
///   [`Host_Indices::new_instance`] followed
///   by [`Host_Indices::load`] to crate an instance of this
///   type.
///
/// These methods are all equivalent to one another and move
/// around the tradeoff of what work is performed when.
///
/// [`Store`]: wasmtime::Store
/// [`Component`]: wasmtime::component::Component
/// [`Linker`]: wasmtime::component::Linker
pub struct Host_ {
    run: wasmtime::component::Func,
}
pub trait Host_Imports {
    fn print(&mut self, msg: wasmtime::component::__internal::String) -> ();
}
pub trait Host_ImportsGetHost<
    T,
>: Fn(T) -> <Self as Host_ImportsGetHost<T>>::Host + Send + Sync + Copy + 'static {
    type Host: Host_Imports;
}
impl<F, T, O> Host_ImportsGetHost<T> for F
where
    F: Fn(T) -> O + Send + Sync + Copy + 'static,
    O: Host_Imports,
{
    type Host = O;
}
impl<_T: Host_Imports + ?Sized> Host_Imports for &mut _T {
    fn print(&mut self, msg: wasmtime::component::__internal::String) -> () {
        Host_Imports::print(*self, msg)
    }
}
const _: () = {
    #[allow(unused_imports)]
    use wasmtime::component::__internal::anyhow;
    impl Host_Indices {
        /// Creates a new copy of `Host_Indices` bindings which can then
        /// be used to instantiate into a particular store.
        ///
        /// This method may fail if the component does not have the
        /// required exports.
        pub fn new(
            component: &wasmtime::component::Component,
        ) -> wasmtime::Result<Self> {
            let _component = component;
            let run = _component
                .export_index(None, "run")
                .ok_or_else(|| ::anyhow::__private::must_use({
                    let error = ::anyhow::__private::format_err(
                        format_args!("no function export `run` found"),
                    );
                    error
                }))?
                .1;
            Ok(Host_Indices { run })
        }
        /// Creates a new instance of [`Host_Indices`] from an
        /// instantiated component.
        ///
        /// This method of creating a [`Host_`] will perform string
        /// lookups for all exports when this method is called. This
        /// will only succeed if the provided instance matches the
        /// requirements of [`Host_`].
        pub fn new_instance(
            mut store: impl wasmtime::AsContextMut,
            instance: &wasmtime::component::Instance,
        ) -> wasmtime::Result<Self> {
            let _instance = instance;
            let run = _instance
                .get_export(&mut store, None, "run")
                .ok_or_else(|| ::anyhow::__private::must_use({
                    let error = ::anyhow::__private::format_err(
                        format_args!("no function export `run` found"),
                    );
                    error
                }))?;
            Ok(Host_Indices { run })
        }
        /// Uses the indices stored in `self` to load an instance
        /// of [`Host_`] from the instance provided.
        ///
        /// Note that at this time this method will additionally
        /// perform type-checks of all exports.
        pub fn load(
            &self,
            mut store: impl wasmtime::AsContextMut,
            instance: &wasmtime::component::Instance,
        ) -> wasmtime::Result<Host_> {
            let _instance = instance;
            let run = *_instance.get_typed_func::<(), ()>(&mut store, &self.run)?.func();
            Ok(Host_ { run })
        }
    }
    impl Host_ {
        /// Convenience wrapper around [`Host_Pre::new`] and
        /// [`Host_Pre::instantiate`].
        pub fn instantiate<_T>(
            mut store: impl wasmtime::AsContextMut<Data = _T>,
            component: &wasmtime::component::Component,
            linker: &wasmtime::component::Linker<_T>,
        ) -> wasmtime::Result<Host_> {
            let pre = linker.instantiate_pre(component)?;
            Host_Pre::new(pre)?.instantiate(store)
        }
        /// Convenience wrapper around [`Host_Indices::new_instance`] and
        /// [`Host_Indices::load`].
        pub fn new(
            mut store: impl wasmtime::AsContextMut,
            instance: &wasmtime::component::Instance,
        ) -> wasmtime::Result<Host_> {
            let indices = Host_Indices::new_instance(&mut store, instance)?;
            in
[message truncated]

view this post on Zulip Wasmtime GitHub notifications bot (Sep 28 2024 at 16:20):

alexcrichton commented on issue #9315:

Fixed in https://github.com/bytecodealliance/wasmtime/pull/9316


Last updated: Oct 23 2024 at 20:03 UTC