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