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