1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
use crate::store::AsStoreRef;
use crate::{Extern, Function, Global, Memory, Table, TypedFunction, WasmTypeList};
use indexmap::IndexMap;
use std::fmt;
use std::iter::{ExactSizeIterator, FromIterator};
use thiserror::Error;

/// The `ExportError` can happen when trying to get a specific
/// export [`Extern`] from the [`Instance`] exports.
///
/// [`Instance`]: crate::Instance
///
/// # Examples
///
/// ## Incompatible export type
///
/// ```should_panic
/// # use wasmer::{imports, wat2wasm, Function, Instance, Module, Store, Type, Value, ExportError};
/// # let mut store = Store::default();
/// # let wasm_bytes = wat2wasm(r#"
/// # (module
/// #   (global $one (export "glob") f32 (f32.const 1)))
/// # "#.as_bytes()).unwrap();
/// # let module = Module::new(&store, wasm_bytes).unwrap();
/// # let import_object = imports! {};
/// # let instance = Instance::new(&mut store, &module, &import_object).unwrap();
/// #
/// // This results with an error: `ExportError::IncompatibleType`.
/// let export = instance.exports.get_function("glob").unwrap();
/// ```
///
/// ## Missing export
///
/// ```should_panic
/// # use wasmer::{imports, wat2wasm, Function, Instance, Module, Store, Type, Value, ExportError};
/// # let mut store = Store::default();
/// # let wasm_bytes = wat2wasm("(module)".as_bytes()).unwrap();
/// # let module = Module::new(&store, wasm_bytes).unwrap();
/// # let import_object = imports! {};
/// # let instance = Instance::new(&mut store, &module, &import_object).unwrap();
/// #
/// // This results with an error: `ExportError::Missing`.
/// let export = instance.exports.get_function("unknown").unwrap();
/// ```
#[derive(Error, Debug)]
pub enum ExportError {
    /// An error than occurs when the exported type and the expected type
    /// are incompatible.
    #[error("Incompatible Export Type")]
    IncompatibleType,
    /// This error arises when an export is missing
    #[error("Missing export {0}")]
    Missing(String),
}

/// Exports is a special kind of map that allows easily unwrapping
/// the types of instances.
///
/// TODO: add examples of using exports
#[derive(Clone, Default, PartialEq, Eq)]
pub struct Exports {
    map: IndexMap<String, Extern>,
}

impl Exports {
    /// Creates a new `Exports`.
    pub fn new() -> Self {
        Default::default()
    }

    /// Creates a new `Exports` with capacity `n`.
    pub fn with_capacity(n: usize) -> Self {
        Self {
            map: IndexMap::with_capacity(n),
        }
    }

    /// Return the number of exports in the `Exports` map.
    pub fn len(&self) -> usize {
        self.map.len()
    }

    /// Return whether or not there are no exports
    pub fn is_empty(&self) -> bool {
        self.len() == 0
    }

    /// Insert a new export into this `Exports` map.
    pub fn insert<S, E>(&mut self, name: S, value: E)
    where
        S: Into<String>,
        E: Into<Extern>,
    {
        self.map.insert(name.into(), value.into());
    }

    /// Get an export given a `name`.
    ///
    /// The `get` method is specifically made for usage inside of
    /// Rust APIs, as we can detect what's the desired type easily.
    ///
    /// If you want to get an export dynamically with type checking
    /// please use the following functions: `get_func`, `get_memory`,
    /// `get_table` or `get_global` instead.
    ///
    /// If you want to get an export dynamically handling manually
    /// type checking manually, please use `get_extern`.
    pub fn get<'a, T: Exportable<'a>>(&'a self, name: &str) -> Result<&'a T, ExportError> {
        match self.map.get(name) {
            None => Err(ExportError::Missing(name.to_string())),
            Some(extern_) => T::get_self_from_extern(extern_),
        }
    }

    /// Get an export as a `Global`.
    pub fn get_global(&self, name: &str) -> Result<&Global, ExportError> {
        self.get(name)
    }

    /// Get an export as a `Memory`.
    pub fn get_memory(&self, name: &str) -> Result<&Memory, ExportError> {
        self.get(name)
    }

    /// Get an export as a `Table`.
    pub fn get_table(&self, name: &str) -> Result<&Table, ExportError> {
        self.get(name)
    }

    /// Get an export as a `Func`.
    pub fn get_function(&self, name: &str) -> Result<&Function, ExportError> {
        self.get(name)
    }

    #[deprecated(
        since = "3.0.0",
        note = "get_native_function() has been renamed to get_typed_function(), just like NativeFunc has been renamed to TypedFunction."
    )]
    /// Get an export as a `TypedFunction`.
    pub fn get_native_function<Args, Rets>(
        &self,
        store: &impl AsStoreRef,
        name: &str,
    ) -> Result<TypedFunction<Args, Rets>, ExportError>
    where
        Args: WasmTypeList,
        Rets: WasmTypeList,
    {
        self.get_typed_function(store, name)
    }

    /// Get an export as a `TypedFunction`.
    pub fn get_typed_function<Args, Rets>(
        &self,
        store: &impl AsStoreRef,
        name: &str,
    ) -> Result<TypedFunction<Args, Rets>, ExportError>
    where
        Args: WasmTypeList,
        Rets: WasmTypeList,
    {
        self.get_function(name)?
            .typed(store)
            .map_err(|_| ExportError::IncompatibleType)
    }

    /// Hack to get this working with nativefunc too
    pub fn get_with_generics<'a, T, Args, Rets>(&'a self, name: &str) -> Result<T, ExportError>
    where
        Args: WasmTypeList,
        Rets: WasmTypeList,
        T: ExportableWithGenerics<'a, Args, Rets>,
    {
        match self.map.get(name) {
            None => Err(ExportError::Missing(name.to_string())),
            Some(extern_) => T::get_self_from_extern_with_generics(extern_),
        }
    }

    /// Get an export as an `Extern`.
    pub fn get_extern(&self, name: &str) -> Option<&Extern> {
        self.map.get(name)
    }

    /// Returns true if the `Exports` contains the given export name.
    pub fn contains<S>(&self, name: S) -> bool
    where
        S: Into<String>,
    {
        self.map.contains_key(&name.into())
    }

    /// Get an iterator over the exports.
    pub fn iter(&self) -> ExportsIterator<impl Iterator<Item = (&String, &Extern)>> {
        ExportsIterator {
            iter: self.map.iter(),
        }
    }
}

impl fmt::Debug for Exports {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        f.debug_set().entries(self.iter()).finish()
    }
}

/// An iterator over exports.
pub struct ExportsIterator<'a, I>
where
    I: Iterator<Item = (&'a String, &'a Extern)> + Sized,
{
    iter: I,
}

impl<'a, I> Iterator for ExportsIterator<'a, I>
where
    I: Iterator<Item = (&'a String, &'a Extern)> + Sized,
{
    type Item = (&'a String, &'a Extern);

    fn next(&mut self) -> Option<Self::Item> {
        self.iter.next()
    }
}

impl<'a, I> ExactSizeIterator for ExportsIterator<'a, I>
where
    I: Iterator<Item = (&'a String, &'a Extern)> + ExactSizeIterator + Sized,
{
    fn len(&self) -> usize {
        self.iter.len()
    }
}

impl<'a, I> ExportsIterator<'a, I>
where
    I: Iterator<Item = (&'a String, &'a Extern)> + Sized,
{
    /// Get only the functions.
    pub fn functions(self) -> impl Iterator<Item = (&'a String, &'a Function)> + Sized {
        self.iter.filter_map(|(name, export)| match export {
            Extern::Function(function) => Some((name, function)),
            _ => None,
        })
    }

    /// Get only the memories.
    pub fn memories(self) -> impl Iterator<Item = (&'a String, &'a Memory)> + Sized {
        self.iter.filter_map(|(name, export)| match export {
            Extern::Memory(memory) => Some((name, memory)),
            _ => None,
        })
    }

    /// Get only the globals.
    pub fn globals(self) -> impl Iterator<Item = (&'a String, &'a Global)> + Sized {
        self.iter.filter_map(|(name, export)| match export {
            Extern::Global(global) => Some((name, global)),
            _ => None,
        })
    }

    /// Get only the tables.
    pub fn tables(self) -> impl Iterator<Item = (&'a String, &'a Table)> + Sized {
        self.iter.filter_map(|(name, export)| match export {
            Extern::Table(table) => Some((name, table)),
            _ => None,
        })
    }
}

impl FromIterator<(String, Extern)> for Exports {
    fn from_iter<I: IntoIterator<Item = (String, Extern)>>(iter: I) -> Self {
        Self {
            map: IndexMap::from_iter(iter),
        }
    }
}

impl IntoIterator for Exports {
    type IntoIter = indexmap::map::IntoIter<String, Extern>;
    type Item = (String, Extern);

    fn into_iter(self) -> Self::IntoIter {
        self.map.into_iter()
    }
}

impl<'a> IntoIterator for &'a Exports {
    type IntoIter = indexmap::map::Iter<'a, String, Extern>;
    type Item = (&'a String, &'a Extern);

    fn into_iter(self) -> Self::IntoIter {
        self.map.iter()
    }
}

/// This trait is used to mark types as gettable from an [`Instance`].
///
/// [`Instance`]: crate::Instance
pub trait Exportable<'a>: Sized {
    /// Implementation of how to get the export corresponding to the implementing type
    /// from an [`Instance`] by name.
    ///
    /// [`Instance`]: crate::Instance
    fn get_self_from_extern(_extern: &'a Extern) -> Result<&'a Self, ExportError>;
}

/// A trait for accessing exports (like [`Exportable`]) but it takes generic
/// `Args` and `Rets` parameters so that `TypedFunction` can be accessed directly
/// as well.
pub trait ExportableWithGenerics<'a, Args: WasmTypeList, Rets: WasmTypeList>: Sized {
    /// Get an export with the given generics.
    fn get_self_from_extern_with_generics(_extern: &'a Extern) -> Result<Self, ExportError>;
}

/// We implement it for all concrete [`Exportable`] types (that are `Clone`)
/// with empty `Args` and `Rets`.
impl<'a, T: Exportable<'a> + Clone + 'static> ExportableWithGenerics<'a, (), ()> for T {
    fn get_self_from_extern_with_generics(_extern: &'a Extern) -> Result<Self, ExportError> {
        T::get_self_from_extern(_extern).map(|i| i.clone())
    }
}