wasi_virt_layer-cli 0.2.2

CLI for the wasi_virt_layer crate
Documentation
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
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
//! Provides mechanisms to generate unique non-colliding crate identifiers and exports for WASM modules.

use crate::{
    generator::{
        abi_connect::Wasip1ABIName, memory::MemoryUniqueName, shared_global::SharedGlobalFnsName,
        special_func::SpecialFuncUniqueName, start_section::StartAlternativeName,
        threads::ThreadsSpawnName,
    },
    util::WasmName,
};

/// Represents a unique, non-colliding name element within the generated WASM structure.
#[derive(Debug, Eq, PartialEq, Hash)]
pub enum UniqueName<'a, 'b> {
    /// A unique name corresponding to an alternative start section.
    StartAlternative(&'a StartAlternativeName),
    /// A unique name corresponding to shared global functions.
    SharedGlobalFns(&'a SharedGlobalFnsName),
    /// A unique name corresponding to WASI P1 ABI function replacements.
    Wasip1ABI(&'a Wasip1ABIName<'b>),
    /// A unique name corresponding to thread spawning logic.
    ThreadsSpawn(&'a ThreadsSpawnName<'b>),
    /// A unique name corresponding to special initialization or reset functions.
    SpecialFunc(&'a SpecialFuncUniqueName<'b>),
    /// A unique name corresponding to memory bridge interactions.
    Memory(&'a MemoryUniqueName<'b>),
}

macro_rules! fmt {
    (
        Wasip1ABI; $($arg:tt)*
    ) => {
        paste::paste! {
            {
                format!(
                    "__wasip1_vfs_{}{}",
                    { $crate::unique_name::UniqueName::WASIP1_ABI },
                    format!($($arg)*)
                )
            }
        }
    };

    (
        $_ty:ty; $($arg:tt)*
    ) => {
        paste::paste! {
            {
                format!(
                    "__wasip1_vfs_{}{}",
                    { $crate::unique_name::UniqueName:: [<$_ty:snake:upper>] },
                    format!($($arg)*)
                )
            }
        }
    };

    (
        $($arg:tt)*
    ) => {
        { format!("__wasip1_vfs_{}", format!($($arg)*)) }
    };
}
pub(crate) use fmt;
use strum::EnumCount;

#[cfg(test)]
mod tests {
    #[test]
    fn test_unique_name_to_str() {
        let r = "abc";
        let fmt = super::fmt!("{r}def");
        assert_eq!(fmt, format!("{}abcdef", super::UniqueName::PREFIX));
    }

    #[test]
    fn test_unique_name_start_alternative() {
        let fmt = super::fmt!(StartAlternative; "suffix");
        assert_eq!(
            fmt,
            format!("{}start_alt_suffix", super::UniqueName::PREFIX)
        );
    }

    #[test]
    fn test_unique_name_threads_import_anchor_is_prefixed() {
        let t = crate::generator::threads::ThreadsSpawnName::ImportAnchor("thread-spawn");
        let s = super::UniqueName::ThreadsSpawn(&t).to_string();
        assert_eq!(s, "__wasip1_vfs_thread-spawn_import_anchor");
    }
}

impl UniqueName<'_, '_> {
    /// The root module namespace for core VFS operations.
    pub const CORE_MODULE_ROOT: &'static str = "wasip1-vfs:host/virtual-file-system-wasip1-core";
    /// The root module namespace for thread imports.
    pub const THREADS_MODULE_ROOT: &'static str =
        "wasip1-vfs:host/virtual-file-system-wasip1-threads-import";
    /// The root module namespace for thread exports.
    pub const THREADS_EXPORT_MODULE_ROOT: &'static str =
        "wasip1-vfs:host/virtual-file-system-wasip1-threads-export#wasi-thread-start";
    /// The module namespace for non-recursive execution of snapshot preview 1.
    pub const CORE_NON_RECURSIVE_MODULE_ROOT: &'static str = "non_recursive_wasi_snapshot_preview1";
    /// The namespace identifier for the virtual file system.
    pub const NAMESPACE: &'static str = "wasip1-vfs";
    /// The crate name for the Wasi Virt Layer library itself.
    pub const CRATE_NAME: &'static str = "wasi_virt_layer";
    /// The typical WASI ABI module string.
    pub const WASIP1_ABI_MODULE: &'static str = "wasi_snapshot_preview1";
    /// An alternative module string for WASI preview 1.
    pub const WASIP1_ABI_MODULE_ALT: &'static str = "wasip1";
    /// The common WASI thread module string.
    pub const WASIP1_THREADS_ABI_MODULE: &'static str = "wasi";
    /// An alternative module string for WASI threads.
    pub const WASIP1_THREADS_ABI_MODULE_ALT: &'static str = "wasip1-threads";

    /// The prefix used for globally distinct Wasm elements generated by this tool.
    pub const PREFIX: &'static str = "__wasip1_vfs_";

    /// Constant representing the start alternative name prefix.
    pub const START_ALTERNATIVE: &'static str = "start_alt_";
    /// Constant representing shared global functions prefix.
    pub const SHARED_GLOBAL_FNS: &'static str = "memory_grow_";
    /// Constant representing the special func prefix identifier.
    /// todo!(); to identified unique names
    pub const SPECIAL_FUNC: &'static str = "";
    /// Constant representing the WASIP1 ABI prefix identifier.
    /// todo!(); to identified unique names
    pub const WASIP1_ABI: &'static str = "";
    /// Constant representing the threads spawn prefix identifier.
    /// todo!(); to identified unique names
    pub const THREADS_SPAWN: &'static str = "";
    /// Constant representing the memory operation prefix identifier.
    /// todo!(); to identified unique names
    pub const MEMORY: &'static str = "";

    fn to_str(&self) -> String {
        match self {
            UniqueName::StartAlternative(alt) => {
                let alt_name = alt.as_ref();
                match alt {
                    StartAlternativeName::WasmName(name) | StartAlternativeName::VFS(name) => {
                        fmt!(StartAlternative; "{alt_name}_{name}")
                    }
                    _ => fmt!(StartAlternative; "{alt_name}"),
                }
            }
            UniqueName::SharedGlobalFns(func) => {
                let func_name = func.as_ref();
                match func {
                    SharedGlobalFnsName::Locker(n) => {
                        fmt!(SharedGlobalFns; "{func_name}_{n}")
                    }
                    _ => fmt!(SharedGlobalFns; "{func_name}"),
                }
            }
            UniqueName::Wasip1ABI(t) => {
                let name = t.as_ref();
                match t {
                    Wasip1ABIName::SelfDefault { import } => fmt!(Wasip1ABI; "{name}_{import}"),
                    Wasip1ABIName::TargetTemporal { wasm, import } => {
                        fmt!(Wasip1ABI; "{wasm}_{import}")
                    }
                }
            }
            UniqueName::ThreadsSpawn(t) => {
                let name = t.as_ref();
                match t {
                    ThreadsSpawnName::ImportAnchor(wasm) => {
                        fmt!(ThreadsSpawn; "{wasm}_{name}")
                    }
                    ThreadsSpawnName::WasiThreadStart(wasm)
                    | ThreadsSpawnName::WasiThreadStartAnchor(wasm) => {
                        fmt!(ThreadsSpawn; "{wasm}_{name}")
                    }
                    ThreadsSpawnName::WasiThreadStartDestination(wasm)
                    | ThreadsSpawnName::WasiThreadSpawn(wasm) => {
                        fmt!(ThreadsSpawn; "{name}_{wasm}")
                    }
                    _ => {
                        fmt!(ThreadsSpawn; "{name}")
                    }
                }
            }
            UniqueName::SpecialFunc(t) => {
                let name = t.as_ref();
                match t {
                    SpecialFuncUniqueName::Resetter(wasm) => {
                        fmt!(SpecialFunc; "{wasm}_{name}")
                    }
                    SpecialFuncUniqueName::Start(wasm) => {
                        fmt!(SpecialFunc; "{wasm}__{name}")
                    }
                    SpecialFuncUniqueName::MainVoid(wasm) => {
                        fmt!(SpecialFunc; "{wasm}___{name}")
                    }
                    SpecialFuncUniqueName::Reset(wasm) => {
                        fmt!(SpecialFunc; "{wasm}_{name}")
                    }
                    _ => {
                        fmt!(SpecialFunc; "{name}")
                    }
                }
            }
            UniqueName::Memory(t) => {
                let name = t.as_ref();
                match t {
                    MemoryUniqueName::MemoryCopyFrom(wasm)
                    | MemoryUniqueName::MemoryCopyTo(wasm)
                    | MemoryUniqueName::MemoryTrap(wasm)
                    | MemoryUniqueName::MemoryTrapAnchor(wasm)
                    | MemoryUniqueName::MemoryDirector(wasm)
                    | MemoryUniqueName::MemoryDirectorAnchor(wasm)
                    | MemoryUniqueName::Memory(wasm) => {
                        fmt!(Memory; "{wasm}_{name}")
                    }
                }
            }
        }
    }
}

/// A marker trait for structured references that can be converted to strings for unique WASM names.
pub trait UniqueNameMarker: ToString + Copy {}

impl UniqueNameMarker for &'_ UniqueName<'_, '_> {}

impl ToString for &'_ UniqueName<'_, '_> {
    fn to_string(&self) -> String {
        self.to_str()
    }
}

impl ToString for UniqueName<'_, '_> {
    fn to_string(&self) -> String {
        self.to_str()
    }
}

impl<'a> From<&'a StartAlternativeName> for UniqueName<'_, 'a> {
    fn from(value: &'a StartAlternativeName) -> Self {
        UniqueName::StartAlternative(value)
    }
}

impl<'a> From<&'a SharedGlobalFnsName> for UniqueName<'_, 'a> {
    fn from(value: &'a SharedGlobalFnsName) -> Self {
        UniqueName::SharedGlobalFns(value)
    }
}

impl<'a> From<&'a Wasip1ABIName<'_>> for UniqueName<'_, 'a> {
    fn from(value: &'a Wasip1ABIName<'_>) -> Self {
        UniqueName::Wasip1ABI(value)
    }
}

impl<'a> From<&'a ThreadsSpawnName<'_>> for UniqueName<'_, 'a> {
    fn from(value: &'a ThreadsSpawnName<'_>) -> Self {
        UniqueName::ThreadsSpawn(value)
    }
}

impl<'a> From<&'a SpecialFuncUniqueName<'_>> for UniqueName<'_, 'a> {
    fn from(value: &'a SpecialFuncUniqueName<'_>) -> Self {
        UniqueName::SpecialFunc(value)
    }
}

impl<'a> From<&'a MemoryUniqueName<'_>> for UniqueName<'_, 'a> {
    fn from(value: &'a MemoryUniqueName<'_>) -> Self {
        UniqueName::Memory(value)
    }
}

/// To verify whether an identical entry exists
/// in the destination for generating UniqueName, prepare an iterator.
#[allow(dead_code)]
trait UniqueNameIterator<'a>
where
    Self: Sized,
{
    type REQUIRED;

    fn iter_unique_names(require: &'a Self::REQUIRED) -> Vec<Self>;
}

impl<'a> UniqueNameIterator<'a> for WasmName {
    type REQUIRED = WasmName;

    fn iter_unique_names(require: &'a Self::REQUIRED) -> Vec<Self> {
        let v = vec![require.clone()];
        assert_eq!(v.len(), 1);
        v
    }
}

impl<'a> UniqueNameIterator<'a> for StartAlternativeName {
    type REQUIRED = WasmName;

    fn iter_unique_names(require: &'a Self::REQUIRED) -> Vec<Self> {
        let v = vec![
            StartAlternativeName::WasmName(require.clone()),
            StartAlternativeName::VFS(require.clone()),
            StartAlternativeName::AfterMemoryReset,
        ];
        assert_eq!(v.len(), StartAlternativeName::COUNT);
        v
    }
}

impl<'a> UniqueNameIterator<'a> for SharedGlobalFnsName {
    type REQUIRED = usize;

    fn iter_unique_names(require: &'a Self::REQUIRED) -> Vec<Self> {
        let v = vec![
            SharedGlobalFnsName::GlobalAltSet,
            SharedGlobalFnsName::GlobalAltGet,
            SharedGlobalFnsName::GlobalAltGetNoWait,
            SharedGlobalFnsName::GlobalAltInitOnce,
            SharedGlobalFnsName::GlobalAltPos,
            SharedGlobalFnsName::Locker(*require),
            SharedGlobalFnsName::LockerBase,
            SharedGlobalFnsName::MemoryGrowAlt,
        ];
        assert_eq!(v.len(), SharedGlobalFnsName::COUNT);
        v
    }
}

impl<'a> UniqueNameIterator<'a> for Wasip1ABIName<'a> {
    type REQUIRED = (WasmName, &'a str);

    fn iter_unique_names(require: &'a Self::REQUIRED) -> Vec<Self> {
        let (wasm, import) = require;
        let v = vec![
            Wasip1ABIName::SelfDefault { import },
            Wasip1ABIName::TargetTemporal { import, wasm },
        ];
        assert_eq!(v.len(), Wasip1ABIName::COUNT);
        v
    }
}

impl<'a> UniqueNameIterator<'a> for ThreadsSpawnName<'a> {
    type REQUIRED = (WasmName, &'a str);

    fn iter_unique_names(require: &'a Self::REQUIRED) -> Vec<Self> {
        let (wasm, import) = require;
        let v = vec![
            ThreadsSpawnName::ImportAnchor(import),
            ThreadsSpawnName::IsRootSpawn,
            ThreadsSpawnName::WasiThreadSpawnSelf,
            ThreadsSpawnName::SelfWasiThreadStart,
            ThreadsSpawnName::SelfWasiThreadStartAnchor,
            ThreadsSpawnName::RealThreadSpawnFn,
            ThreadsSpawnName::WasiThreadStartEntry,
            ThreadsSpawnName::WasiThreadSpawn(wasm),
            ThreadsSpawnName::WasiThreadStart(wasm),
            ThreadsSpawnName::WasiThreadStartAnchor(wasm),
            ThreadsSpawnName::WasiThreadStartDestination(wasm),
            ThreadsSpawnName::ThreadInitializer,
            ThreadsSpawnName::OldStart,
        ];
        assert_eq!(v.len(), ThreadsSpawnName::COUNT);
        v
    }
}

impl<'a> UniqueNameIterator<'a> for SpecialFuncUniqueName<'a> {
    type REQUIRED = WasmName;

    fn iter_unique_names(require: &'a Self::REQUIRED) -> Vec<Self> {
        let v = vec![
            SpecialFuncUniqueName::Resetter(require),
            SpecialFuncUniqueName::ResetOnThread,
            SpecialFuncUniqueName::ResetOnThreadOnce,
            SpecialFuncUniqueName::StartInitOld,
            SpecialFuncUniqueName::Start(require),
            SpecialFuncUniqueName::MainVoid(require),
            SpecialFuncUniqueName::Reset(require),
        ];
        assert_eq!(v.len(), SpecialFuncUniqueName::COUNT);
        v
    }
}

impl<'a> UniqueNameIterator<'a> for MemoryUniqueName<'a> {
    type REQUIRED = WasmName;

    fn iter_unique_names(require: &'a Self::REQUIRED) -> Vec<Self> {
        let v = vec![
            MemoryUniqueName::MemoryCopyFrom(require),
            MemoryUniqueName::MemoryCopyTo(require),
            MemoryUniqueName::MemoryTrap(require),
            MemoryUniqueName::MemoryTrapAnchor(require),
            MemoryUniqueName::MemoryDirector(require),
            MemoryUniqueName::MemoryDirectorAnchor(require),
            MemoryUniqueName::Memory(require),
        ];
        assert_eq!(v.len(), MemoryUniqueName::COUNT);
        v
    }
}

#[cfg(test)]
mod unique_name_iterator_tests {
    use std::collections::HashSet;

    use crate::util::WasmNameHolder;

    use super::*;

    #[test]
    fn test_unique_name_iterator_start_alternative() {
        let holder = WasmNameHolder::new(vec!["#original_import".into()].into_boxed_slice());
        let require_import = holder.iter().next().unwrap();
        let require_name = "#original_name";
        let require_num = 5;
        let requires = (require_import.clone(), require_name);
        let t2 = StartAlternativeName::iter_unique_names(&require_import);
        let t3 = SharedGlobalFnsName::iter_unique_names(&require_num);
        let t4 = Wasip1ABIName::iter_unique_names(&requires);
        let t5 = ThreadsSpawnName::iter_unique_names(&requires);
        let t6 = SpecialFuncUniqueName::iter_unique_names(&require_import);
        let t7 = MemoryUniqueName::iter_unique_names(&require_import);
        let t2 = t2.iter().map(Into::into);
        let t3 = t3.iter().map(Into::into);
        let t4 = t4.iter().map(Into::into);
        let t5 = t5.iter().map(Into::into);
        let t6 = t6.iter().map(Into::into);
        let t7 = t7.iter().map(Into::into);
        let t = t2
            .chain(t3)
            .chain(t4)
            .chain(t5)
            .chain(t6)
            .chain(t7)
            .collect::<Vec<UniqueName>>();

        // Check whether there is the same output destination
        let mut seen = std::collections::HashMap::new();
        let mut duplicates = HashSet::new();
        for t in &t {
            let name = t.to_string();
            if seen.insert(name.clone(), t).is_some() {
                duplicates.insert(t);
                duplicates.insert(seen.get(&name).unwrap());
            }
        }
        assert!(
            duplicates.is_empty(),
            "Found duplicate unique names: {duplicates:?}",
        );
    }
}