Skip to main content

wasi_virt_layer_cli/
util.rs

1use std::{
2    borrow::Borrow,
3    collections::HashMap,
4    fmt::Debug,
5    path::{Path, PathBuf},
6    sync::atomic::AtomicUsize,
7};
8
9use compact_str::CompactString;
10
11#[allow(dead_code)]
12#[allow(dead_code)]
13#[allow(dead_code)]
14
15/// Extension trait for Camino paths to extract the main module file name.
16pub trait CaminoUtilModule {
17    /// Gets the base compact string name without extension and specific postfixes.
18    fn get_file_main_name(&self) -> Option<CompactString>;
19}
20
21impl CaminoUtilModule for camino::Utf8Path {
22    fn get_file_main_name(&self) -> Option<CompactString> {
23        let binding = self.file_name().unwrap().split(".").collect::<Vec<_>>();
24        let file_name_poss = binding.iter().rev();
25        let mut file_name = None;
26        for name in file_name_poss {
27            if *name == "opt"
28                || *name == "adjusted"
29                || *name == "wasm"
30                || *name == "core"
31                || *name == "component"
32            {
33                continue;
34            }
35            file_name = Some(name);
36            break;
37        }
38        let file_name = file_name.map(ToOwned::to_owned).or_else(|| {
39            self.file_name()
40                .unwrap()
41                .split(".")
42                .next()
43                .as_ref()
44                .cloned()
45        });
46
47        file_name.map(CompactString::from)
48    }
49}
50
51impl CaminoUtilModule for PathBuf {
52    fn get_file_main_name(&self) -> Option<CompactString> {
53        camino::Utf8Path::new(self.to_str().unwrap()).get_file_main_name()
54    }
55}
56
57impl CaminoUtilModule for Path {
58    fn get_file_main_name(&self) -> Option<CompactString> {
59        camino::Utf8Path::new(self.to_str().unwrap()).get_file_main_name()
60    }
61}
62
63/// Utility trait for converting generic or `anyhow` results into `eyre::Result`.
64pub trait ResultUtil<T> {
65    /// Converts the result into an `eyre::Result`.
66    fn to_eyre(self) -> eyre::Result<T>;
67}
68
69// https://github.com/eyre-rs/eyre/issues/31
70impl<T> ResultUtil<T> for anyhow::Result<T> {
71    fn to_eyre(self) -> eyre::Result<T> {
72        self.map_err(|e| {
73            eyre::eyre!(Box::<dyn std::error::Error + Send + Sync + 'static>::from(
74                e
75            ))
76        })
77    }
78}
79
80impl<T, I: Iterator> ResultUtil<T> for Result<T, itertools::ExactlyOneError<I>> {
81    fn to_eyre(self) -> eyre::Result<T> {
82        self.map_err(|e| eyre::eyre!(e.to_string()))
83    }
84}
85
86/// Provides unified Function ID resolution for different markers (like tuples of module/name).
87
88/// Provides the actual lookup operations for FID resolution.
89
90/// Marker for looking up FIDs by `FunctionId` values.
91pub struct FunctionIdMarker;
92/// Marker for looking up FIDs by string names.
93pub struct StrMarker;
94/// Marker for looking up FIDs using `UniqueName` constants.
95pub struct UniqueMarker;
96/// Marker for looking up FIDs by a module-name and item-name tuple.
97pub struct DoubleStrMarker;
98/// Marker for looking up FIDs using a string module-name and `UniqueName` item.
99pub struct StrAndUniqueNameMarker;
100
101// pub fn init_data_set(buff: &mut walrus::ModuleData, offset: u32, data: &[u8]) -> eyre::Result<()> {
102//     let data_ids = buff.iter().map(|data| data.id()).collect::<Vec<_>>();
103
104//     for id in data_ids {
105//         let data = buff.get_mut(id);
106//         if let walrus::DataKind::Active(walrus::ActiveData {
107//             memory: _,
108//             offset: walrus::ir::Value::I32(current_offset),
109//             ..
110//         }) = &data.kind
111//         {
112//             let current_offset = *current_offset as u32;
113//             if current_offset <= offset && offset < current_offset + data.value.len() as u32 {
114//                 let start = (offset - current_offset) as usize;
115//                 let end = std::cmp::min(start + data.value.len(), start + data.len());
116//                 data.value[start..end].copy_from_slice(&data[..(end - start)]);
117//                 return Ok(());
118//             }
119//         }
120//     }
121
122//     Ok(())
123// }
124
125/// A container holding global statics for tracking Wasm Names.
126#[derive(Debug)]
127pub struct WasmNameHolder(&'static [compact_str::CompactString], &'static AtomicUsize);
128
129impl WasmNameHolder {
130    /// Creates a new `WasmNameHolder`, leaking the provided names into static memory.
131    pub fn new(strings: Box<[compact_str::CompactString]>) -> Self {
132        let count = Box::leak(Box::new(AtomicUsize::new(0)));
133
134        let strings = Box::leak(strings);
135        WasmNameHolder(strings, count)
136    }
137
138    /// Returns an iterator over the underlying tracked `WasmName` items.
139    pub fn iter(&self) -> impl Iterator<Item = WasmName> {
140        self.0.iter().map(|s| WasmName::new(s.as_str(), self.1))
141    }
142}
143
144impl Drop for WasmNameHolder {
145    fn drop(&mut self) {
146        unsafe {
147            let _ = Box::from_raw(self.0 as *const _ as *mut [compact_str::CompactString]);
148            let count = self.1.load(std::sync::atomic::Ordering::SeqCst);
149            let _ = Box::from_raw(self.1 as *const _ as *mut AtomicUsize);
150            if count != 0 {
151                panic!(
152                    "WasmNameHolder dropped while there are still {count} WasmName instances alive"
153                );
154            }
155        }
156    }
157}
158
159/// Context-aware wrapper for a copied string slice with lifecycle tracking.
160pub struct WasmName(&'static str, &'static AtomicUsize);
161impl WasmName {
162    /// Creates a new tracked `WasmName`.
163    pub fn new(s: &'static str, counter: &'static AtomicUsize) -> Self {
164        counter.fetch_add(1, std::sync::atomic::Ordering::SeqCst);
165        WasmName(s, counter)
166    }
167}
168impl Drop for WasmName {
169    fn drop(&mut self) {
170        self.1.fetch_sub(1, std::sync::atomic::Ordering::SeqCst);
171    }
172}
173impl Clone for WasmName {
174    fn clone(&self) -> Self {
175        self.1.fetch_add(1, std::sync::atomic::Ordering::SeqCst);
176        WasmName(self.0, self.1)
177    }
178}
179impl std::hash::Hash for WasmName {
180    fn hash<H: std::hash::Hasher>(&self, state: &mut H) {
181        (self.0 as *const str).hash(state);
182    }
183}
184impl PartialEq for WasmName {
185    fn eq(&self, other: &Self) -> bool {
186        std::ptr::addr_eq(self.0 as *const _, other.0 as *const _)
187    }
188}
189impl Eq for WasmName {}
190impl std::fmt::Debug for WasmName {
191    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
192        write!(f, "{:?}", self.0)
193    }
194}
195impl std::fmt::Display for WasmName {
196    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
197        write!(f, "{}", self.0)
198    }
199}
200impl AsRef<str> for WasmName {
201    fn as_ref(&self) -> &str {
202        &self.0
203    }
204}
205impl Borrow<str> for WasmName {
206    fn borrow(&self) -> &str {
207        &self.0
208    }
209}
210
211/// Generates a standardized static import string for WASM component architectures.
212pub fn gen_component_name(namespace: &str, name: &str) -> String {
213    format!("[static]{namespace}.{}-import", name.replace("_", "-"))
214}
215
216/// Iterator for enumerating combinations of boolean features.
217#[derive(Debug)]
218pub struct BitIterator {
219    current: FeatureCombinationIteratorInnerBits,
220    skip: FeatureCombinationIteratorInnerBits, // if this bit is set, skip this iteration
221    kind: u8,
222}
223
224impl BitIterator {
225    const MAX_KIND: u8 = core::mem::size_of::<FeatureCombinationIteratorInnerBits>() as u8 * 8;
226
227    /// Constructs a new `BitIterator` for a given feature count.
228    pub fn new(kind: u8) -> Self {
229        if kind >= Self::MAX_KIND {
230            panic!("Kind must be between 0 and {}", Self::MAX_KIND - 1);
231        }
232
233        BitIterator {
234            current: FeatureCombinationIteratorInnerBits::ZERO,
235            kind,
236            skip: FeatureCombinationIteratorInnerBits::ZERO,
237        }
238    }
239
240    /// Retrieves the current bit state representation.
241    pub fn now(&self) -> FeatureCombinationIteratorInnerBits {
242        self.current
243    }
244
245    /// Registers a specific bit index to be skipped during iteration.
246    pub fn register_skip(&mut self, bit: u8) {
247        if bit >= Self::MAX_KIND {
248            panic!("Bit must be between 0 and {}", Self::MAX_KIND - 1);
249        }
250        self.skip.set(bit as usize, true);
251    }
252
253    /// Unregisters a raw mask of underlying bits from being skipped.
254    pub fn skip_raw(&mut self, mask: FeatureCombinationIteratorInnerBits) {
255        self.skip |= mask;
256    }
257
258    /// Unregisters a specific skipped bit index.
259    pub fn unregister_skip(&mut self, bit: u8) {
260        if bit >= Self::MAX_KIND {
261            panic!("Bit must be between 0 and {}", Self::MAX_KIND - 1);
262        }
263        self.skip.set(bit as usize, false);
264    }
265
266    /// Unregisters an exact sequence of raw iteration bits.
267    pub fn unregister_skip_raw(&mut self, mask: FeatureCombinationIteratorInnerBits) {
268        self.skip &= !mask;
269    }
270
271    /// Clears any registered skip states.
272    pub fn clear_skip(&mut self) {
273        self.skip = FeatureCombinationIteratorInnerBits::ZERO;
274    }
275}
276
277/// Underlying bit representations for the iterator generator.
278pub mod bits {
279    use bitvec::prelude::*;
280    type FeatureCombinationIteratorInnerBitsInner = BitArray<[u64; 2]>;
281
282    #[derive(Copy, Clone, Debug)]
283    /// Strongly typed inner bit representation optimized for combination tracking.
284    pub struct FeatureCombinationIteratorInnerBits(FeatureCombinationIteratorInnerBitsInner);
285
286    impl core::ops::BitAnd for FeatureCombinationIteratorInnerBits {
287        type Output = Self;
288
289        fn bitand(self, rhs: Self) -> Self::Output {
290            FeatureCombinationIteratorInnerBits { 0: self.0 & rhs.0 }
291        }
292    }
293
294    impl core::ops::BitAndAssign for FeatureCombinationIteratorInnerBits {
295        fn bitand_assign(&mut self, rhs: Self) {
296            self.0 &= rhs.0;
297        }
298    }
299
300    impl core::ops::BitOr for FeatureCombinationIteratorInnerBits {
301        type Output = Self;
302
303        fn bitor(self, rhs: Self) -> Self::Output {
304            FeatureCombinationIteratorInnerBits { 0: self.0 | rhs.0 }
305        }
306    }
307
308    impl core::ops::BitOrAssign for FeatureCombinationIteratorInnerBits {
309        fn bitor_assign(&mut self, rhs: Self) {
310            self.0 |= rhs.0;
311        }
312    }
313
314    impl core::ops::BitXor for FeatureCombinationIteratorInnerBits {
315        type Output = Self;
316
317        fn bitxor(self, rhs: Self) -> Self::Output {
318            FeatureCombinationIteratorInnerBits { 0: self.0 ^ rhs.0 }
319        }
320    }
321
322    impl core::ops::Not for FeatureCombinationIteratorInnerBits {
323        type Output = Self;
324
325        fn not(self) -> Self::Output {
326            FeatureCombinationIteratorInnerBits { 0: !self.0 }
327        }
328    }
329
330    impl core::ops::AddAssign for FeatureCombinationIteratorInnerBits {
331        fn add_assign(&mut self, rhs: Self) {
332            // arbitrary-precision integer
333            let raw_lhs = &mut self.0.data;
334            let raw_rhs = &rhs.0.data;
335            let mut carry = 0u64;
336
337            for i in 0..raw_lhs.len() {
338                let (sum1, carry1) = raw_lhs[i].overflowing_add(raw_rhs[i]);
339                let (sum2, carry2) = sum1.overflowing_add(carry);
340                raw_lhs[i] = sum2;
341                carry = (carry1 as u64) + (carry2 as u64);
342            }
343        }
344    }
345
346    impl core::cmp::PartialOrd for FeatureCombinationIteratorInnerBits {
347        fn partial_cmp(&self, other: &Self) -> Option<core::cmp::Ordering> {
348            self.0.partial_cmp(&other.0)
349        }
350    }
351
352    impl core::cmp::Ord for FeatureCombinationIteratorInnerBits {
353        fn cmp(&self, other: &Self) -> core::cmp::Ordering {
354            self.0.cmp(&other.0)
355        }
356    }
357
358    impl core::cmp::PartialEq for FeatureCombinationIteratorInnerBits {
359        fn eq(&self, other: &Self) -> bool {
360            self.0 == other.0
361        }
362    }
363
364    impl core::cmp::Eq for FeatureCombinationIteratorInnerBits {}
365
366    impl core::ops::Index<usize> for FeatureCombinationIteratorInnerBits {
367        type Output = bool;
368
369        fn index(&self, index: usize) -> &bool {
370            &self.0[index]
371        }
372    }
373
374    impl FeatureCombinationIteratorInnerBits {
375        /// Represents zero bits or no combinations active.
376        pub const ZERO: Self = FeatureCombinationIteratorInnerBits {
377            0: FeatureCombinationIteratorInnerBitsInner::ZERO,
378        };
379        /// Represents a standard first iteration or bit-start active.
380        pub const ONE: Self = Self::from_number(1);
381
382        /// Sets a specific position in the underlying representation.
383        pub fn set(&mut self, index: usize, value: bool) {
384            self.0.set(index, value);
385        }
386
387        /// Checks if this completely represents zeros.
388        pub fn is_zero(&self) -> bool {
389            self.0 == FeatureCombinationIteratorInnerBitsInner::ZERO
390        }
391
392        /// Checks if this is fully saturated.
393        pub fn is_full(&self) -> bool {
394            self.0.all()
395        }
396
397        /// Counts empty zeroes towards the most significant bit.
398        pub fn leading_zeros(&self) -> usize {
399            self.0.leading_zeros()
400        }
401
402        /// Counts empty zeroes towards the least significant bit.
403        pub fn trailing_zeros(&self) -> usize {
404            self.0.trailing_zeros()
405        }
406
407        /// Retrieves memory layout mapping to underlying pointers.
408        pub fn as_raw_slice(&self) -> &[u64] {
409            self.0.as_raw_slice()
410        }
411
412        /// Wraps static number initializations.
413        pub const fn from_number(num: u64) -> Self {
414            let mut bits: FeatureCombinationIteratorInnerBitsInner =
415                FeatureCombinationIteratorInnerBitsInner::ZERO;
416            bits.data[0] = num;
417            FeatureCombinationIteratorInnerBits { 0: bits }
418        }
419
420        /// Generates an instance securely masked to the indicated position.
421        pub fn from_one_pos(pos: usize) -> Self {
422            let mut bits: FeatureCombinationIteratorInnerBitsInner =
423                FeatureCombinationIteratorInnerBitsInner::ZERO;
424            bits.set(pos, true);
425            FeatureCombinationIteratorInnerBits { 0: bits }
426        }
427
428        /// Rapidly progresses to the next combination variant manually.
429        pub fn increment(&mut self) {
430            // arbitrary-precision integer
431            let raw = &mut self.0.data;
432            let mut carry = 1u64;
433
434            for i in 0..raw.len() {
435                let (new_value, new_carry) = raw[i].overflowing_add(carry);
436                raw[i] = new_value;
437                carry = if new_carry { 1 } else { 0 };
438                if carry == 0 {
439                    break;
440                }
441            }
442        }
443    }
444
445    #[cfg(test)]
446    mod tests {
447        use super::FeatureCombinationIteratorInnerBits;
448
449        #[test]
450        fn test_increment() {
451            let mut s = FeatureCombinationIteratorInnerBits::ZERO;
452            assert_eq!(s.leading_zeros(), 128);
453            s.set(1, true);
454            println!("{:?}", s.as_raw_slice());
455            assert_eq!(s.leading_zeros(), 1);
456
457            let mut a = FeatureCombinationIteratorInnerBits::ONE;
458            a.increment();
459            assert_eq!(a.as_raw_slice()[0], 2);
460
461            let mut b = FeatureCombinationIteratorInnerBits::from_number(u64::MAX);
462            b.increment();
463            assert_eq!(b.as_raw_slice()[0], 0);
464            assert_eq!(b.as_raw_slice()[1], 1);
465
466            let mut c = FeatureCombinationIteratorInnerBits::from_number(u64::MAX);
467            c.set(64, true);
468            c.increment();
469            assert_eq!(c.as_raw_slice()[0], 0);
470            assert_eq!(c.as_raw_slice()[1], 2);
471        }
472
473        #[test]
474        fn test_add_assign() {
475            let mut a = FeatureCombinationIteratorInnerBits::from_number(1);
476            let b = FeatureCombinationIteratorInnerBits::from_number(2);
477            a += b;
478            assert_eq!(a.as_raw_slice()[0], 3);
479
480            let mut c = FeatureCombinationIteratorInnerBits::from_number(u64::MAX);
481            let d = FeatureCombinationIteratorInnerBits::from_number(1);
482            c += d;
483            assert_eq!(c.as_raw_slice()[0], 0);
484            assert_eq!(c.as_raw_slice()[1], 1);
485
486            let mut e = FeatureCombinationIteratorInnerBits::from_number(u64::MAX);
487            e.set(64, true);
488            let f = FeatureCombinationIteratorInnerBits::from_number(1);
489            e += f;
490            assert_eq!(e.as_raw_slice()[0], 0);
491            assert_eq!(e.as_raw_slice()[1], 2);
492        }
493    }
494}
495pub use bits::FeatureCombinationIteratorInnerBits;
496
497impl Iterator for BitIterator {
498    type Item = FeatureCombinationIteratorInnerBits;
499
500    fn next(&mut self) -> Option<Self::Item> {
501        let count = core::mem::size_of::<FeatureCombinationIteratorInnerBits>() * 8
502            - self.current.trailing_zeros();
503        if count > self.kind as usize {
504            None
505        } else {
506            let result = self.current;
507            self.current.increment();
508
509            loop {
510                let flag = self.current & self.skip;
511                if flag.is_zero() {
512                    break;
513                } else {
514                    self.current +=
515                        FeatureCombinationIteratorInnerBits::from_one_pos(flag.leading_zeros());
516                }
517            }
518            Some(result)
519        }
520    }
521}
522
523#[derive(Debug)]
524/// Facilitates multi-state combination testing iteration mapping arrays.
525pub struct FeatureCombinationIterator<C: Borrow<T>, T: ?Sized> {
526    features: Vec<(
527        C,
528        FeatureCombinationIteratorInnerBits,
529        FeatureCombinationIteratorInnerBits,
530    )>,
531    current: BitIterator,
532    __marker: std::marker::PhantomData<T>,
533}
534
535impl<'a, T: 'a + ?Sized, B: Borrow<T>, C: Borrow<T>, I: IntoIterator<Item = B>> FromIterator<(C, I)>
536    for FeatureCombinationIterator<C, T>
537where
538    for<'c> &'c T: std::cmp::Eq + std::hash::Hash,
539{
540    fn from_iter<U: IntoIterator<Item = (C, I)>>(iter: U) -> Self {
541        // What T refers to
542        let data = iter
543            .into_iter()
544            .map(|(v, includes)| (v, includes.into_iter().collect::<Vec<_>>()))
545            .collect::<Vec<_>>();
546
547        // Referring to T
548        let num = {
549            let mut counts = HashMap::new();
550            // Initialize counts for all items to 0
551            for (v, _) in &data {
552                counts.insert(v.borrow(), 0isize);
553            }
554            // Count references
555            for (_, inc) in &data {
556                for v in inc {
557                    if let Some(c) = counts.get_mut(&v.borrow()) {
558                        *c += 1;
559                    }
560                }
561            }
562
563            data.iter()
564                .map(|(v, _)| -*counts.get(&v.borrow()).unwrap_or(&0))
565                .collect::<Vec<_>>()
566        };
567
568        let data = data.into_iter().zip(num).collect::<Vec<_>>();
569
570        // TODO!(); fix with behavior change
571        // data.sort_by_key(|(_, v)| *v);
572        // Remove 'num' from data, but keep dependencies
573        let mut data: Vec<(C, Vec<B>)> = data.into_iter().map(|(v, _)| v).collect();
574
575        // Check for non-trivial cycles (mutual references)
576        {
577            let index_map: std::collections::HashMap<&T, usize> = data
578                .iter()
579                .enumerate()
580                .map(|(i, (v, _))| (v.borrow(), i))
581                .collect();
582
583            let mut visited = vec![0u8; data.len()]; // 0: White, 1: Gray, 2: Black
584            let mut stack = Vec::new();
585
586            for i in 0..data.len() {
587                if visited[i] != 0 {
588                    continue;
589                }
590
591                stack.push((i, 0));
592                visited[i] = 1; // Gray
593
594                while let Some((u, dep_idx)) = stack.last_mut() {
595                    let u = *u;
596                    let deps = &data[u].1;
597                    if *dep_idx < deps.len() {
598                        let dep = &deps[*dep_idx];
599                        *dep_idx += 1;
600
601                        if let Some(&v) = index_map.get(&dep.borrow()) {
602                            if u == v {
603                                continue;
604                            }
605                            if visited[v] == 1 {
606                                panic!("Mutual reference detected!");
607                            }
608                            if visited[v] == 0 {
609                                visited[v] = 1;
610                                stack.push((v, 0));
611                            }
612                        }
613                    } else {
614                        // Finished processing u
615                        visited[u] = 2; // Black
616                        stack.pop();
617                    }
618                }
619            }
620        }
621
622        // Ensure that values referencing themselves are always placed on the right.
623        // if sortable, swap with a value that does not reference itself so we check it.
624        let mut count = 0i32;
625        loop {
626            let mut changed = false;
627            for i in 0..data.len() {
628                let mut swap_idx = None;
629                {
630                    let (ref_value, ref_includes) = &data[i];
631                    if ref_includes
632                        .iter()
633                        .any(|v| v.borrow() == ref_value.borrow())
634                    {
635                        // Find a value to swap with
636                        for j in (i + 1)..data.len() {
637                            let (_, swap_includes) = &data[j];
638                            if !swap_includes
639                                .iter()
640                                .any(|v| v.borrow() == ref_value.borrow())
641                            {
642                                swap_idx = Some(j);
643                                break;
644                            }
645                        }
646                    }
647                }
648
649                if let Some(j) = swap_idx {
650                    data.swap(i, j);
651                    changed = true;
652                }
653            }
654            if !changed {
655                break;
656            }
657            if count.checked_add(1).is_none() {
658                break;
659            }
660            count += 1;
661            if count as u128 > 1u128.checked_shl(data.len() as u32).unwrap_or(u128::MAX) {
662                panic!("Mutual reference detected!");
663            }
664        }
665
666        let (data, _): (Vec<_>, Vec<_>) = data.into_iter().map(|v| (v, ())).unzip();
667
668        let len = data.len();
669
670        let map = data
671            .iter()
672            .enumerate()
673            .map(|(i, (v, _))| (v.borrow(), i))
674            .collect::<HashMap<&T, usize>>();
675
676        // Rebuild dependents map from sorted data
677        let dependents_map = {
678            let mut dmap = data
679                .iter()
680                .map(|(v, _)| (v.borrow(), vec![]))
681                .collect::<HashMap<&T, Vec<&C>>>();
682
683            for (t, inc) in &data {
684                for v in inc {
685                    if let Some(list) = dmap.get_mut(&v.borrow()) {
686                        list.push(t);
687                    }
688                }
689            }
690            dmap
691        };
692
693        let mut features_base = Vec::with_capacity(data.len());
694        let mut dependencies_masks = Vec::with_capacity(data.len());
695        for (v, inc) in &data {
696            let deps = dependents_map
697                .get(&v.borrow())
698                .map(|v| v.as_slice())
699                .unwrap_or(&[]);
700            let mut mask = FeatureCombinationIteratorInnerBits::ZERO;
701            let mut indices = Vec::new();
702
703            for dep in deps {
704                let idx = map[&(*dep).borrow()];
705                mask.set(idx, true);
706                indices.push(idx);
707            }
708            features_base.push((indices, mask));
709
710            // Compute dependencies mask
711            let mut dep_mask = FeatureCombinationIteratorInnerBits::ZERO;
712            for d in inc {
713                if let Some(idx) = map.get(&d.borrow()) {
714                    dep_mask.set(*idx, true);
715                }
716            }
717            dependencies_masks.push(dep_mask);
718        }
719
720        let mut features_masks: Vec<FeatureCombinationIteratorInnerBits> =
721            features_base.iter().map(|(_, m)| *m).collect();
722
723        for _ in 0..data.len() {
724            let mut changed = false;
725            for i in 0..data.len() {
726                let (indices, _) = &features_base[i];
727                let mut mask = features_masks[i];
728                for &dep_idx in indices {
729                    mask |= features_masks[dep_idx];
730                    if mask != features_masks[i] { // Check against current stored mask, not 'old' local var if we updated it?
731                        // Logic: mask |= dep_mask.
732                        // If mask grew, changed=true.
733                    }
734                }
735                if mask != features_masks[i] {
736                    features_masks[i] = mask;
737                    changed = true;
738                }
739            }
740            if !changed {
741                break;
742            }
743        }
744
745        let features = features_masks
746            .into_iter()
747            .zip(dependencies_masks)
748            .zip(data)
749            .map(|((mask, dep_mask), (v, _))| (v, mask, dep_mask))
750            .collect::<Vec<_>>();
751
752        FeatureCombinationIterator {
753            features,
754            current: BitIterator::new(len as u8),
755            __marker: std::marker::PhantomData,
756        }
757    }
758}
759
760impl<C: Borrow<T> + std::cmp::Eq + std::hash::Hash + Clone, T: ?Sized> Iterator
761    for FeatureCombinationIterator<C, T>
762{
763    type Item = std::collections::HashSet<C>;
764
765    fn next(&mut self) -> Option<Self::Item> {
766        loop {
767            let bits = self.current.now();
768
769            // Check termination
770            let count = core::mem::size_of::<FeatureCombinationIteratorInnerBits>() * 8
771                - bits.trailing_zeros();
772            if count > self.current.kind as usize {
773                return None;
774            }
775
776            // Compute skip mask (dependents of absent features)
777            let mut _mask = FeatureCombinationIteratorInnerBits::ZERO;
778            for (i, (_, feature_bits, _)) in self.features.iter().enumerate() {
779                if !bits[i] {
780                    // Feature i is absent
781                    _mask |= *feature_bits; // Dependents of i are forbidden
782                }
783            }
784
785            // Compute skip mask (dependents of absent features)
786            // AND resolve violations (features present without dependencies)
787            let _mask = FeatureCombinationIteratorInnerBits::ZERO;
788
789            // Check for Forbidden features (because dependency is missing)
790            // This is equivalent to checking "Present features have all dependencies".
791
792            // Strategy: Iterate all features.
793            // If feature i is PRESENT:
794            //    Check dependencies_masks[i].
795            //    If ANY dependency d is ABSENT -> Violation.
796            //    violation |= (1 << i).
797            //    To resolve: Either Clear i (add 1<<i) OR Set d (add 1<<d).
798            //    We should pick the one that adds the LEAST to current.
799            //    If d < i: Set d.
800            //    If d > i: Clear i.
801            //    Also if Clear i, we might need to carry.
802
803            // We can compute minimum jump.
804
805            let mut min_jump = None;
806
807            for (i, (_, _, dependencies)) in self.features.iter().enumerate() {
808                if bits[i] {
809                    // Feature i is Present.
810                    // Dependencies must be Present.
811                    // Missing = dependencies & !bits.
812                    let missing = *dependencies & !bits;
813                    if !missing.is_zero() {
814                        // Violation! Feature i needs missing dependencies.
815                        // Options:
816                        // 1. Clear i (add 1<<i).
817                        // 2. Set d (for each d in missing). (add distance to d).
818
819                        // Option 1: Clear i.
820
821                        // Option 2: Set d.
822                        // For each d in missing:
823                        //   d_pos = trailing_zeros(d)?
824                        //   d_jump = 1<<d_pos - (bits & low_mask)?
825                        //   Wait. next_valid(bits, d) = (bits | (1<<d)) & !((1<<d)-1).
826                        //   jump = next_valid - bits.
827                        //   Or simplistically: 1<<d?
828                        //   If bits has lower bits set, 1<<d might not be enough or too much?
829                        //   Actually, we want to reach the *next* state where d=1.
830                        //   (bits | (1<<d)) & !((1<<d)-1).
831
832                        // Let's implement calculate_jump(current, target_bit).
833                        // But FeatureCombinationInnerBits doesn't expose arithmetic easily.
834                        // It has `from_one_pos`.
835                        // It has `+`.
836
837                        // If d < i.
838                        // Then bits[d]=0. bits[i]=1.
839                        // We want d=1.
840                        // Since d < i, d is a lower bit.
841                        // If we increment, d will toggle soon.
842                        // E.g. d=0. 0->1 is +1.
843                        // d=1. 00->10 is +2 (if 00).
844
845                        // If we just track "smallest bit that needs to change".
846                        // If any d < i.
847                        // Then we assume natural increment will handle it?
848                        // But we want to SKIP invalid states.
849                        // If d < i. We can jump to next d=1.
850                        // If d > i. We MUST clear i. (Jump to next i=0).
851
852                        // If d > i. Jump = 1<<i (Clear i).
853                        // If d < i. Jump = Next d=1.
854                        // Next d=1 is <= 1<<d (relative to cleared lower).
855
856                        // Let's optimize:
857                        // If ANY d > i: We MUST clear i.
858                        // Jump = 1<<i.
859
860                        // If ALL d < i:
861                        // We can wait for d.
862                        // Can we skip to d?
863                        // Yes. Jump to smallest d.
864                        // But we can't easily compute "Jump to d" with abstract bits.
865                        // But if d < i, and we assume Lsb0.
866                        // 1<<d is smaller than 1<<i.
867                        // So jump is smaller?
868                        // If we iterate violations and pick minimum 1<<pos.
869                        // If we pick 1<<i (Clear i).
870                        // If we pick 1<<d (Set d? No, 1<<d might not set d correctly if lower bits are messy).
871                        // But generally, adding 1<<d will toggle d (0->1) and clear lower.
872                        // So adding 1<<d IS correct to jump to next d=1.
873
874                        // So:
875                        // Candidates:
876                        // 1. 1<<i.
877                        // 2. 1<<d (for all d in missing).
878
879                        // Pick the SMALLEST candidate (lowest index).
880                        // And apply it.
881
882                        // If we find MULTIPLE violations.
883                        // We should pick the global minimum jump.
884
885                        // So loop over all i.
886                        // Collect candidates.
887                        // Pick min.
888
889                        // Candidate from i: i.
890                        // Candidates from missing: d's.
891
892                        // Wait. If d < i.
893                        // Should we set d or clear i?
894                        // If we set d (jump 1<<d), we keep i set. Result valid (i=1, d=1).
895                        // If we clear i (jump 1<<i), we get i=0. Result valid (i=0, d=0).
896                        // Which is next?
897                        // 1<<d is smaller. So we set d.
898
899                        // If d > i.
900                        // Set d (jump 1<<d). Keep i set.
901                        // Clear i (jump 1<<i).
902                        // 1<<i is smaller. So we clear i.
903
904                        // So strategy:
905                        // Collect all `i` (violation bits) and all `d` (missing dependencies).
906                        // Find the MINIMUM index `m` among them.
907                        // Add `1 << m`.
908
909                        // Example: i=1 (B). d=0 (A).
910                        // Min(1, 0) = 0.
911                        // Add 1<<0 (1).
912                        // 0010 + 1 = 0011 (A=1, B=1). Correct.
913
914                        // Example: i=0 (A). d=2 (C). (If A depended on C).
915                        // Min(0, 2) = 0.
916                        // Add 1<<0 (1).
917                        // 0001 + 1 = 0010 (A=0). Correct.
918
919                        // This logic is beautiful.
920                        // Just find the lowest bit involved in any violation (either the feature itself or its missing dependency).
921                        // And add 1 << that bit.
922
923                        // Iterate bits of missing.
924
925                        // Let's accumulate a "jump_mask".
926                        // jump_mask |= (1 << i).
927                        // jump_mask |= missing.
928
929                        if min_jump.is_none() {
930                            min_jump = Some(FeatureCombinationIteratorInnerBits::ZERO);
931                        }
932                        if let Some(ref mut j) = min_jump {
933                            j.set(i, true);
934                            *j |= missing;
935                        }
936                    }
937                }
938            }
939
940            if let Some(jump_mask) = min_jump {
941                // Found violations.
942                // We want smallest bit in jump_mask.
943                // Wait. trailing_zeros counts from MSB in BitArray (Lsb0)???
944                // NO. I decided earlier it counted from MSB.
945                // But leading_zeros counted from LSB?
946                // `from_one_pos` uses index.
947                // If I want index of lowest bit.
948                // If `Lsb0`: Index 0 is lowest.
949                // If `trailing_zeros` counts from End (127).
950                // `leading_zeros` counts from Start (0).
951                // So I want `leading_zeros`.
952
953                // Let's use `leading_zeros`.
954                let bit = jump_mask.leading_zeros(); // Index of first set bit (lowest index).
955                self.current.current += FeatureCombinationIteratorInnerBits::from_one_pos(bit);
956
957                // Continue loop
958            } else {
959                // Valid!
960                // ... return result ...
961                let mut result = std::collections::HashSet::new();
962                for (i, (feature, _, _)) in self.features.iter().enumerate() {
963                    if bits[i] {
964                        result.insert(feature.clone());
965                    }
966                }
967                self.current.current.increment();
968                return Some(result);
969            }
970        }
971    }
972}
973
974#[cfg(test)]
975mod tests {
976    use std::{collections::HashSet, sync::Arc};
977
978    use super::*;
979
980    #[test]
981    fn test_get_file_main_name() {
982        let path = camino::Utf8Path::new("name.opt.adjusted.wasm");
983        let file_name = path.get_file_main_name();
984        assert_eq!(file_name.unwrap(), "name");
985    }
986
987    #[test]
988    fn test_bit_generator() {
989        let bits = BitIterator::new(3).collect::<Vec<_>>();
990
991        assert_eq!(
992            &bits
993                .iter()
994                .map(|b| b.as_raw_slice()[0])
995                .collect::<Vec<u64>>(),
996            &[0b000, 0b001, 0b010, 0b011, 0b100, 0b101, 0b110, 0b111]
997        );
998
999        let count = BitIterator::new(10).count();
1000        assert_eq!(count, 1024);
1001
1002        let mut generator = BitIterator::new(5);
1003        generator.register_skip(1);
1004        generator.register_skip(3);
1005        let bits = generator.collect::<Vec<_>>();
1006
1007        assert_eq!(
1008            &bits
1009                .iter()
1010                .map(|b| b.as_raw_slice()[0])
1011                .collect::<Vec<u64>>(),
1012            &[
1013                0b00000, 0b00001, 0b00100, 0b00101, 0b10000, 0b10001, 0b10100, 0b10101
1014            ]
1015        );
1016    }
1017
1018    #[test]
1019    fn test_feature_combination_iterator() {
1020        let data = vec![
1021            ("A", vec![]),
1022            ("B", vec!["A"]),
1023            ("C", vec!["A"]),
1024            ("D", vec!["B", "C"]),
1025        ];
1026
1027        let iterator = data
1028            .into_iter()
1029            .collect::<FeatureCombinationIterator<_, str>>();
1030
1031        println!("Iterator created: {:?}", iterator);
1032
1033        let combinations = iterator.collect::<Vec<_>>();
1034
1035        let expected = vec![
1036            HashSet::from([]),
1037            HashSet::from(["A"]),
1038            HashSet::from(["A", "B"]),
1039            HashSet::from(["A", "C"]),
1040            HashSet::from(["A", "B", "C"]),
1041            HashSet::from(["A", "B", "C", "D"]),
1042        ];
1043
1044        assert_eq!(combinations, expected);
1045
1046        let data = vec![
1047            (String::from("A"), vec![]),
1048            (String::from("B"), vec![String::from("A")]),
1049            (String::from("C"), vec![String::from("A")]),
1050            (
1051                String::from("D"),
1052                vec![String::from("B"), String::from("C")],
1053            ),
1054        ];
1055        let data_ref = data
1056            .iter()
1057            .map(|(v, inc)| (v, inc.iter().map(|s| s).collect::<Vec<_>>()))
1058            .collect::<Vec<_>>();
1059
1060        let iterator = data
1061            .clone()
1062            .into_iter()
1063            .collect::<FeatureCombinationIterator<_, String>>();
1064
1065        let iterator2 = data_ref
1066            .into_iter()
1067            .collect::<FeatureCombinationIterator<_, String>>();
1068
1069        println!("Iterator created: {:?}", iterator);
1070
1071        let combinations = iterator.collect::<Vec<_>>();
1072        let _combinations2 = iterator2.collect::<Vec<_>>();
1073
1074        let expected = vec![
1075            HashSet::from([]),
1076            HashSet::from([String::from("A")]),
1077            HashSet::from([String::from("A"), String::from("B")]),
1078            HashSet::from([String::from("A"), String::from("C")]),
1079            HashSet::from([String::from("A"), String::from("B"), String::from("C")]),
1080            HashSet::from([
1081                String::from("A"),
1082                String::from("B"),
1083                String::from("C"),
1084                String::from("D"),
1085            ]),
1086        ];
1087
1088        assert_eq!(combinations, expected);
1089
1090        let data = data
1091            .iter()
1092            .map(|(u, v)| (Arc::new(u.clone()), v))
1093            .collect::<Vec<_>>();
1094
1095        let iterator = data
1096            .into_iter()
1097            .collect::<FeatureCombinationIterator<_, String>>();
1098
1099        println!("Iterator created: {:?}", iterator);
1100
1101        let _combinations = iterator.collect::<Vec<_>>();
1102    }
1103
1104    #[test]
1105    #[should_panic(expected = "Mutual reference detected!")]
1106    fn test_feature_combination_iterator_mutual_ref() {
1107        // A includes B
1108        // B includes A
1109        // Cycle!
1110        let data = vec![
1111            (String::from("A"), vec![String::from("B")]),
1112            (String::from("B"), vec![String::from("A")]),
1113        ];
1114
1115        let _iterator = data
1116            .into_iter()
1117            .collect::<FeatureCombinationIterator<_, String>>();
1118    }
1119
1120    #[test]
1121    #[should_panic(expected = "Mutual reference detected!")]
1122    fn test_feature_combination_iterator_complex_cycle() {
1123        // A -> B -> C -> A
1124        let data = vec![
1125            (String::from("A"), vec![String::from("B")]),
1126            (String::from("B"), vec![String::from("C")]),
1127            (String::from("C"), vec![String::from("A")]),
1128        ];
1129
1130        let _iterator = data
1131            .into_iter()
1132            .collect::<FeatureCombinationIterator<_, String>>();
1133    }
1134
1135    #[test]
1136    fn test_feature_combination_iterator_complex_valid() {
1137        // Valid graph:
1138        // A -> B, C
1139        // B -> D
1140        // C -> D
1141        // D -> []
1142        // Order should handle this (D comes first, then B/C, then A)
1143
1144        let data = vec![
1145            (
1146                String::from("A"),
1147                vec![String::from("B"), String::from("C")],
1148            ),
1149            (String::from("B"), vec![String::from("D")]),
1150            (String::from("C"), vec![String::from("D")]),
1151            (String::from("D"), vec![]),
1152        ];
1153
1154        let iterator = data
1155            .into_iter()
1156            .collect::<FeatureCombinationIterator<_, String>>();
1157
1158        let combinations = iterator.collect::<Vec<_>>();
1159        // If it didn't panic and produced combinations, the topological sort/check worked for this valid case.
1160        assert!(combinations.len() > 0);
1161    }
1162
1163    #[test]
1164    fn test_feature_combination_iterator_complex_diamond() {
1165        use std::collections::{HashMap, HashSet};
1166        // Diamond:
1167        // Root -> Left, Right
1168        // Left -> Base
1169        // Right -> Base
1170        // Base -> []
1171
1172        let data = vec![
1173            (
1174                String::from("Root"),
1175                vec![String::from("Left"), String::from("Right")],
1176            ),
1177            (String::from("Left"), vec![String::from("Base")]),
1178            (String::from("Right"), vec![String::from("Base")]),
1179            (String::from("Base"), vec![]),
1180        ];
1181
1182        let iterator = data
1183            .into_iter()
1184            .collect::<FeatureCombinationIterator<_, String>>();
1185
1186        let combinations: Vec<HashSet<String>> = iterator.collect();
1187
1188        // Verify that for every combination, if a feature is present, its dependencies are also present.
1189        // We can check this property for all combinations.
1190
1191        // Dependency map for checking
1192        let deps: HashMap<String, Vec<String>> = HashMap::from([
1193            (
1194                String::from("Root"),
1195                vec![String::from("Left"), String::from("Right")],
1196            ),
1197            (String::from("Left"), vec![String::from("Base")]),
1198            (String::from("Right"), vec![String::from("Base")]),
1199            (String::from("Base"), vec![]),
1200        ]);
1201
1202        for combo in &combinations {
1203            for feature in combo {
1204                if let Some(required) = deps.get(feature) {
1205                    for req in required {
1206                        assert!(
1207                            combo.contains(req),
1208                            "Combination {:?} invalid: {} requires {}",
1209                            combo,
1210                            feature,
1211                            req
1212                        );
1213                    }
1214                }
1215            }
1216        }
1217
1218        // Also verify some known valid combinations are present
1219        assert!(combinations.contains(&HashSet::from([])));
1220        assert!(combinations.contains(&HashSet::from([String::from("Base")])));
1221        assert!(
1222            combinations.contains(&HashSet::from([String::from("Base"), String::from("Left")]))
1223        );
1224        assert!(combinations.contains(&HashSet::from([
1225            String::from("Base"),
1226            String::from("Left"),
1227            String::from("Right"),
1228            String::from("Root")
1229        ])));
1230
1231        // Verify invalid ones are NOT present
1232        // Root only
1233        assert!(!combinations.contains(&HashSet::from([String::from("Root")])));
1234        // Left only
1235        assert!(!combinations.contains(&HashSet::from([String::from("Left")])));
1236    }
1237}