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