marine_wasm_backend_traits/
imports.rs

1/*
2 * Copyright 2023 Fluence Labs Limited
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 *     http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17use crate::errors::*;
18
19use crate::AsContext;
20use crate::WasmBackend;
21use crate::WType;
22
23use futures::future::BoxFuture;
24
25use std::borrow::Cow;
26use std::fmt::Formatter;
27use std::sync::Arc;
28
29/// A "Linker" object, that is used to match functions with module imports during instantiation.
30/// Cloning is a cheap operation for this object. All clones refer to the same data in store.
31pub trait Imports<WB: WasmBackend>: Clone {
32    /// Creates a new empty object.
33    fn new(store: &mut <WB as WasmBackend>::Store) -> Self;
34
35    /// Inserts a function with name `name` to the namespace `module`.
36    /// # Errors:
37    ///     An error returned if such combination of `module` and `name` already has an associated function.
38    fn insert(
39        &mut self,
40        store: &impl AsContext<WB>,
41        module: impl Into<String>,
42        name: impl Into<String>,
43        func: <WB as WasmBackend>::HostFunction,
44    ) -> Result<(), ImportError>;
45
46    /// Inserts several named functions to the same namespace `module` at once, an equivalent to multiple calls of `insert`.
47    /// # Errors:
48    ///     An error returned if such combination of `module` and `name` already has an associated function.
49    ///
50    fn register<S, I>(
51        &mut self,
52        store: &impl AsContext<WB>,
53        name: S,
54        namespace: I,
55    ) -> Result<(), ImportError>
56    where
57        S: Into<String>,
58        I: IntoIterator<Item = (String, <WB as WasmBackend>::HostFunction)>;
59}
60
61/// A type representing function signature.
62#[derive(Clone)]
63pub struct FuncSig {
64    params: Cow<'static, [WType]>,
65    returns: Cow<'static, [WType]>,
66}
67
68impl FuncSig {
69    pub fn new<Params, Returns>(params: Params, returns: Returns) -> Self
70    where
71        Params: Into<Cow<'static, [WType]>>,
72        Returns: Into<Cow<'static, [WType]>>,
73    {
74        Self {
75            params: params.into(),
76            returns: returns.into(),
77        }
78    }
79
80    pub fn params(&self) -> &[WType] {
81        &self.params
82    }
83
84    pub fn returns(&self) -> &[WType] {
85        &self.returns
86    }
87}
88
89impl std::fmt::Debug for FuncSig {
90    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
91        write!(
92            f,
93            "params: {:?}, returns: {:?}",
94            self.params(),
95            self.returns
96        )
97    }
98}
99
100pub type TypedFuncFuture<'c, Rets> = BoxFuture<'c, RuntimeResult<Rets>>;
101
102pub type TypedFunc<WB, Args, Rets> = Arc<
103    dyn for<'ctx1, 'ctx2> Fn(
104            &'ctx1 mut <WB as WasmBackend>::ContextMut<'ctx2>,
105            Args,
106        ) -> TypedFuncFuture<'ctx1, Rets>
107        + Sync
108        + Send
109        + 'static,
110>;
111
112pub trait FuncGetter<WB: WasmBackend, Args, Rets> {
113    /// Gets an export function from the calling instance.
114    fn get_func(&mut self, name: &str) -> ResolveResult<TypedFunc<WB, Args, Rets>>;
115}