Skip to main content

wasi_virt_layer_cli/
unique_name.rs

1//! Provides mechanisms to generate unique non-colliding crate identifiers and exports for WASM modules.
2
3use crate::{
4    generator::{
5        abi_connect::Wasip1ABIName, memory::MemoryUniqueName, shared_global::SharedGlobalFnsName,
6        special_func::SpecialFuncUniqueName,
7        threads::ThreadsSpawnName,
8    },
9    util::WasmName,
10};
11
12/// Represents a unique, non-colliding name element within the generated WASM structure.
13#[derive(Debug, Eq, PartialEq, Hash)]
14pub enum UniqueName<'a, 'b> {
15    /// A unique name corresponding to shared global functions.
16    SharedGlobalFns(&'a SharedGlobalFnsName),
17    /// A unique name corresponding to shared global functions for a specific target.
18    SharedGlobalFnsForTarget(&'a SharedGlobalFnsName, &'a str),
19    /// A unique name corresponding to WASI P1 ABI function replacements.
20    Wasip1ABI(&'a Wasip1ABIName<'b>),
21    /// A unique name corresponding to thread spawning logic.
22    ThreadsSpawn(&'a ThreadsSpawnName<'b>),
23    /// A unique name corresponding to special initialization or reset functions.
24    SpecialFunc(&'a SpecialFuncUniqueName<'b>),
25    /// A unique name corresponding to memory bridge interactions.
26    Memory(&'a MemoryUniqueName<'b>),
27}
28
29macro_rules! fmt {
30    (
31        Wasip1ABI; $($arg:tt)*
32    ) => {
33        paste::paste! {
34            {
35                format!(
36                    "__wasip1_vfs_{}{}",
37                    { $crate::unique_name::UniqueName::WASIP1_ABI },
38                    format!($($arg)*)
39                )
40            }
41        }
42    };
43
44    (
45        $_ty:ty; $($arg:tt)*
46    ) => {
47        paste::paste! {
48            {
49                format!(
50                    "__wasip1_vfs_{}{}",
51                    { $crate::unique_name::UniqueName:: [<$_ty:snake:upper>] },
52                    format!($($arg)*)
53                )
54            }
55        }
56    };
57
58    (
59        $($arg:tt)*
60    ) => {
61        { format!("__wasip1_vfs_{}", format!($($arg)*)) }
62    };
63}
64pub(crate) use fmt;
65use strum::EnumCount;
66
67#[cfg(test)]
68mod tests {
69    #[test]
70    fn test_unique_name_to_str() {
71        let r = "abc";
72        let fmt = super::fmt!("{r}def");
73        assert_eq!(fmt, format!("{}abcdef", super::UniqueName::PREFIX));
74    }
75
76    #[test]
77    fn test_unique_name_start_alternative() {
78        let fmt = super::fmt!(StartAlternative; "suffix");
79        assert_eq!(
80            fmt,
81            format!("{}start_alt_suffix", super::UniqueName::PREFIX)
82        );
83    }
84
85    #[test]
86    fn test_unique_name_threads_import_anchor_is_prefixed() {
87        let t = crate::generator::threads::ThreadsSpawnName::ImportAnchor("thread-spawn");
88        let s = super::UniqueName::ThreadsSpawn(&t).to_string();
89        assert_eq!(s, "__wasip1_vfs_thread-spawn_import_anchor");
90    }
91}
92
93impl UniqueName<'_, '_> {
94    /// The root module namespace for core VFS operations.
95    pub const CORE_MODULE_ROOT: &'static str = "wasip1-vfs:host/virtual-file-system-wasip1-core";
96    /// The root module namespace for thread imports.
97    pub const THREADS_MODULE_ROOT: &'static str =
98        "wasip1-vfs:host/virtual-file-system-wasip1-threads-import";
99    /// The root module namespace for thread exports.
100    pub const THREADS_EXPORT_MODULE_ROOT: &'static str =
101        "wasip1-vfs:host/virtual-file-system-wasip1-threads-export#wasi-thread-start";
102    /// The module namespace for non-recursive execution of snapshot preview 1.
103    pub const CORE_NON_RECURSIVE_MODULE_ROOT: &'static str = "non_recursive_wasi_snapshot_preview1";
104    /// The namespace identifier for the virtual file system.
105    pub const NAMESPACE: &'static str = "wasip1-vfs";
106    /// The crate name for the Wasi Virt Layer library itself.
107    pub const CRATE_NAME: &'static str = "wasi_virt_layer";
108    /// The typical WASI ABI module string.
109    pub const WASIP1_ABI_MODULE: &'static str = "wasi_snapshot_preview1";
110    /// An alternative module string for WASI preview 1.
111    pub const WASIP1_ABI_MODULE_ALT: &'static str = "wasip1";
112    /// The common WASI thread module string.
113    pub const WASIP1_THREADS_ABI_MODULE: &'static str = "wasi";
114    /// An alternative module string for WASI threads.
115    pub const WASIP1_THREADS_ABI_MODULE_ALT: &'static str = "wasip1-threads";
116
117    /// The prefix used for globally distinct Wasm elements generated by this tool.
118    pub const PREFIX: &'static str = "__wasip1_vfs_";
119
120    /// Constant representing the start alternative name prefix.
121    pub const START_ALTERNATIVE: &'static str = "start_alt_";
122    /// Constant representing shared global functions prefix.
123    pub const SHARED_GLOBAL_FNS: &'static str = "memory_grow_";
124    /// Constant representing the special func prefix identifier.
125    /// todo!(); to identified unique names
126    pub const SPECIAL_FUNC: &'static str = "";
127    /// Constant representing the WASIP1 ABI prefix identifier.
128    /// todo!(); to identified unique names
129    pub const WASIP1_ABI: &'static str = "";
130    /// Constant representing the threads spawn prefix identifier.
131    /// todo!(); to identified unique names
132    pub const THREADS_SPAWN: &'static str = "";
133    /// Constant representing the memory operation prefix identifier.
134    /// todo!(); to identified unique names
135    pub const MEMORY: &'static str = "";
136
137    fn to_str(&self) -> String {
138        match self {
139            UniqueName::SharedGlobalFns(func) => {
140                let func_name = func.as_ref();
141                match func {
142                    SharedGlobalFnsName::Locker(n) => {
143                        fmt!(SharedGlobalFns; "{func_name}_{n}")
144                    }
145                    _ => fmt!(SharedGlobalFns; "{func_name}"),
146                }
147            }
148            UniqueName::SharedGlobalFnsForTarget(func, target) => {
149                let func_name = func.as_ref();
150                let normalized_target = target.replace('-', "_");
151                let op = UniqueName::SHARED_GLOBAL_FNS;
152                match func {
153                    SharedGlobalFnsName::Locker(n) => {
154                        fmt!("{normalized_target}_{op}{func_name}_{n}")
155                    }
156                    _ => fmt!("{normalized_target}_{op}{func_name}"),
157                }
158            }
159            UniqueName::Wasip1ABI(t) => {
160                let name = t.as_ref();
161                match t {
162                    Wasip1ABIName::SelfDefault { import } => fmt!(Wasip1ABI; "{name}_{import}"),
163                    Wasip1ABIName::TargetTemporal { wasm, import } => {
164                        fmt!(Wasip1ABI; "{wasm}_{import}")
165                    }
166                }
167            }
168            UniqueName::ThreadsSpawn(t) => {
169                let name = t.as_ref();
170                match t {
171                    ThreadsSpawnName::ImportAnchor(wasm) => {
172                        fmt!(ThreadsSpawn; "{wasm}_{name}")
173                    }
174                    ThreadsSpawnName::WasiThreadStart(wasm)
175                    | ThreadsSpawnName::WasiThreadStartAnchor(wasm) => {
176                        fmt!(ThreadsSpawn; "{wasm}_{name}")
177                    }
178                    ThreadsSpawnName::WasiThreadStartDestination(wasm)
179                    | ThreadsSpawnName::WasiThreadSpawn(wasm) => {
180                        fmt!(ThreadsSpawn; "{name}_{wasm}")
181                    }
182                    _ => {
183                        fmt!(ThreadsSpawn; "{name}")
184                    }
185                }
186            }
187            UniqueName::SpecialFunc(t) => {
188                let name = t.as_ref();
189                match t {
190                    SpecialFuncUniqueName::Resetter(wasm) => {
191                        fmt!(SpecialFunc; "{wasm}_{name}")
192                    }
193                    SpecialFuncUniqueName::Start(wasm) => {
194                        fmt!(SpecialFunc; "{wasm}__{name}")
195                    }
196                    SpecialFuncUniqueName::MainVoid(wasm) => {
197                        fmt!(SpecialFunc; "{wasm}___{name}")
198                    }
199                    SpecialFuncUniqueName::Reset(wasm) => {
200                        fmt!(SpecialFunc; "{wasm}_{name}")
201                    }
202                    _ => {
203                        fmt!(SpecialFunc; "{name}")
204                    }
205                }
206            }
207            UniqueName::Memory(t) => {
208                let name = t.as_ref();
209                match t {
210                    MemoryUniqueName::MemoryCopyFrom(wasm)
211                    | MemoryUniqueName::MemoryCopyTo(wasm)
212                    | MemoryUniqueName::MemoryTrap(wasm)
213                    | MemoryUniqueName::MemoryTrapAnchor(wasm)
214                    | MemoryUniqueName::MemoryDirector(wasm)
215                    | MemoryUniqueName::MemoryDirectorAnchor(wasm)
216                    | MemoryUniqueName::Memory(wasm) => {
217                        fmt!(Memory; "{wasm}_{name}")
218                    }
219                }
220            }
221        }
222    }
223}
224
225/// A marker trait for structured references that can be converted to strings for unique WASM names.
226pub trait UniqueNameMarker: ToString + Copy {}
227
228impl UniqueNameMarker for &'_ UniqueName<'_, '_> {}
229
230impl ToString for &'_ UniqueName<'_, '_> {
231    fn to_string(&self) -> String {
232        self.to_str()
233    }
234}
235
236impl ToString for UniqueName<'_, '_> {
237    fn to_string(&self) -> String {
238        self.to_str()
239    }
240}
241
242impl<'a> From<&'a SharedGlobalFnsName> for UniqueName<'_, 'a> {
243    fn from(value: &'a SharedGlobalFnsName) -> Self {
244        UniqueName::SharedGlobalFns(value)
245    }
246}
247
248impl<'a> From<&'a Wasip1ABIName<'_>> for UniqueName<'_, 'a> {
249    fn from(value: &'a Wasip1ABIName<'_>) -> Self {
250        UniqueName::Wasip1ABI(value)
251    }
252}
253
254impl<'a> From<&'a ThreadsSpawnName<'_>> for UniqueName<'_, 'a> {
255    fn from(value: &'a ThreadsSpawnName<'_>) -> Self {
256        UniqueName::ThreadsSpawn(value)
257    }
258}
259
260impl<'a> From<&'a SpecialFuncUniqueName<'_>> for UniqueName<'_, 'a> {
261    fn from(value: &'a SpecialFuncUniqueName<'_>) -> Self {
262        UniqueName::SpecialFunc(value)
263    }
264}
265
266impl<'a> From<&'a MemoryUniqueName<'_>> for UniqueName<'_, 'a> {
267    fn from(value: &'a MemoryUniqueName<'_>) -> Self {
268        UniqueName::Memory(value)
269    }
270}
271
272/// To verify whether an identical entry exists
273/// in the destination for generating UniqueName, prepare an iterator.
274#[allow(dead_code)]
275trait UniqueNameIterator<'a>
276where
277    Self: Sized,
278{
279    type REQUIRED;
280
281    fn iter_unique_names(require: &'a Self::REQUIRED) -> Vec<Self>;
282}
283
284impl<'a> UniqueNameIterator<'a> for WasmName {
285    type REQUIRED = WasmName;
286
287    fn iter_unique_names(require: &'a Self::REQUIRED) -> Vec<Self> {
288        let v = vec![require.clone()];
289        assert_eq!(v.len(), 1);
290        v
291    }
292}
293
294impl<'a> UniqueNameIterator<'a> for SharedGlobalFnsName {
295    type REQUIRED = usize;
296
297    fn iter_unique_names(require: &'a Self::REQUIRED) -> Vec<Self> {
298        let v = vec![
299            SharedGlobalFnsName::GlobalAltSet,
300            SharedGlobalFnsName::GlobalAltGet,
301            SharedGlobalFnsName::GlobalAltGetNoWait,
302            SharedGlobalFnsName::GlobalAltInitOnce,
303            SharedGlobalFnsName::GlobalAltPos,
304            SharedGlobalFnsName::Locker(*require),
305            SharedGlobalFnsName::LockerBase,
306            SharedGlobalFnsName::MemoryGrowAlt,
307            SharedGlobalFnsName::GlobalAltSetWithLock,
308        ];
309        assert_eq!(v.len(), SharedGlobalFnsName::COUNT);
310        v
311    }
312}
313
314impl<'a> UniqueNameIterator<'a> for Wasip1ABIName<'a> {
315    type REQUIRED = (WasmName, &'a str);
316
317    fn iter_unique_names(require: &'a Self::REQUIRED) -> Vec<Self> {
318        let (wasm, import) = require;
319        let v = vec![
320            Wasip1ABIName::SelfDefault { import },
321            Wasip1ABIName::TargetTemporal { import, wasm },
322        ];
323        assert_eq!(v.len(), Wasip1ABIName::COUNT);
324        v
325    }
326}
327
328impl<'a> UniqueNameIterator<'a> for ThreadsSpawnName<'a> {
329    type REQUIRED = (WasmName, &'a str);
330
331    fn iter_unique_names(require: &'a Self::REQUIRED) -> Vec<Self> {
332        let (wasm, import) = require;
333        let v = vec![
334            ThreadsSpawnName::ImportAnchor(import),
335            ThreadsSpawnName::IsRootSpawn,
336            ThreadsSpawnName::WasiThreadSpawnSelf,
337            ThreadsSpawnName::SelfWasiThreadStart,
338            ThreadsSpawnName::SelfWasiThreadStartAnchor,
339            ThreadsSpawnName::RealThreadSpawnFn,
340            ThreadsSpawnName::WasiThreadStartEntry,
341            ThreadsSpawnName::WasiThreadSpawn(wasm),
342            ThreadsSpawnName::WasiThreadStart(wasm),
343            ThreadsSpawnName::WasiThreadStartAnchor(wasm),
344            ThreadsSpawnName::WasiThreadStartDestination(wasm),
345            ThreadsSpawnName::ThreadInitializer,
346            ThreadsSpawnName::OldStart,
347        ];
348        assert_eq!(v.len(), ThreadsSpawnName::COUNT);
349        v
350    }
351}
352
353impl<'a> UniqueNameIterator<'a> for SpecialFuncUniqueName<'a> {
354    type REQUIRED = WasmName;
355
356    fn iter_unique_names(require: &'a Self::REQUIRED) -> Vec<Self> {
357        let v = vec![
358            SpecialFuncUniqueName::Resetter(require),
359            SpecialFuncUniqueName::ResetOnThread,
360            SpecialFuncUniqueName::ResetOnThreadOnce,
361            SpecialFuncUniqueName::StartInitOld,
362            SpecialFuncUniqueName::Start(require),
363            SpecialFuncUniqueName::MainVoid(require),
364            SpecialFuncUniqueName::Reset(require),
365        ];
366        assert_eq!(v.len(), SpecialFuncUniqueName::COUNT);
367        v
368    }
369}
370
371impl<'a> UniqueNameIterator<'a> for MemoryUniqueName<'a> {
372    type REQUIRED = WasmName;
373
374    fn iter_unique_names(require: &'a Self::REQUIRED) -> Vec<Self> {
375        let v = vec![
376            MemoryUniqueName::MemoryCopyFrom(require),
377            MemoryUniqueName::MemoryCopyTo(require),
378            MemoryUniqueName::MemoryTrap(require),
379            MemoryUniqueName::MemoryTrapAnchor(require),
380            MemoryUniqueName::MemoryDirector(require),
381            MemoryUniqueName::MemoryDirectorAnchor(require),
382            MemoryUniqueName::Memory(require),
383        ];
384        assert_eq!(v.len(), MemoryUniqueName::COUNT);
385        v
386    }
387}
388
389#[cfg(test)]
390mod unique_name_iterator_tests {
391    use std::collections::HashSet;
392
393    use crate::util::WasmNameHolder;
394
395    use super::*;
396
397    #[test]
398    fn test_unique_name_iterator_start_alternative() {
399        let holder = WasmNameHolder::new(vec!["#original_import".into()].into_boxed_slice());
400        let require_import = holder.iter().next().unwrap();
401        let require_name = "#original_name";
402        let require_num = 5;
403        let requires = (require_import.clone(), require_name);
404        let t3 = SharedGlobalFnsName::iter_unique_names(&require_num);
405        let t4 = Wasip1ABIName::iter_unique_names(&requires);
406        let t5 = ThreadsSpawnName::iter_unique_names(&requires);
407        let t6 = SpecialFuncUniqueName::iter_unique_names(&require_import);
408        let t7 = MemoryUniqueName::iter_unique_names(&require_import);
409        let t3 = t3.iter().map(Into::into);
410        let t4 = t4.iter().map(Into::into);
411        let t5 = t5.iter().map(Into::into);
412        let t6 = t6.iter().map(Into::into);
413        let t7 = t7.iter().map(Into::into);
414        let t = t3
415            .chain(t4)
416            .chain(t5)
417            .chain(t6)
418            .chain(t7)
419            .collect::<Vec<UniqueName>>();
420
421        // Check whether there is the same output destination
422        let mut seen = std::collections::HashMap::new();
423        let mut duplicates = HashSet::new();
424        for t in &t {
425            let name = t.to_string();
426            if seen.insert(name.clone(), t).is_some() {
427                duplicates.insert(t);
428                duplicates.insert(seen.get(&name).unwrap());
429            }
430        }
431        assert!(
432            duplicates.is_empty(),
433            "Found duplicate unique names: {duplicates:?}",
434        );
435    }
436}