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
324
325
326
327
328
329
#![allow(dead_code)]
#![allow(unused_variables)]

use soroban_env_common::call_macro_with_all_host_functions;

use super::{Env, EnvBase, Object, RawVal, Status, Symbol};
#[cfg(target_family = "wasm")]
use static_assertions as sa;

/// The [Guest] is the implementation of the [Env] interface seen and used by
/// contracts built into WASM for execution within a WASM VM. It is a 0-sized
/// "stub" type implementation of the [Env] interface that forwards each [Env]
/// method to an external function, imported from its runtime environment. This
/// implementation is automatically generated and has no interesting content.
#[derive(Copy, Clone, Default)]
pub struct Guest;

// The Guest struct is only meaningful when compiling for the WASM target. All
// these fns should not be called at all because the SDK's choice of Env should be
// Host for a non-WASM build.
#[cfg(not(target_family = "wasm"))]
impl EnvBase for Guest {
    fn as_mut_any(&mut self) -> &mut dyn core::any::Any {
        unimplemented!()
    }

    fn check_same_env(&self, other: &Self) {
        unimplemented!()
    }

    fn deep_clone(&self) -> Self {
        unimplemented!()
    }

    fn bytes_copy_from_slice(
        &self,
        b: Object,
        b_pos: RawVal,
        mem: &[u8],
    ) -> Result<Object, Status> {
        unimplemented!()
    }

    fn bytes_copy_to_slice(&self, b: Object, b_pos: RawVal, mem: &mut [u8]) -> Result<(), Status> {
        unimplemented!()
    }

    fn bytes_new_from_slice(&self, mem: &[u8]) -> Result<Object, Status> {
        unimplemented!()
    }

    fn log_static_fmt_val(&self, fmt: &'static str, v: RawVal) -> Result<(), Status> {
        unimplemented!()
    }

    fn log_static_fmt_static_str(&self, fmt: &'static str, s: &'static str) -> Result<(), Status> {
        unimplemented!()
    }

    fn log_static_fmt_val_static_str(
        &self,
        fmt: &'static str,
        v: RawVal,
        s: &'static str,
    ) -> Result<(), Status> {
        unimplemented!()
    }

    fn log_static_fmt_general(
        &self,
        fmt: &'static str,
        vals: &[RawVal],
        strs: &[&'static str],
    ) -> Result<(), Status> {
        unimplemented!()
    }
}

#[cfg(target_family = "wasm")]
impl EnvBase for Guest {
    fn as_mut_any(&mut self) -> &mut dyn core::any::Any {
        return self;
    }

    fn check_same_env(&self, other: &Self) {
        ()
    }

    fn deep_clone(&self) -> Self {
        Self
    }

    fn bytes_copy_from_slice(
        &self,
        b: Object,
        b_pos: RawVal,
        mem: &[u8],
    ) -> Result<Object, Status> {
        sa::assert_eq_size!(u32, *const u8);
        sa::assert_eq_size!(u32, usize);
        let lm_pos: RawVal = RawVal::from_u32(mem.as_ptr() as u32);
        let len: RawVal = RawVal::from_u32(mem.len() as u32);
        // NB: any failure in the host function here will trap the guest,
        // not return, so we only have to code the happy path.
        Ok(self.bytes_copy_from_linear_memory(b, b_pos, lm_pos, len))
    }

    fn bytes_copy_to_slice(&self, b: Object, b_pos: RawVal, mem: &mut [u8]) -> Result<(), Status> {
        sa::assert_eq_size!(u32, *const u8);
        sa::assert_eq_size!(u32, usize);
        let lm_pos: RawVal = RawVal::from_u32(mem.as_ptr() as u32);
        let len: RawVal = RawVal::from_u32(mem.len() as u32);
        self.bytes_copy_to_linear_memory(b, b_pos, lm_pos, len);
        Ok(())
    }

    fn bytes_new_from_slice(&self, mem: &[u8]) -> Result<Object, Status> {
        sa::assert_eq_size!(u32, *const u8);
        sa::assert_eq_size!(u32, usize);
        let lm_pos: RawVal = RawVal::from_u32(mem.as_ptr() as u32);
        let len: RawVal = RawVal::from_u32(mem.len() as u32);
        Ok(self.bytes_new_from_linear_memory(lm_pos, len))
    }

    fn log_static_fmt_val(&self, fmt: &'static str, v: RawVal) -> Result<(), Status> {
        // TODO: It's possible we might want to do something in the wasm
        // case with static strings similar to the bytes functions above,
        // eg. decay the strings to u32 values and pass them to the host as linear
        // memory locations for capture into the debug-events buffer,
        // but for the time being we're going to _not_ do that because
        // we assume users building for wasm want their static strings
        // _removed_ from the bytes statically (it's also somewhat annoying
        // to implement the capture of static strings into the debug buffer,
        // it makes the debug buffer into non-Send+Sync and then we need
        // to remove it from the HostError, report separately from HostError's
        // Debug impl)
        Ok(())
    }

    fn log_static_fmt_static_str(&self, fmt: &'static str, s: &'static str) -> Result<(), Status> {
        // Intentionally a no-op in this cfg. See above.
        Ok(())
    }

    fn log_static_fmt_val_static_str(
        &self,
        fmt: &'static str,
        v: RawVal,
        s: &'static str,
    ) -> Result<(), Status> {
        // Intentionally a no-op in this cfg. See above.
        Ok(())
    }

    fn log_static_fmt_general(
        &self,
        fmt: &'static str,
        vals: &[RawVal],
        strs: &[&'static str],
    ) -> Result<(), Status> {
        // Intentionally a no-op in this cfg. See above.
        Ok(())
    }
}

///////////////////////////////////////////////////////////////////////////////
/// X-macro use: impl Env for Guest
///////////////////////////////////////////////////////////////////////////////

// This is a helper macro used only by impl_env_for_guest below. It consumes a
// token-tree of the form:
//
//  {fn $fn_id:ident $args:tt -> $ret:ty}
//
// and produces the the corresponding method definition to be used in the
// Guest implementation of the Env trait (calling through to the corresponding
// unsafe extern function).
macro_rules! guest_function_helper {
    {$mod_id:ident, fn $fn_id:ident($($arg:ident:$type:ty),*) -> $ret:ty}
    =>
    {
        fn $fn_id(&self, $($arg:$type),*) -> $ret {
            unsafe {
                $mod_id::$fn_id($($arg),*)
            }
        }
    };
}

// This is a callback macro that pattern-matches the token-tree passed by the
// x-macro (call_macro_with_all_host_functions) and produces a suite of
// forwarding-method definitions, which it places in the body of the declaration
// of the implementation of Env for Guest.
macro_rules! impl_env_for_guest {
    {
        $(
            // This outer pattern matches a single 'mod' block of the token-tree
            // passed from the x-macro to this macro. It is embedded in a `$()*`
            // pattern-repetition matcher so that it will match all provided
            // 'mod' blocks provided.
            $(#[$mod_attr:meta])*
            mod $mod_id:ident $mod_str:literal
            {
                $(
                    // This inner pattern matches a single function description
                    // inside a 'mod' block in the token-tree passed from the
                    // x-macro to this macro. It is embedded in a `$()*`
                    // pattern-repetition matcher so that it will match all such
                    // descriptions.
                    $(#[$fn_attr:meta])*
                    { $fn_str:literal, fn $fn_id:ident $args:tt -> $ret:ty }
                )*
            }
        )*
    }

    =>  // The part of the macro above this line is a matcher; below is its expansion.

    {
        // This macro expands to a single item: the implementation of Env for
        // the Guest struct used by client contract code running in a WASM VM.
        impl Env for Guest
        {
            $(
                $(
                    // This invokes the guest_function_helper! macro above
                    // passing only the relevant parts of the declaration
                    // matched by the inner pattern above. It is embedded in two
                    // nested `$()*` pattern-repetition expanders that
                    // correspond to the pattern-repetition matchers in the
                    // match section, but we ignore the structure of the 'mod'
                    // block repetition-level from the outer pattern in the
                    // expansion, flattening all functions from all 'mod' blocks
                    // into the implementation of Env for Guest.
                    guest_function_helper!{$mod_id, fn $fn_id $args -> $ret}
                )*
            )*
        }
    };
}

// Here we invoke the x-macro passing generate_env_trait as its callback macro.
call_macro_with_all_host_functions! { impl_env_for_guest }

///////////////////////////////////////////////////////////////////////////////
/// X-macro use: extern mod blocks
///////////////////////////////////////////////////////////////////////////////

// This is a helper macro used only by impl_env_for_guest below. It consumes a
// token-tree of the form:
//
//  {fn $fn_id:ident $args:tt -> $ret:ty}
//
// and produces the the corresponding method definition to be used in the
// Guest implementation of the Env trait (calling through to the corresponding
// unsafe extern function).
macro_rules! extern_function_helper {
    {
        $fn_str:literal, $(#[$attr:meta])* fn $fn_id:ident($($arg:ident:$type:ty),*) -> $ret:ty
    }
    =>
    {
        #[cfg_attr(target_family = "wasm", link_name = $fn_str)]
        $(#[$attr])*
        pub(crate) fn $fn_id($($arg:$type),*) -> $ret;
    };
}

// This is a callback macro that pattern-matches the token-tree passed by the
// x-macro (call_macro_with_all_host_functions) and produces a set of mod
// items containing extern "C" blocks, each containing extern function
// declarations.
macro_rules! generate_extern_modules {
    {
        $(
            // This outer pattern matches a single 'mod' block of the token-tree
            // passed from the x-macro to this macro. It is embedded in a `$()*`
            // pattern-repetition matcher so that it will match all provided
            // 'mod' blocks provided.
            $(#[$mod_attr:meta])*
            mod $mod_id:ident $mod_str:literal
            {
                $(
                    // This inner pattern matches a single function description
                    // inside a 'mod' block in the token-tree passed from the
                    // x-macro to this macro. It is embedded in a `$()*`
                    // pattern-repetition matcher so that it will match all such
                    // descriptions.
                    $(#[$fn_attr:meta])*
                    { $fn_str:literal, fn $fn_id:ident $args:tt -> $ret:ty }
                )*
            }
        )*
    }

    =>  // The part of the macro above this line is a matcher; below is its expansion.

    {
        // This macro expands to a set of mod items, each declaring all the extern fns
        // available for the `impl Env for Guest` methods above to call through to.
        $(
            // Unlike the other uses of the x-macro that "flatten" the
            // mod-and-fn structure of the matched token-tree, this callback
            // macro's expansion preserves the structure, creating a nested set
            // of mods and fns. There is therefore a mod declaration between the
            // outer and inner `$()*` pattern-repetition expanders.
            $(#[$mod_attr])*
            mod $mod_id {
                #[allow(unused_imports)]
                use crate::{RawVal,Object,Symbol,Status};
                #[link(wasm_import_module = $mod_str)]
                extern "C" {
                    $(
                        // This invokes the extern_function_helper! macro above
                        // passing only the relevant parts of the declaration
                        // matched by the inner pattern above. It is embedded in
                        // one `$()*` pattern-repetition expander so that it
                        // repeats only for the part of each mod that the
                        // corresponding pattern-repetition matcher.
                        extern_function_helper!{$fn_str, $(#[$fn_attr])* fn $fn_id $args -> $ret}
                    )*
                }
            }
        )*
    };
}

// Here we invoke the x-macro passing generate_extern_modules as its callback macro.
call_macro_with_all_host_functions! { generate_extern_modules }