linera_witty/runtime/wasmtime/
export_function.rs

1// Copyright (c) Zefchain Labs, Inc.
2// SPDX-License-Identifier: Apache-2.0
3
4//! Wasmtime support for host functions exported to guests Wasm instances.
5
6#![allow(clippy::let_unit_value)]
7
8use wasmtime::{Caller, Linker, WasmRet, WasmTy};
9
10use crate::{primitive_types::MaybeFlatType, ExportFunction, RuntimeError};
11
12/// Implements [`ExportFunction`] for Wasmtime's [`Linker`] using the supported function
13/// signatures.
14macro_rules! export_function {
15    ($( $names:ident: $types:ident ),*) => {
16        impl<Handler, $( $types, )* FlatResult, Data>
17            ExportFunction<Handler, ($( $types, )*), FlatResult> for Linker<Data>
18        where
19            $( $types: WasmTy, )*
20            FlatResult: MaybeFlatType + WasmRet,
21            Handler:
22                Fn(Caller<'_, Data>, ($( $types, )*)) -> Result<FlatResult, RuntimeError>
23                + Send
24                + Sync
25                + 'static,
26        {
27            fn export(
28                &mut self,
29                module_name: &str,
30                function_name: &str,
31                handler: Handler,
32            ) -> Result<(), RuntimeError> {
33                self.func_wrap(
34                    module_name,
35                    function_name,
36                    move |
37                        caller: Caller<'_, Data>,
38                        $( $names: $types ),*
39                    | -> anyhow::Result<FlatResult> {
40                        let response = handler(caller, ($( $names, )*))?;
41                        Ok(response)
42                    },
43                )
44                .map_err(RuntimeError::Wasmtime)?;
45                Ok(())
46            }
47        }
48    };
49}
50
51repeat_macro!(export_function =>
52    a: A,
53    b: B,
54    c: C,
55    d: D,
56    e: E,
57    f: F,
58    g: G,
59    h: H,
60    i: I,
61    j: J,
62    k: K,
63    l: L,
64    m: M,
65    n: N,
66    o: O,
67    p: P,
68    q: Q,
69);