Skip to main content

wasmtime/runtime/component/
linker.rs

1#[cfg(feature = "component-model-async")]
2use crate::component::concurrent::Accessor;
3use crate::component::func::HostFunc;
4use crate::component::instance::RuntimeImport;
5use crate::component::matching::{InstanceType, TypeChecker};
6use crate::component::types;
7use crate::component::{
8    Component, ComponentNamedList, Instance, InstancePre, Lift, Lower, ResourceType, Val,
9};
10use crate::prelude::*;
11use crate::{AsContextMut, Engine, Module, StoreContextMut};
12use alloc::sync::Arc;
13use core::marker;
14#[cfg(feature = "component-model-async")]
15use core::pin::Pin;
16use wasmtime_environ::component::NameMap;
17use wasmtime_environ::{Atom, PrimaryMap, StringPool};
18
19/// A type used to instantiate [`Component`]s.
20///
21/// This type is used to both link components together as well as supply host
22/// functionality to components. Values are defined in a [`Linker`] by their
23/// import name and then components are instantiated with a [`Linker`] using the
24/// names provided for name resolution of the component's imports.
25///
26/// # Names and Semver
27///
28/// Names defined in a [`Linker`] correspond to import names in the Component
29/// Model. Names in the Component Model are allowed to be semver-qualified, for
30/// example:
31///
32/// * `wasi:cli/stdout@0.2.0`
33/// * `wasi:http/types@0.2.0-rc-2023-10-25`
34/// * `my:custom/plugin@1.0.0-pre.2`
35///
36/// These version strings are taken into account when looking up names within a
37/// [`Linker`]. You're allowed to define any number of versions within a
38/// [`Linker`] still, for example you can define `a:b/c@0.2.0`, `a:b/c@0.2.1`,
39/// and `a:b/c@0.3.0` all at the same time.
40///
41/// Specifically though when names are looked up within a linker, for example
42/// during instantiation, semver-compatible names are automatically consulted.
43/// This means that if you define `a:b/c@0.2.1` in a [`Linker`] but a component
44/// imports `a:b/c@0.2.0` then that import will resolve to the `0.2.1` version.
45///
46/// This lookup behavior relies on hosts being well-behaved when using Semver,
47/// specifically that interfaces once defined are never changed. This reflects
48/// how Semver works at the Component Model layer, and it's assumed that if
49/// versions are present then hosts are respecting this.
50///
51/// Note that this behavior goes the other direction, too. If a component
52/// imports `a:b/c@0.2.1` and the host has provided `a:b/c@0.2.0` then that
53/// will also resolve correctly. This is because if an API was defined at 0.2.0
54/// and 0.2.1 then it must be the same API.
55///
56/// This behavior is intended to make it easier for hosts to upgrade WASI and
57/// for guests to upgrade WASI. So long as the actual "meat" of the
58/// functionality is defined then it should align correctly and components can
59/// be instantiated.
60pub struct Linker<T: 'static> {
61    engine: Engine,
62    strings: StringPool,
63    map: NameMap<Atom, Definition>,
64    path: Vec<Atom>,
65    allow_shadowing: bool,
66    _marker: marker::PhantomData<fn() -> T>,
67}
68
69impl<T: 'static> Clone for Linker<T> {
70    fn clone(&self) -> Linker<T> {
71        Linker {
72            engine: self.engine.clone(),
73            strings: self.strings.clone_panic_on_oom(),
74            map: self.map.clone_panic_on_oom(),
75            path: self.path.clone(),
76            allow_shadowing: self.allow_shadowing,
77            _marker: self._marker,
78        }
79    }
80}
81
82/// Structure representing an "instance" being defined within a linker.
83///
84/// Instances do not need to be actual [`Instance`]s and instead are defined by
85/// a "bag of named items", so each [`LinkerInstance`] can further define items
86/// internally.
87pub struct LinkerInstance<'a, T: 'static> {
88    engine: &'a Engine,
89    path: &'a mut Vec<Atom>,
90    path_len: usize,
91    strings: &'a mut StringPool,
92    map: &'a mut NameMap<Atom, Definition>,
93    allow_shadowing: bool,
94    _marker: marker::PhantomData<fn() -> T>,
95}
96
97#[derive(Debug)]
98pub(crate) enum Definition {
99    Instance(NameMap<Atom, Definition>),
100    Func(Arc<HostFunc>),
101    Module(Module),
102    Resource(ResourceType, Arc<crate::func::HostFunc>),
103}
104
105impl TryClone for Definition {
106    fn try_clone(&self) -> Result<Self, OutOfMemory> {
107        Ok(match self {
108            Self::Instance(i) => Self::Instance(i.try_clone()?),
109            Self::Func(f) => Self::Func(f.try_clone()?),
110            Self::Module(m) => Self::Module(m.clone()),
111            Self::Resource(r, f) => Self::Resource(*r, f.try_clone()?),
112        })
113    }
114}
115
116impl<T: 'static> Linker<T> {
117    /// Creates a new linker for the [`Engine`] specified with no items defined
118    /// within it.
119    pub fn new(engine: &Engine) -> Linker<T> {
120        Linker {
121            engine: engine.clone(),
122            strings: StringPool::default(),
123            map: NameMap::default(),
124            allow_shadowing: false,
125            path: Vec::new(),
126            _marker: marker::PhantomData,
127        }
128    }
129
130    /// Returns the [`Engine`] this is connected to.
131    pub fn engine(&self) -> &Engine {
132        &self.engine
133    }
134
135    /// Configures whether or not name-shadowing is allowed.
136    ///
137    /// By default name shadowing is not allowed and it's an error to redefine
138    /// the same name within a linker.
139    pub fn allow_shadowing(&mut self, allow: bool) -> &mut Self {
140        self.allow_shadowing = allow;
141        self
142    }
143
144    /// Returns the "root instance" of this linker, used to define names into
145    /// the root namespace.
146    pub fn root(&mut self) -> LinkerInstance<'_, T> {
147        LinkerInstance {
148            engine: &self.engine,
149            path: &mut self.path,
150            path_len: 0,
151            strings: &mut self.strings,
152            map: &mut self.map,
153            allow_shadowing: self.allow_shadowing,
154            _marker: self._marker,
155        }
156    }
157
158    /// Returns a builder for the named instance specified.
159    ///
160    /// # Errors
161    ///
162    /// Returns an error if `name` is already defined within the linker.
163    pub fn instance(&mut self, name: &str) -> Result<LinkerInstance<'_, T>> {
164        self.root().into_instance(name)
165    }
166
167    fn typecheck<'a>(&'a self, component: &'a Component) -> Result<TypeChecker<'a>> {
168        let mut cx = TypeChecker {
169            engine: &self.engine,
170            types: component.types(),
171            strings: &self.strings,
172            imported_resources: try_new::<Arc<_>>(TryPrimaryMap::new())?,
173        };
174
175        // Walk over the component's list of import names and use that to lookup
176        // the definition within this linker that it corresponds to. When found
177        // perform a typecheck against the component's expected type.
178        let env_component = component.env_component();
179        for (_idx, (name, ty)) in env_component.import_types.iter() {
180            let import = self.map.get(name, &self.strings);
181            cx.definition(ty, import)
182                .with_context(|| format!("component imports {desc} `{name}`, but a matching implementation was not found in the linker", desc = ty.desc()))?;
183        }
184        Ok(cx)
185    }
186
187    /// Returns the [`types::Component`] corresponding to `component` with resource
188    /// types imported by it replaced using imports present in [`Self`].
189    ///
190    /// # Errors
191    ///
192    /// This function will return an [`OutOfMemory`][crate::OutOfMemory] error when
193    /// memory allocation fails. See the `OutOfMemory` type's documentation for
194    /// details on Wasmtime's out-of-memory handling.
195    pub fn substituted_component_type(&self, component: &Component) -> Result<types::Component> {
196        let cx = self.typecheck(&component)?;
197        Ok(types::Component::from(
198            component.ty(),
199            &InstanceType {
200                types: cx.types,
201                resources: Some(&cx.imported_resources),
202            },
203        ))
204    }
205
206    /// Performs a "pre-instantiation" to resolve the imports of the
207    /// [`Component`] specified with the items defined within this linker.
208    ///
209    /// This method will perform as much work as possible short of actually
210    /// instantiating an instance. Internally this will use the names defined
211    /// within this linker to satisfy the imports of the [`Component`] provided.
212    /// Additionally this will perform type-checks against the component's
213    /// imports against all items defined within this linker.
214    ///
215    /// Note that unlike internally in components where subtyping at the
216    /// interface-types layer is supported this is not supported here. Items
217    /// defined in this linker must match the component's imports precisely.
218    ///
219    /// # Errors
220    ///
221    /// Returns an error if this linker doesn't define a name that the
222    /// `component` imports or if a name defined doesn't match the type of the
223    /// item imported by the `component` provided.
224    ///
225    /// This function will return an [`OutOfMemory`][crate::OutOfMemory] error when
226    /// memory allocation fails. See the `OutOfMemory` type's documentation for
227    /// details on Wasmtime's out-of-memory handling.
228    pub fn instantiate_pre(&self, component: &Component) -> Result<InstancePre<T>> {
229        let cx = self.typecheck(&component)?;
230
231        // A successful typecheck resolves all of the imported resources used by
232        // this InstancePre. We keep a clone of this table in the InstancePre
233        // so that we can construct an InstanceType for typechecking.
234        let imported_resources = cx.imported_resources.clone();
235
236        // Now that all imports are known to be defined and satisfied by this
237        // linker a list of "flat" import items (aka no instances) is created
238        // using the import map within the component created at
239        // component-compile-time.
240        let env_component = component.env_component();
241        let mut imports = PrimaryMap::with_capacity(env_component.imports.len());
242        for (idx, (import, names)) in env_component.imports.iter() {
243            let (root, _) = &env_component.import_types[*import];
244
245            // This is the flattening process where we go from a definition
246            // optionally through a list of exported names to get to the final
247            // item.
248            let mut cur = self.map.get(root, &self.strings).unwrap();
249            for name in names {
250                cur = match cur {
251                    Definition::Instance(map) => map.get(&name, &self.strings).unwrap(),
252                    _ => unreachable!(),
253                };
254            }
255            let import = match cur {
256                Definition::Module(m) => RuntimeImport::Module(m.clone()),
257                Definition::Func(f) => RuntimeImport::Func(f.clone()),
258                Definition::Resource(t, dtor) => RuntimeImport::Resource {
259                    ty: *t,
260                    dtor: dtor.clone(),
261                    dtor_funcref: component.resource_drop_func_ref(dtor),
262                },
263
264                // This is guaranteed by the compilation process that "leaf"
265                // runtime imports are never instances.
266                Definition::Instance(_) => unreachable!(),
267            };
268            let i = imports.push(import);
269            assert_eq!(i, idx);
270        }
271        Ok(unsafe {
272            InstancePre::new_unchecked(
273                component.clone(),
274                try_new::<Arc<_>>(imports)?,
275                imported_resources,
276            )
277        })
278    }
279
280    /// Instantiates the [`Component`] provided into the `store` specified.
281    ///
282    /// This function will use the items defined within this [`Linker`] to
283    /// satisfy the imports of the [`Component`] provided as necessary. For more
284    /// information about this see [`Linker::instantiate_pre`] as well.
285    ///
286    /// # Errors
287    ///
288    /// Returns an error if this [`Linker`] doesn't define an import that
289    /// `component` requires or if it is of the wrong type. Additionally this
290    /// can return an error if something goes wrong during instantiation such as
291    /// a runtime trap or a runtime limit being exceeded.
292    ///
293    /// This function will return an [`OutOfMemory`][crate::OutOfMemory] error when
294    /// memory allocation fails. See the `OutOfMemory` type's documentation for
295    /// details on Wasmtime's out-of-memory handling.
296    pub fn instantiate(
297        &self,
298        mut store: impl AsContextMut<Data = T>,
299        component: &Component,
300    ) -> Result<Instance> {
301        let store = store.as_context_mut();
302        store.0.validate_sync_call()?;
303        self.instantiate_pre(component)?.instantiate(store)
304    }
305
306    /// Instantiates the [`Component`] provided into the `store` specified.
307    ///
308    /// This is exactly like [`Linker::instantiate`] except for [asynchronous
309    /// execution](crate#async).
310    ///
311    /// # Errors
312    ///
313    /// Returns an error if this [`Linker`] doesn't define an import that
314    /// `component` requires or if it is of the wrong type. Additionally this
315    /// can return an error if something goes wrong during instantiation such as
316    /// a runtime trap or a runtime limit being exceeded.
317    ///
318    /// This function will return an [`OutOfMemory`][crate::OutOfMemory] error when
319    /// memory allocation fails. See the `OutOfMemory` type's documentation for
320    /// details on Wasmtime's out-of-memory handling.
321    #[cfg(feature = "async")]
322    pub async fn instantiate_async(
323        &self,
324        store: impl AsContextMut<Data = T>,
325        component: &Component,
326    ) -> Result<Instance>
327    where
328        T: Send,
329    {
330        self.instantiate_pre(component)?
331            .instantiate_async(store)
332            .await
333    }
334
335    /// Implement any imports of the given [`Component`] with a function which traps.
336    ///
337    /// By default a [`Linker`] will error when unknown imports are encountered when instantiating a [`Component`].
338    /// This changes this behavior from an instant error to a trap that will happen if the import is called.
339    ///
340    /// # Errors
341    ///
342    /// This function will return an [`OutOfMemory`][crate::OutOfMemory] error when
343    /// memory allocation fails. See the `OutOfMemory` type's documentation for
344    /// details on Wasmtime's out-of-memory handling.
345    pub fn define_unknown_imports_as_traps(&mut self, component: &Component) -> Result<()> {
346        use wasmtime_environ::component::ComponentTypes;
347        use wasmtime_environ::component::TypeDef;
348        // Recursively stub out all imports of the component with a function that traps.
349        fn stub_item<T>(
350            linker: &mut LinkerInstance<T>,
351            item_name: &str,
352            item_def: &TypeDef,
353            parent_instance: Option<&str>,
354            types: &ComponentTypes,
355        ) -> Result<()> {
356            // Skip if the item isn't an instance and has already been defined in the linker.
357            if !matches!(item_def, TypeDef::ComponentInstance(_)) && linker.get(item_name).is_some()
358            {
359                return Ok(());
360            }
361
362            match item_def {
363                TypeDef::ComponentFunc(_) => {
364                    let fully_qualified_name = match parent_instance {
365                        Some(parent) => {
366                            let mut s = TryString::new();
367                            s.push_str(parent)?;
368                            s.push('#')?;
369                            s.push_str(item_name)?;
370                            s
371                        }
372                        None => {
373                            let mut s = TryString::new();
374                            s.push_str(item_name)?;
375                            s
376                        }
377                    };
378                    linker.func_new(&item_name, move |_, _, _, _| {
379                        bail!("unknown import: `{fully_qualified_name}` has not been defined")
380                    })?;
381                }
382                TypeDef::ComponentInstance(i) => {
383                    let instance = &types[*i];
384                    let mut linker_instance = linker.instance(item_name)?;
385                    for (export_name, export) in instance.exports.iter() {
386                        stub_item(
387                            &mut linker_instance,
388                            export_name,
389                            export,
390                            Some(item_name),
391                            types,
392                        )?;
393                    }
394                }
395                TypeDef::Resource(_) => {
396                    let ty = crate::component::ResourceType::host::<()>();
397                    linker.resource(item_name, ty, |_, _| Ok(()))?;
398                }
399                TypeDef::Component(_) | TypeDef::Module(_) => {
400                    bail!("unable to define {} imports as traps", item_def.desc())
401                }
402                _ => {}
403            }
404            Ok(())
405        }
406
407        for (_, (import_name, import_type)) in &component.env_component().import_types {
408            stub_item(
409                &mut self.root(),
410                import_name,
411                import_type,
412                None,
413                component.types(),
414            )?;
415        }
416        Ok(())
417    }
418}
419
420impl<T: 'static> LinkerInstance<'_, T> {
421    fn as_mut(&mut self) -> LinkerInstance<'_, T> {
422        LinkerInstance {
423            engine: self.engine,
424            path: self.path,
425            path_len: self.path_len,
426            strings: self.strings,
427            map: self.map,
428            allow_shadowing: self.allow_shadowing,
429            _marker: self._marker,
430        }
431    }
432
433    /// Defines a new host-provided function into this [`LinkerInstance`].
434    ///
435    /// This method is used to give host functions to wasm components. The
436    /// `func` provided will be callable from linked components with the type
437    /// signature dictated by `Params` and `Return`. The `Params` is a tuple of
438    /// types that will come from wasm and `Return` is a value coming from the
439    /// host going back to wasm.
440    ///
441    /// Additionally the `func` takes a
442    /// [`StoreContextMut`](crate::StoreContextMut) as its first parameter.
443    ///
444    /// Note that `func` must be an `Fn` and must also be `Send + Sync +
445    /// 'static`. Shared state within a func is typically accessed with the `T`
446    /// type parameter from [`Store<T>`](crate::Store) which is accessible
447    /// through the leading [`StoreContextMut<'_, T>`](crate::StoreContextMut)
448    /// argument which can be provided to the `func` given here.
449    ///
450    /// # Blocking / Async Behavior
451    ///
452    /// The host function `func` provided here is a blocking function from the
453    /// perspective of WebAssembly. WebAssembly, and Rust, will be blocked until
454    /// `func` completes.
455    ///
456    /// To define a function which is async on the host, but blocking to the
457    /// guest, see the [`func_wrap_async`] method.
458    ///
459    /// [`func_wrap_async`]: LinkerInstance::func_wrap_async
460    ///
461    /// # Errors
462    ///
463    /// This function will return an [`OutOfMemory`][crate::OutOfMemory] error when
464    /// memory allocation fails. See the `OutOfMemory` type's documentation for
465    /// details on Wasmtime's out-of-memory handling.
466    //
467    // TODO: needs more words and examples
468    pub fn func_wrap<F, Params, Return>(&mut self, name: &str, func: F) -> Result<()>
469    where
470        F: Fn(StoreContextMut<T>, Params) -> Result<Return> + Send + Sync + 'static,
471        Params: ComponentNamedList + Lift + 'static,
472        Return: ComponentNamedList + Lower + 'static,
473    {
474        self.insert(name, Definition::Func(HostFunc::func_wrap(func)?))?;
475        Ok(())
476    }
477
478    /// Defines a new host-provided async function into this [`LinkerInstance`].
479    ///
480    /// This function is similar to [`Self::func_wrap`] except it takes an async
481    /// host function instead of a blocking host function. The `F` function here
482    /// is intended to be:
483    ///
484    /// ```ignore
485    /// F: AsyncFn(StoreContextMut<'_, T>, Params) -> Result<Return>
486    /// ```
487    ///
488    /// however the returned future must be `Send` which is not possible to
489    /// bound at this time. This will be switched to an async closure once Rust
490    /// supports it.
491    ///
492    /// # Blocking / Async Behavior
493    ///
494    /// The function defined which WebAssembly calls will still appear as
495    /// blocking from the perspective of WebAssembly itself. The host, however,
496    /// can perform asynchronous operations without blocking the thread
497    /// performing a call.
498    ///
499    /// When defining host functions with this function, WebAssembly is invoked
500    /// on a separate stack within a Wasmtime-managed fiber (through the
501    /// `call_async`-style of invocation). This means that if the future
502    /// returned by `F` is not immediately ready then the fiber will be
503    /// suspended to block WebAssembly but not the host. When the future
504    /// becomes ready again the fiber will be resumed to continue execution
505    /// within WebAssembly.
506    ///
507    /// [`func_wrap_async`]: LinkerInstance::func_wrap_async
508    #[cfg(feature = "async")]
509    pub fn func_wrap_async<Params, Return, F>(&mut self, name: &str, f: F) -> Result<()>
510    where
511        F: Fn(
512                StoreContextMut<'_, T>,
513                Params,
514            ) -> Box<dyn Future<Output = Result<Return>> + Send + '_>
515            + Send
516            + Sync
517            + 'static,
518        Params: ComponentNamedList + Lift + 'static,
519        Return: ComponentNamedList + Lower + 'static,
520    {
521        self.insert(name, Definition::Func(HostFunc::func_wrap_async(f)?))?;
522        Ok(())
523    }
524
525    /// Defines a new host-provided async function into this [`LinkerInstance`].
526    ///
527    /// This function defines a host function available to call from
528    /// WebAssembly. WebAssembly may additionally make multiple invocations of
529    /// this function concurrently all at the same time. This function requires
530    /// the [`Config::wasm_component_model_async`] feature to be enabled.
531    ///
532    /// The function `f` provided will be invoked when called by WebAssembly.
533    /// WebAssembly components may then call `f` multiple times while previous
534    /// invocations of `f` are already running. Additionally while `f` is
535    /// running other host functions may be invoked.
536    ///
537    /// The `F` function here is intended to be:
538    ///
539    /// ```ignore
540    /// F: AsyncFn(&Accessor<T>, Params) -> Result<Return>
541    /// ```
542    ///
543    /// however the returned future must be `Send` which is not possible to
544    /// bound at this time. This will be switched to an async closure once Rust
545    /// supports it.
546    ///
547    /// The closure `f` is provided an [`Accessor`] which can be used to acquire
548    /// temporary, blocking, access to a [`StoreContextMut`] (through
549    /// [`Access`](crate::component::Access]). This models how a store is not
550    /// available to `f` across `await` points but it is temporarily available
551    /// while actively being polled.
552    ///
553    /// # Blocking / Async Behavior
554    ///
555    /// Unlike [`Self::func_wrap`] and [`Self::func_wrap_async`] this function
556    /// is asynchronous even from the perspective of guest WebAssembly. This
557    /// means that if `f` is not immediately resolved then the call from
558    /// WebAssembly will still return immediately (assuming it was lowered with
559    /// `async`). The closure `f` should not block the current thread and
560    /// should only perform blocking via `async` meaning that `f` won't block
561    /// either WebAssembly nor the host.
562    ///
563    /// Note that WebAssembly components can lower host functions both with and
564    /// without `async`. That means that even if a host function is defined in
565    /// the "concurrent" mode here a guest may still lower it synchronously. In
566    /// this situation Wasmtime will manage blocking the guest while the closure
567    /// `f` provided here completes. If a guest lowers this function with
568    /// `async`, though, then no blocking will happen.
569    ///
570    /// [`Config::wasm_component_model_async`]: crate::Config::wasm_component_model_async
571    /// [`func_wrap_async`]: LinkerInstance::func_wrap_async
572    #[cfg(feature = "component-model-async")]
573    pub fn func_wrap_concurrent<Params, Return, F>(&mut self, name: &str, f: F) -> Result<()>
574    where
575        T: 'static,
576        F: Fn(&Accessor<T>, Params) -> Pin<Box<dyn Future<Output = Result<Return>> + Send + '_>>
577            + Send
578            + Sync
579            + 'static,
580        Params: ComponentNamedList + Lift + 'static,
581        Return: ComponentNamedList + Lower + 'static,
582    {
583        if !self.engine.tunables().concurrency_support {
584            bail!("concurrent host functions require `Config::concurrency_support`");
585        }
586        self.insert(name, Definition::Func(HostFunc::func_wrap_concurrent(f)?))?;
587        Ok(())
588    }
589
590    /// Define a new host-provided function using dynamically typed values.
591    ///
592    /// The `name` provided is the name of the function to define and the
593    /// `func` provided is the host-defined closure to invoke when this
594    /// function is called.
595    ///
596    /// This function is the "dynamic" version of defining a host function as
597    /// compared to [`LinkerInstance::func_wrap`]. With
598    /// [`LinkerInstance::func_wrap`] a function's type is statically known but
599    /// with this method the `func` argument's type isn't known ahead of time.
600    /// That means that `func` can be by imported component so long as it's
601    /// imported as a matching name.
602    ///
603    /// Type information will be available at execution time, however. For
604    /// example when `func` is invoked the second argument, a `&[Val]` list,
605    /// contains [`Val`] entries that say what type they are. Additionally the
606    /// third argument, `&mut [Val]`, is the expected number of results. Note
607    /// that the expected types of the results cannot be learned during the
608    /// execution of `func`. Learning that would require runtime introspection
609    /// of a component.
610    ///
611    /// Return values, stored in the third argument of `&mut [Val]`, are
612    /// type-checked at runtime to ensure that they have the appropriate type.
613    /// A trap will be raised if they do not have the right type.
614    ///
615    /// # Examples
616    ///
617    /// ```
618    /// use wasmtime::{Store, Engine};
619    /// use wasmtime::component::{Component, Linker, Val};
620    ///
621    /// # fn main() -> wasmtime::Result<()> {
622    /// let engine = Engine::default();
623    /// let component = Component::new(
624    ///     &engine,
625    ///     r#"
626    ///         (component
627    ///             (import "thunk" (func $thunk))
628    ///             (import "is-even" (func $is-even (param "x" u32) (result bool)))
629    ///
630    ///             (core module $m
631    ///                 (import "" "thunk" (func $thunk))
632    ///                 (import "" "is-even" (func $is-even (param i32) (result i32)))
633    ///
634    ///                 (func (export "run")
635    ///                     call $thunk
636    ///
637    ///                     (call $is-even (i32.const 1))
638    ///                     if unreachable end
639    ///
640    ///                     (call $is-even (i32.const 2))
641    ///                     i32.eqz
642    ///                     if unreachable end
643    ///                 )
644    ///             )
645    ///             (core func $thunk (canon lower (func $thunk)))
646    ///             (core func $is-even (canon lower (func $is-even)))
647    ///             (core instance $i (instantiate $m
648    ///                 (with "" (instance
649    ///                     (export "thunk" (func $thunk))
650    ///                     (export "is-even" (func $is-even))
651    ///                 ))
652    ///             ))
653    ///
654    ///             (func (export "run") (canon lift (core func $i "run")))
655    ///         )
656    ///     "#,
657    /// )?;
658    ///
659    /// let mut linker = Linker::<()>::new(&engine);
660    ///
661    /// // Sample function that takes no arguments.
662    /// linker.root().func_new("thunk", |_store, _ty, params, results| {
663    ///     assert!(params.is_empty());
664    ///     assert!(results.is_empty());
665    ///     println!("Look ma, host hands!");
666    ///     Ok(())
667    /// })?;
668    ///
669    /// // This function takes one argument and returns one result.
670    /// linker.root().func_new("is-even", |_store, _ty, params, results| {
671    ///     assert_eq!(params.len(), 1);
672    ///     let param = match params[0] {
673    ///         Val::U32(n) => n,
674    ///         _ => panic!("unexpected type"),
675    ///     };
676    ///
677    ///     assert_eq!(results.len(), 1);
678    ///     results[0] = Val::Bool(param % 2 == 0);
679    ///     Ok(())
680    /// })?;
681    ///
682    /// let mut store = Store::new(&engine, ());
683    /// let instance = linker.instantiate(&mut store, &component)?;
684    /// let run = instance.get_typed_func::<(), ()>(&mut store, "run")?;
685    /// run.call(&mut store, ())?;
686    /// # Ok(())
687    /// # }
688    /// ```
689    ///
690    /// # Errors
691    ///
692    /// This function will return an [`OutOfMemory`][crate::OutOfMemory] error when
693    /// memory allocation fails. See the `OutOfMemory` type's documentation for
694    /// details on Wasmtime's out-of-memory handling.
695    pub fn func_new(
696        &mut self,
697        name: &str,
698        func: impl Fn(StoreContextMut<'_, T>, types::ComponentFunc, &[Val], &mut [Val]) -> Result<()>
699        + Send
700        + Sync
701        + 'static,
702    ) -> Result<()> {
703        self.insert(name, Definition::Func(HostFunc::func_new(func)?))?;
704        Ok(())
705    }
706
707    /// Define a new host-provided async function using dynamic types.
708    ///
709    /// As [`Self::func_wrap_async`] is a dual of [`Self::func_wrap`], this
710    /// function is the dual of [`Self::func_new`].
711    ///
712    /// For documentation on blocking behavior see [`Self::func_wrap_async`].
713    #[cfg(feature = "async")]
714    pub fn func_new_async<F>(&mut self, name: &str, func: F) -> Result<()>
715    where
716        F: for<'a> Fn(
717                StoreContextMut<'a, T>,
718                types::ComponentFunc,
719                &'a [Val],
720                &'a mut [Val],
721            ) -> Box<dyn Future<Output = Result<()>> + Send + 'a>
722            + Send
723            + Sync
724            + 'static,
725    {
726        self.insert(name, Definition::Func(HostFunc::func_new_async(func)?))?;
727        Ok(())
728    }
729
730    /// Define a new host-provided async function using dynamic types.
731    ///
732    /// As [`Self::func_wrap_concurrent`] is a dual of [`Self::func_wrap`], this
733    /// function is the dual of [`Self::func_new`].
734    ///
735    /// For documentation on async/blocking behavior see
736    /// [`Self::func_wrap_concurrent`].
737    #[cfg(feature = "component-model-async")]
738    pub fn func_new_concurrent<F>(&mut self, name: &str, f: F) -> Result<()>
739    where
740        T: 'static,
741        F: for<'a> Fn(
742                &'a Accessor<T>,
743                types::ComponentFunc,
744                &'a [Val],
745                &'a mut [Val],
746            ) -> Pin<Box<dyn Future<Output = Result<()>> + Send + 'a>>
747            + Send
748            + Sync
749            + 'static,
750    {
751        if !self.engine.tunables().concurrency_support {
752            bail!("concurrent host functions require `Config::concurrency_support`");
753        }
754        self.insert(name, Definition::Func(HostFunc::func_new_concurrent(f)?))?;
755        Ok(())
756    }
757
758    /// Defines a [`Module`] within this instance.
759    ///
760    /// This can be used to provide a core wasm [`Module`] as an import to a
761    /// component. The [`Module`] provided is saved within the linker for the
762    /// specified `name` in this instance.
763    ///
764    /// # Errors
765    ///
766    /// This function will return an [`OutOfMemory`][crate::OutOfMemory] error when
767    /// memory allocation fails. See the `OutOfMemory` type's documentation for
768    /// details on Wasmtime's out-of-memory handling.
769    pub fn module(&mut self, name: &str, module: &Module) -> Result<()> {
770        self.insert(name, Definition::Module(module.clone()))?;
771        Ok(())
772    }
773
774    /// Defines a new resource of a given [`ResourceType`] in this linker.
775    ///
776    /// This function is used to specify resources defined in the host.
777    ///
778    /// The `name` argument is the name to define the resource within this
779    /// linker.
780    ///
781    /// The `dtor` provided is a destructor that will get invoked when an owned
782    /// version of this resource is destroyed from the guest. Note that this
783    /// destructor is not called when a host-owned resource is destroyed as it's
784    /// assumed the host knows how to handle destroying its own resources.
785    ///
786    /// The `dtor` closure is provided the store state as the first argument
787    /// along with the representation of the resource that was just destroyed.
788    ///
789    /// [`Resource<U>`]: crate::component::Resource
790    ///
791    /// # Errors
792    ///
793    /// The provided `dtor` closure returns an error if something goes wrong
794    /// when a guest calls the `dtor` to drop a `Resource<T>` such as
795    /// a runtime trap or a runtime limit being exceeded.
796    ///
797    /// This function will return an [`OutOfMemory`][crate::OutOfMemory] error when
798    /// memory allocation fails. See the `OutOfMemory` type's documentation for
799    /// details on Wasmtime's out-of-memory handling.
800    pub fn resource(
801        &mut self,
802        name: &str,
803        ty: ResourceType,
804        dtor: impl Fn(StoreContextMut<'_, T>, u32) -> Result<()> + Send + Sync + 'static,
805    ) -> Result<()> {
806        let dtor = try_new::<Arc<_>>(crate::func::HostFunc::wrap(
807            &self.engine,
808            move |mut cx: crate::Caller<'_, T>, (param,): (u32,)| dtor(cx.as_context_mut(), param),
809        )?)?;
810        self.insert(name, Definition::Resource(ty, dtor))?;
811        Ok(())
812    }
813
814    /// Identical to [`Self::resource`], except that it takes an async destructor.
815    #[cfg(feature = "async")]
816    pub fn resource_async<F>(&mut self, name: &str, ty: ResourceType, dtor: F) -> Result<()>
817    where
818        T: Send,
819        F: Fn(StoreContextMut<'_, T>, u32) -> Box<dyn Future<Output = Result<()>> + Send + '_>
820            + Send
821            + Sync
822            + 'static,
823    {
824        let dtor = try_new::<Arc<_>>(crate::func::HostFunc::wrap_async(
825            &self.engine,
826            move |cx: crate::Caller<'_, T>, (param,): (u32,)| dtor(cx.into(), param),
827        )?)?;
828        self.insert(name, Definition::Resource(ty, dtor))?;
829        Ok(())
830    }
831
832    /// Identical to [`Self::resource`], except that it takes a concurrent destructor.
833    #[cfg(feature = "component-model-async")]
834    pub fn resource_concurrent<F>(&mut self, name: &str, ty: ResourceType, dtor: F) -> Result<()>
835    where
836        T: Send + 'static,
837        F: Fn(&Accessor<T>, u32) -> Pin<Box<dyn Future<Output = Result<()>> + Send + '_>>
838            + Send
839            + Sync
840            + 'static,
841    {
842        if !self.engine.tunables().concurrency_support {
843            bail!("concurrent host functions require `Config::concurrency_support`");
844        }
845        // TODO: This isn't really concurrent -- it requires exclusive access to
846        // the store for the duration of the call, preventing guest code from
847        // running until it completes.  We should make it concurrent and clean
848        // up the implementation to avoid using e.g. `Accessor::new` and
849        // `tls::set` directly.
850        let dtor = Arc::new(dtor);
851        let dtor = Arc::new(crate::func::HostFunc::wrap_async(
852            &self.engine,
853            move |mut cx: crate::Caller<'_, T>, (param,): (u32,)| {
854                let dtor = dtor.clone();
855                Box::new(async move {
856                    let mut store = cx.as_context_mut();
857                    let accessor =
858                        &Accessor::new(crate::store::StoreToken::new(store.as_context_mut()));
859                    let mut future = std::pin::pin!(dtor(accessor, param));
860                    std::future::poll_fn(|cx| {
861                        crate::component::concurrent::tls::set(store.0, || future.as_mut().poll(cx))
862                    })
863                    .await
864                })
865            },
866        )?);
867        self.insert(name, Definition::Resource(ty, dtor))?;
868        Ok(())
869    }
870
871    /// Defines a nested instance within this instance.
872    ///
873    /// This can be used to describe arbitrarily nested levels of instances
874    /// within a linker to satisfy nested instance exports of components.
875    pub fn instance(&mut self, name: &str) -> Result<LinkerInstance<'_, T>> {
876        self.as_mut().into_instance(name)
877    }
878
879    /// Same as [`LinkerInstance::instance`] except with different lifetime
880    /// parameters.
881    pub fn into_instance(mut self, name: &str) -> Result<Self> {
882        let name = self.insert(name, Definition::Instance(NameMap::default()))?;
883        self.map = match self.map.raw_get_mut(&name) {
884            Some(Definition::Instance(map)) => map,
885            _ => unreachable!(),
886        };
887        self.path.truncate(self.path_len);
888        self.path.push(name);
889        self.path_len += 1;
890        Ok(self)
891    }
892
893    fn insert(&mut self, name: &str, item: Definition) -> Result<Atom> {
894        self.map
895            .insert(name, self.strings, self.allow_shadowing, item)
896    }
897
898    fn get(&self, name: &str) -> Option<&Definition> {
899        self.map.get(name, self.strings)
900    }
901}