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, start_section::StartAlternativeName,
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 an alternative start section.
16    StartAlternative(&'a StartAlternativeName),
17    /// A unique name corresponding to shared global functions.
18    SharedGlobalFns(&'a SharedGlobalFnsName),
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::StartAlternative(alt) => {
140                let alt_name = alt.as_ref();
141                match alt {
142                    StartAlternativeName::WasmName(name) | StartAlternativeName::VFS(name) => {
143                        fmt!(StartAlternative; "{alt_name}_{name}")
144                    }
145                    _ => fmt!(StartAlternative; "{alt_name}"),
146                }
147            }
148            UniqueName::SharedGlobalFns(func) => {
149                let func_name = func.as_ref();
150                match func {
151                    SharedGlobalFnsName::Locker(n) => {
152                        fmt!(SharedGlobalFns; "{func_name}_{n}")
153                    }
154                    _ => fmt!(SharedGlobalFns; "{func_name}"),
155                }
156            }
157            UniqueName::Wasip1ABI(t) => {
158                let name = t.as_ref();
159                match t {
160                    Wasip1ABIName::SelfDefault { import } => fmt!(Wasip1ABI; "{name}_{import}"),
161                    Wasip1ABIName::TargetTemporal { wasm, import } => {
162                        fmt!(Wasip1ABI; "{wasm}_{import}")
163                    }
164                }
165            }
166            UniqueName::ThreadsSpawn(t) => {
167                let name = t.as_ref();
168                match t {
169                    ThreadsSpawnName::ImportAnchor(wasm) => {
170                        fmt!(ThreadsSpawn; "{wasm}_{name}")
171                    }
172                    ThreadsSpawnName::WasiThreadStart(wasm)
173                    | ThreadsSpawnName::WasiThreadStartAnchor(wasm) => {
174                        fmt!(ThreadsSpawn; "{wasm}_{name}")
175                    }
176                    ThreadsSpawnName::WasiThreadStartDestination(wasm)
177                    | ThreadsSpawnName::WasiThreadSpawn(wasm) => {
178                        fmt!(ThreadsSpawn; "{name}_{wasm}")
179                    }
180                    _ => {
181                        fmt!(ThreadsSpawn; "{name}")
182                    }
183                }
184            }
185            UniqueName::SpecialFunc(t) => {
186                let name = t.as_ref();
187                match t {
188                    SpecialFuncUniqueName::Resetter(wasm) => {
189                        fmt!(SpecialFunc; "{wasm}_{name}")
190                    }
191                    SpecialFuncUniqueName::Start(wasm) => {
192                        fmt!(SpecialFunc; "{wasm}__{name}")
193                    }
194                    SpecialFuncUniqueName::MainVoid(wasm) => {
195                        fmt!(SpecialFunc; "{wasm}___{name}")
196                    }
197                    SpecialFuncUniqueName::Reset(wasm) => {
198                        fmt!(SpecialFunc; "{wasm}_{name}")
199                    }
200                    _ => {
201                        fmt!(SpecialFunc; "{name}")
202                    }
203                }
204            }
205            UniqueName::Memory(t) => {
206                let name = t.as_ref();
207                match t {
208                    MemoryUniqueName::MemoryCopyFrom(wasm)
209                    | MemoryUniqueName::MemoryCopyTo(wasm)
210                    | MemoryUniqueName::MemoryTrap(wasm)
211                    | MemoryUniqueName::MemoryTrapAnchor(wasm)
212                    | MemoryUniqueName::MemoryDirector(wasm)
213                    | MemoryUniqueName::MemoryDirectorAnchor(wasm)
214                    | MemoryUniqueName::Memory(wasm) => {
215                        fmt!(Memory; "{wasm}_{name}")
216                    }
217                }
218            }
219        }
220    }
221}
222
223/// A marker trait for structured references that can be converted to strings for unique WASM names.
224pub trait UniqueNameMarker: ToString + Copy {}
225
226impl UniqueNameMarker for &'_ UniqueName<'_, '_> {}
227
228impl ToString for &'_ UniqueName<'_, '_> {
229    fn to_string(&self) -> String {
230        self.to_str()
231    }
232}
233
234impl ToString for UniqueName<'_, '_> {
235    fn to_string(&self) -> String {
236        self.to_str()
237    }
238}
239
240impl<'a> From<&'a StartAlternativeName> for UniqueName<'_, 'a> {
241    fn from(value: &'a StartAlternativeName) -> Self {
242        UniqueName::StartAlternative(value)
243    }
244}
245
246impl<'a> From<&'a SharedGlobalFnsName> for UniqueName<'_, 'a> {
247    fn from(value: &'a SharedGlobalFnsName) -> Self {
248        UniqueName::SharedGlobalFns(value)
249    }
250}
251
252impl<'a> From<&'a Wasip1ABIName<'_>> for UniqueName<'_, 'a> {
253    fn from(value: &'a Wasip1ABIName<'_>) -> Self {
254        UniqueName::Wasip1ABI(value)
255    }
256}
257
258impl<'a> From<&'a ThreadsSpawnName<'_>> for UniqueName<'_, 'a> {
259    fn from(value: &'a ThreadsSpawnName<'_>) -> Self {
260        UniqueName::ThreadsSpawn(value)
261    }
262}
263
264impl<'a> From<&'a SpecialFuncUniqueName<'_>> for UniqueName<'_, 'a> {
265    fn from(value: &'a SpecialFuncUniqueName<'_>) -> Self {
266        UniqueName::SpecialFunc(value)
267    }
268}
269
270impl<'a> From<&'a MemoryUniqueName<'_>> for UniqueName<'_, 'a> {
271    fn from(value: &'a MemoryUniqueName<'_>) -> Self {
272        UniqueName::Memory(value)
273    }
274}
275
276/// To verify whether an identical entry exists
277/// in the destination for generating UniqueName, prepare an iterator.
278#[allow(dead_code)]
279trait UniqueNameIterator<'a>
280where
281    Self: Sized,
282{
283    type REQUIRED;
284
285    fn iter_unique_names(require: &'a Self::REQUIRED) -> Vec<Self>;
286}
287
288impl<'a> UniqueNameIterator<'a> for WasmName {
289    type REQUIRED = WasmName;
290
291    fn iter_unique_names(require: &'a Self::REQUIRED) -> Vec<Self> {
292        let v = vec![require.clone()];
293        assert_eq!(v.len(), 1);
294        v
295    }
296}
297
298impl<'a> UniqueNameIterator<'a> for StartAlternativeName {
299    type REQUIRED = WasmName;
300
301    fn iter_unique_names(require: &'a Self::REQUIRED) -> Vec<Self> {
302        let v = vec![
303            StartAlternativeName::WasmName(require.clone()),
304            StartAlternativeName::VFS(require.clone()),
305            StartAlternativeName::AfterMemoryReset,
306        ];
307        assert_eq!(v.len(), StartAlternativeName::COUNT);
308        v
309    }
310}
311
312impl<'a> UniqueNameIterator<'a> for SharedGlobalFnsName {
313    type REQUIRED = usize;
314
315    fn iter_unique_names(require: &'a Self::REQUIRED) -> Vec<Self> {
316        let v = vec![
317            SharedGlobalFnsName::GlobalAltSet,
318            SharedGlobalFnsName::GlobalAltGet,
319            SharedGlobalFnsName::GlobalAltGetNoWait,
320            SharedGlobalFnsName::GlobalAltInitOnce,
321            SharedGlobalFnsName::GlobalAltPos,
322            SharedGlobalFnsName::Locker(*require),
323            SharedGlobalFnsName::LockerBase,
324            SharedGlobalFnsName::MemoryGrowAlt,
325        ];
326        assert_eq!(v.len(), SharedGlobalFnsName::COUNT);
327        v
328    }
329}
330
331impl<'a> UniqueNameIterator<'a> for Wasip1ABIName<'a> {
332    type REQUIRED = (WasmName, &'a str);
333
334    fn iter_unique_names(require: &'a Self::REQUIRED) -> Vec<Self> {
335        let (wasm, import) = require;
336        let v = vec![
337            Wasip1ABIName::SelfDefault { import },
338            Wasip1ABIName::TargetTemporal { import, wasm },
339        ];
340        assert_eq!(v.len(), Wasip1ABIName::COUNT);
341        v
342    }
343}
344
345impl<'a> UniqueNameIterator<'a> for ThreadsSpawnName<'a> {
346    type REQUIRED = (WasmName, &'a str);
347
348    fn iter_unique_names(require: &'a Self::REQUIRED) -> Vec<Self> {
349        let (wasm, import) = require;
350        let v = vec![
351            ThreadsSpawnName::ImportAnchor(import),
352            ThreadsSpawnName::IsRootSpawn,
353            ThreadsSpawnName::WasiThreadSpawnSelf,
354            ThreadsSpawnName::SelfWasiThreadStart,
355            ThreadsSpawnName::SelfWasiThreadStartAnchor,
356            ThreadsSpawnName::RealThreadSpawnFn,
357            ThreadsSpawnName::WasiThreadStartEntry,
358            ThreadsSpawnName::WasiThreadSpawn(wasm),
359            ThreadsSpawnName::WasiThreadStart(wasm),
360            ThreadsSpawnName::WasiThreadStartAnchor(wasm),
361            ThreadsSpawnName::WasiThreadStartDestination(wasm),
362            ThreadsSpawnName::ThreadInitializer,
363            ThreadsSpawnName::OldStart,
364        ];
365        assert_eq!(v.len(), ThreadsSpawnName::COUNT);
366        v
367    }
368}
369
370impl<'a> UniqueNameIterator<'a> for SpecialFuncUniqueName<'a> {
371    type REQUIRED = WasmName;
372
373    fn iter_unique_names(require: &'a Self::REQUIRED) -> Vec<Self> {
374        let v = vec![
375            SpecialFuncUniqueName::Resetter(require),
376            SpecialFuncUniqueName::ResetOnThread,
377            SpecialFuncUniqueName::ResetOnThreadOnce,
378            SpecialFuncUniqueName::StartInitOld,
379            SpecialFuncUniqueName::Start(require),
380            SpecialFuncUniqueName::MainVoid(require),
381            SpecialFuncUniqueName::Reset(require),
382        ];
383        assert_eq!(v.len(), SpecialFuncUniqueName::COUNT);
384        v
385    }
386}
387
388impl<'a> UniqueNameIterator<'a> for MemoryUniqueName<'a> {
389    type REQUIRED = WasmName;
390
391    fn iter_unique_names(require: &'a Self::REQUIRED) -> Vec<Self> {
392        let v = vec![
393            MemoryUniqueName::MemoryCopyFrom(require),
394            MemoryUniqueName::MemoryCopyTo(require),
395            MemoryUniqueName::MemoryTrap(require),
396            MemoryUniqueName::MemoryTrapAnchor(require),
397            MemoryUniqueName::MemoryDirector(require),
398            MemoryUniqueName::MemoryDirectorAnchor(require),
399            MemoryUniqueName::Memory(require),
400        ];
401        assert_eq!(v.len(), MemoryUniqueName::COUNT);
402        v
403    }
404}
405
406#[cfg(test)]
407mod unique_name_iterator_tests {
408    use std::collections::HashSet;
409
410    use crate::util::WasmNameHolder;
411
412    use super::*;
413
414    #[test]
415    fn test_unique_name_iterator_start_alternative() {
416        let holder = WasmNameHolder::new(vec!["#original_import".into()].into_boxed_slice());
417        let require_import = holder.iter().next().unwrap();
418        let require_name = "#original_name";
419        let require_num = 5;
420        let requires = (require_import.clone(), require_name);
421        let t2 = StartAlternativeName::iter_unique_names(&require_import);
422        let t3 = SharedGlobalFnsName::iter_unique_names(&require_num);
423        let t4 = Wasip1ABIName::iter_unique_names(&requires);
424        let t5 = ThreadsSpawnName::iter_unique_names(&requires);
425        let t6 = SpecialFuncUniqueName::iter_unique_names(&require_import);
426        let t7 = MemoryUniqueName::iter_unique_names(&require_import);
427        let t2 = t2.iter().map(Into::into);
428        let t3 = t3.iter().map(Into::into);
429        let t4 = t4.iter().map(Into::into);
430        let t5 = t5.iter().map(Into::into);
431        let t6 = t6.iter().map(Into::into);
432        let t7 = t7.iter().map(Into::into);
433        let t = t2
434            .chain(t3)
435            .chain(t4)
436            .chain(t5)
437            .chain(t6)
438            .chain(t7)
439            .collect::<Vec<UniqueName>>();
440
441        // Check whether there is the same output destination
442        let mut seen = std::collections::HashMap::new();
443        let mut duplicates = HashSet::new();
444        for t in &t {
445            let name = t.to_string();
446            if seen.insert(name.clone(), t).is_some() {
447                duplicates.insert(t);
448                duplicates.insert(seen.get(&name).unwrap());
449            }
450        }
451        assert!(
452            duplicates.is_empty(),
453            "Found duplicate unique names: {duplicates:?}",
454        );
455    }
456}