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;
13use walrus::{ir::InstrSeqId, *};
14
15use crate::{
16    args::TargetMemoryType,
17    instrs::{InstrRead, InstrRewrite as _},
18    unique_name::UniqueNameMarker,
19};
20
21#[allow(dead_code)]
22pub(crate) trait WalrusUtilImport: Debug {
23    fn find_mut<A>(&mut self, as_fn: impl WalrusFID<A>) -> eyre::Result<&mut Import>;
24
25    /// Swap two imports but if other not found, skip
26    /// This is useful when you want to swap imports that may not exist
27    fn may_swap_import<A>(
28        &mut self,
29        one: impl WalrusFID<A>,
30        other: (impl AsRef<str>, impl AsRef<str>),
31    ) -> eyre::Result<()>
32    where
33        Self: Sized,
34    {
35        let other_module = other.0.as_ref();
36        let other_name = other.1.as_ref();
37
38        let one_import = self
39            .find_mut(one)
40            .wrap_err_with(|| eyre::eyre!("One Import {} not found", one.as_str()))?;
41
42        let one_module = one_import.module.clone();
43        let one_name = one_import.name.clone();
44
45        one_import.module = "archived".to_string();
46
47        self.find_mut((other_module, other_name))
48            .ok()
49            .map(|import| {
50                import.module = one_module;
51                import.name = one_name.clone();
52            });
53
54        let one_import = self.find_mut(("archived", &one_name)).unwrap();
55
56        one_import.module = other_module.to_string();
57        one_import.name = other_name.to_string();
58
59        Ok(())
60    }
61
62    fn swap_import<A, B>(
63        &mut self,
64        one: impl WalrusFID<A>,
65        other: impl WalrusFID<B>,
66    ) -> eyre::Result<()>
67    where
68        Self: Sized,
69    {
70        let (other_module, other_name) = {
71            let other_import = self
72                .find_mut(other)
73                .wrap_err_with(|| eyre::eyre!("Other Import {} not found", other.as_str()))?;
74            (other_import.module.clone(), other_import.name.clone())
75        };
76
77        let one_import = self
78            .find_mut(one)
79            .wrap_err_with(|| eyre::eyre!("One Import {} not found", one.as_str()))?;
80
81        let one_module = one_import.module.clone();
82        let one_name = one_import.name.clone();
83
84        one_import.module = "archived".to_string();
85
86        let other_import = self.find_mut(other).unwrap();
87
88        other_import.module = one_module;
89        other_import.name = one_name.clone();
90
91        let one_import = self.find_mut(("archived", &one_name)).unwrap();
92
93        one_import.module = other_module;
94        one_import.name = other_name.clone();
95
96        Ok(())
97    }
98
99    fn erase<A>(&mut self, as_fn: impl WalrusFID<A>) -> eyre::Result<()>;
100}
101
102pub(crate) trait WalrusUtilExport: Debug {
103    /// As it deletes based on the fid, it may involve functions that export the same function.
104    fn erase<A>(&mut self, as_fn: impl WalrusFID<A>) -> eyre::Result<()>;
105    /// As it deletes based on the fid, it may involve functions that export the same function.
106    fn erase_with<A>(&mut self, as_fn: impl WalrusFID<A>, debug: bool) -> eyre::Result<()> {
107        if !debug { self.erase(as_fn) } else { Ok(()) }
108    }
109}
110
111pub(crate) trait WalrusUtilFuncs {
112    /// Find children flat functions
113    fn find_children(
114        &self,
115        fid: impl Borrow<FunctionId>,
116        allow_call_indirect: bool,
117    ) -> eyre::Result<Vec<FunctionId>>;
118
119    /// Find children flat functions with self
120    fn find_children_with(
121        &self,
122        fid: impl Borrow<FunctionId>,
123        allow_call_indirect: bool,
124    ) -> eyre::Result<Vec<FunctionId>> {
125        let fid = *fid.borrow();
126        let mut children = self.find_children(fid, allow_call_indirect)?;
127        if !children.contains(&fid) {
128            children.insert(0, fid);
129        }
130        Ok(children)
131    }
132
133    /// call rewrite on function
134    fn rewrite<T>(
135        &mut self,
136        find: impl FnMut(&mut ir::Instr, (usize, InstrSeqId)) -> T,
137        fid: impl Borrow<FunctionId>,
138    ) -> eyre::Result<Vec<T>>
139    where
140        Self: Sized;
141
142    /// call rewrite on children functions
143    fn flat_rewrite<T>(
144        &mut self,
145        find: impl FnMut(&mut ir::Instr, (usize, InstrSeqId)) -> T,
146        fid: impl Borrow<FunctionId>,
147        allow_call_indirect: bool,
148    ) -> eyre::Result<Vec<T>>
149    where
150        Self: Sized;
151
152    fn read<T>(
153        &self,
154        find: impl FnMut(&ir::Instr, (usize, InstrSeqId)) -> T,
155        fid: impl Borrow<FunctionId>,
156    ) -> eyre::Result<Vec<T>>
157    where
158        Self: Sized;
159
160    fn flat_read<T>(
161        &self,
162        find: impl FnMut(&ir::Instr, (usize, InstrSeqId)) -> T,
163        fid: impl Borrow<FunctionId>,
164    ) -> eyre::Result<Vec<T>>
165    where
166        Self: Sized;
167
168    fn all_rewrite<T>(
169        &mut self,
170        find: impl FnMut(&mut ir::Instr, (usize, InstrSeqId)) -> T,
171        exclude: &[impl Borrow<FunctionId>],
172    ) -> eyre::Result<Vec<T>>
173    where
174        Self: Sized;
175
176    fn all_read<T>(
177        &self,
178        find: impl FnMut(&ir::Instr, (usize, InstrSeqId)) -> T,
179        exclude: &[impl Borrow<FunctionId>],
180    ) -> eyre::Result<Vec<T>>
181    where
182        Self: Sized;
183
184    fn par_flat_read<T: Send>(
185        &self,
186        find: impl Fn(&ir::Instr, (usize, InstrSeqId)) -> T + Sync + Send,
187        fid: impl Borrow<FunctionId>,
188    ) -> eyre::Result<Vec<T>>
189    where
190        Self: Sized;
191
192    fn par_all_rewrite<T: Send>(
193        &mut self,
194        find: impl Fn(&mut ir::Instr, (usize, InstrSeqId)) -> T + Sync + Send,
195        exclude: &[impl Borrow<FunctionId> + Sync],
196    ) -> eyre::Result<Vec<T>>
197    where
198        Self: Sized;
199
200    fn par_flat_rewrite<T: Send>(
201        &mut self,
202        find: impl Fn(&mut ir::Instr, (usize, InstrSeqId)) -> T + Sync + Send,
203        fid: impl Borrow<FunctionId>,
204        allow_call_indirect: bool,
205    ) -> eyre::Result<Vec<T>>
206    where
207        Self: Sized;
208}
209
210#[allow(dead_code)]
211pub(crate) trait WalrusUtilModule {
212    /// connect function from import to export
213    /// export will be removed
214    /// and import will be replaced with the export function
215    fn connect_func<A, B>(
216        &mut self,
217        import: impl WalrusFID<A>,
218        export: impl WalrusFID<B>,
219    ) -> eyre::Result<()> {
220        self.connect_func_with_is_delete(import, export, true)
221    }
222
223    fn connect_func_alt<A, B>(
224        &mut self,
225        import: impl WalrusFID<A>,
226        export: impl WalrusFID<B>,
227    ) -> eyre::Result<()>;
228
229    fn connect_func_alt_with_remove_export<A>(
230        &mut self,
231        import: impl WalrusFID<A>,
232        export: impl AsRef<str>,
233        is_debug: bool,
234    ) -> eyre::Result<()>;
235
236    fn connect_func_without_remove<A, B>(
237        &mut self,
238        import: impl WalrusFID<A>,
239        export: impl WalrusFID<B>,
240    ) -> eyre::Result<()> {
241        self.connect_func_with_is_delete(import, export, false)
242    }
243
244    fn connect_func_with_is_delete<A, B>(
245        &mut self,
246        import: impl WalrusFID<A>,
247        export: impl WalrusFID<B>,
248        is_delete: bool,
249    ) -> eyre::Result<()>;
250
251    /// add fake function to the module
252    /// and return the function id
253    fn add_func(
254        &mut self,
255        params: &[ValType],
256        results: &[ValType],
257        fn_: impl FnMut(&mut FunctionBuilder, &Vec<LocalId>) -> eyre::Result<()>,
258    ) -> eyre::Result<FunctionId>;
259
260    /// get the memory id from target name
261    /// and remove anchor
262    fn get_memory_anchor(&mut self, name: impl AsRef<str>, remove: bool) -> eyre::Result<MemoryId> {
263        self.get_memory_anchor_with_info::<String>(name, remove)
264            .map(|(mem_id, _)| mem_id)
265    }
266
267    fn get_memory_anchor_with_info<T: ToString + std::str::FromStr>(
268        &mut self,
269        name: impl AsRef<str>,
270        remove: bool,
271    ) -> eyre::Result<(MemoryId, Option<T>)>
272    where
273        <T as std::str::FromStr>::Err: Debug;
274
275    fn find_used_memory_id(&self, memory_hint: Option<usize>) -> eyre::Result<MemoryId>;
276
277    // fn flatten_tables(&mut self) -> eyre::Result<()>;
278
279    /// create memory anchor function
280    fn create_memory_anchor(
281        &mut self,
282        name: impl AsRef<str>,
283        memory_id: MemoryId,
284    ) -> eyre::Result<MemoryId> {
285        self.create_memory_anchor_with_info(name, memory_id, None::<String>)?;
286
287        Ok(memory_id)
288    }
289
290    fn create_memory_anchor_with_info(
291        &mut self,
292        name: impl AsRef<str>,
293        memory_id: MemoryId,
294        with_info: Option<impl ToString + FromStr>,
295    ) -> eyre::Result<()>;
296
297    fn get_memory_type(&mut self, is_remove: bool) -> eyre::Result<TargetMemoryType>;
298
299    fn get_global_anchor(&mut self, name: impl AsRef<str>) -> eyre::Result<Box<[GlobalId]>>;
300
301    fn create_global_anchor(&mut self, name: impl AsRef<str>) -> eyre::Result<()>;
302
303    /// Return all functions that call functions in this fid
304    fn get_using_func<A>(
305        &self,
306        as_fn: impl WalrusFID<A>,
307        allow_call_indirect: bool,
308    ) -> eyre::Result<Vec<(FunctionId, InstrSeqId, usize)>>;
309
310    fn renew_id_on_table<A, B>(
311        &mut self,
312        old: impl WalrusFID<A>,
313        new: impl WalrusFID<B>,
314    ) -> eyre::Result<()>
315    where
316        Self: Sized;
317
318    fn fid_pos_on_table<A>(
319        &self,
320        as_fn: impl WalrusFID<A>,
321    ) -> eyre::Result<Box<[(TableId, usize)]>>;
322
323    fn renew_call_fn<A, B>(
324        &mut self,
325        old: impl WalrusFID<A>,
326        new: impl WalrusFID<B>,
327    ) -> eyre::Result<()>
328    where
329        Self: Sized;
330
331    // this is broken
332    // fn renew_call_fn_in_the_fn(
333    //     &mut self,
334    //     old_id: impl Borrow<FunctionId>,
335    //     new_id: impl Borrow<FunctionId>,
336    //     fn_id: impl Borrow<FunctionId>,
337    // ) -> eyre::Result<()>
338    // where
339    //     Self: Sized;
340
341    fn gen_new_function(
342        &mut self,
343        params: &[ValType],
344        results: &[ValType],
345        fn_: impl FnOnce(&mut FunctionBuilder, &Vec<LocalId>) -> eyre::Result<()>,
346    ) -> eyre::Result<FunctionId>
347    where
348        Self: Sized;
349
350    fn check_function_type<A, B>(
351        &self,
352        before: impl WalrusFID<A>,
353        after: impl WalrusFID<B>,
354    ) -> eyre::Result<()>
355    where
356        Self: Sized;
357
358    #[allow(dead_code)]
359    fn debug_call_indirect<A>(&mut self, debugger: impl WalrusFID<A>) -> eyre::Result<()>
360    where
361        Self: Sized;
362
363    #[allow(dead_code)]
364    fn gen_inspect<const N: usize, A>(
365        &mut self,
366        inspector: impl WalrusFID<A>,
367        params: &[ValType],
368        exclude: &[impl Borrow<FunctionId>],
369        filter: impl FnMut(&ir::Instr) -> Option<[i32; N]>,
370    ) -> eyre::Result<()>
371    where
372        Self: Sized,
373    {
374        self.gen_inspect_with_finalize(
375            Some(inspector),
376            None::<FunctionId>,
377            params,
378            &[],
379            exclude,
380            filter,
381        )
382    }
383
384    #[allow(dead_code)]
385    fn gen_finalize<const N: usize, A>(
386        &mut self,
387        finalize: impl WalrusFID<A>,
388        params: &[ValType],
389        exclude: &[impl Borrow<FunctionId>],
390        filter: impl FnMut(&ir::Instr) -> Option<[i32; N]>,
391    ) -> eyre::Result<()>
392    where
393        Self: Sized,
394    {
395        self.gen_inspect_with_finalize(
396            None::<FunctionId>,
397            Some(finalize),
398            &[],
399            params,
400            exclude,
401            filter,
402        )
403    }
404
405    #[allow(dead_code)]
406    fn gen_inspect_with_finalize<const N: usize, A, B>(
407        &mut self,
408        inspector: Option<impl WalrusFID<A>>,
409        finalize: Option<impl WalrusFID<B>>,
410        params: &[ValType],
411        results: &[ValType],
412        exclude: &[impl Borrow<FunctionId>],
413        filter: impl FnMut(&ir::Instr) -> Option<[i32; N]>,
414    ) -> eyre::Result<()>
415    where
416        Self: Sized;
417
418    #[allow(dead_code)]
419    fn assert_i32_const(
420        &mut self,
421        val: i32,
422    ) -> eyre::Result<impl FnMut(&mut walrus::InstrSeqBuilder) -> eyre::Result<()> + 'static>;
423
424    fn load(path: impl AsRef<Path>, dwarf: bool) -> eyre::Result<Self>
425    where
426        Self: Sized;
427
428    fn copy_func<A>(&mut self, from: impl WalrusFID<A>) -> eyre::Result<walrus::FunctionId>
429    where
430        Self: Sized;
431
432    /// This method copies functions by copying the functions called internally.
433    /// It is used to rewrite the internal instructions of functions called under specific conditions.
434    /// Note: that calls_indirect may throw errors.
435    /// If you include yourself in the exclude list, only the function being called will be copied.
436    /// Note: that even if a function not included in the exclude list is called, that call will not be updated.
437    fn nested_copy_func<A>(
438        &mut self,
439        from: impl WalrusFID<A>,
440        exclude: &[impl Borrow<FunctionId>],
441        allow_import_func: bool,
442        allow_call_indirect: bool,
443    ) -> eyre::Result<walrus::FunctionId>
444    where
445        Self: Sized;
446
447    fn renew_export<A, B>(
448        &mut self,
449        old: impl WalrusFID<A>,
450        new: impl WalrusFID<B>,
451    ) -> eyre::Result<()>
452    where
453        Self: Sized;
454
455    fn save_info(
456        &mut self,
457        salt: impl AsRef<str>,
458        info: impl ToString + FromStr,
459    ) -> eyre::Result<()>;
460
461    fn load_info<T: ToString + FromStr>(&mut self, salt: impl AsRef<str>) -> eyre::Result<T>
462    where
463        <T as std::str::FromStr>::Err: Debug;
464}
465
466impl WalrusUtilImport for ModuleImports {
467    fn find_mut<A>(&mut self, as_fn: impl WalrusFID<A>) -> eyre::Result<&mut Import> {
468        let fid = as_fn.get_fid(self)?;
469
470        let import_id = self.get_imported_func(fid).unwrap().id();
471
472        Ok(self.get_mut(import_id))
473    }
474
475    fn erase<A>(&mut self, as_fn: impl WalrusFID<A>) -> eyre::Result<()> {
476        let fid = as_fn.get_fid(self)?;
477        let import_id = self
478            .iter()
479            .find(|f| {
480                if let walrus::ImportKind::Function(f) = f.kind {
481                    f == fid
482                } else {
483                    false
484                }
485            })
486            .map(|f| f.id())
487            .ok_or_else(|| eyre::eyre!("Import not found: {}", as_fn.as_str()))?;
488
489        self.delete(import_id);
490
491        Ok(())
492    }
493}
494
495impl WalrusUtilExport for ModuleExports {
496    fn erase<A>(&mut self, as_fn: impl WalrusFID<A>) -> eyre::Result<()> {
497        let fid = as_fn.get_fid(self)?;
498
499        let export_id = self
500            .iter()
501            .filter(|f| matches!(f.item, walrus::ExportItem::Function(f) if f == fid))
502            .map(|f| f.id())
503            .exactly_one()
504            .to_eyre()
505            .wrap_err("Expected exactly one export for function")?;
506
507        self.delete(export_id);
508
509        Ok(())
510    }
511}
512
513impl WalrusUtilModule for walrus::Module {
514    fn connect_func_with_is_delete<A, B>(
515        &mut self,
516        import: impl WalrusFID<A>,
517        export: impl WalrusFID<B>,
518        is_delete: bool,
519    ) -> eyre::Result<()> {
520        let fid = import.get_fid(&self.imports)?;
521        let export_id = export.get_fid(&self.exports)?;
522
523        self.check_function_type(fid, export_id)
524            .wrap_err("Function types do not match on connect func inner")?;
525
526        self.replace_imported_func(fid, |(builder, arg_locals)| {
527            let mut func_body = builder.func_body();
528
529            for local in arg_locals {
530                func_body.local_get(*local);
531            }
532            func_body.call(export_id);
533            func_body.return_();
534        })
535        .to_eyre()
536        .wrap_err_with(|| eyre::eyre!("Failed to replace imported function"))?;
537
538        let export_id = self
539            .exports
540            .iter()
541            .find(|f| {
542                if let walrus::ExportItem::Function(f) = f.item {
543                    f == export_id
544                } else {
545                    false
546                }
547            })
548            .map(|f| f.id())
549            .ok_or_else(|| eyre::eyre!("Export not found"))?;
550
551        if is_delete {
552            self.exports.delete(export_id);
553        }
554
555        Ok(())
556    }
557
558    fn add_func(
559        &mut self,
560        params: &[ValType],
561        results: &[ValType],
562        fn_: impl FnOnce(&mut FunctionBuilder, &Vec<LocalId>) -> eyre::Result<()>,
563    ) -> eyre::Result<FunctionId> {
564        let mut builder = FunctionBuilder::new(&mut self.types, params, results);
565
566        let args = params
567            .iter()
568            .map(|ty| self.locals.add(*ty))
569            .collect::<Vec<_>>();
570
571        fn_(&mut builder, &args)?;
572
573        Ok(builder.finish(args, &mut self.funcs))
574    }
575
576    /// if vfs, get vfs memory_id
577    fn get_memory_anchor_with_info<T: ToString + std::str::FromStr>(
578        &mut self,
579        name: impl AsRef<str>,
580        remove: bool,
581    ) -> eyre::Result<(MemoryId, Option<T>)>
582    where
583        <T as std::str::FromStr>::Err: Debug,
584    {
585        let name = name.as_ref();
586
587        let anchor_name = self
588            .exports
589            .iter()
590            .find_map(|export| {
591                if matches!(export.item, walrus::ExportItem::Function(_))
592                    && export
593                        .name
594                        .starts_with(&format!("__wasip1_vfs_flag_{name}_memory"))
595                {
596                    Some(export.name.clone())
597                } else {
598                    None
599                }
600            })
601            .ok_or_else(|| eyre::eyre!("Memory anchor function not found"))?;
602        let anchor_func_id = anchor_name.get_fid(&self.exports).unwrap();
603
604        self.exports.erase_with(anchor_func_id, !remove)?;
605
606        let anchor_body = &self.funcs.get(anchor_func_id).kind;
607
608        let local_func = anchor_body.unwrap_local();
609
610        let func_body = local_func.block(local_func.entry_block());
611        let memory_id = func_body
612            .iter()
613            .map(|(block, _)| block)
614            .filter_map(|block| match block {
615                ir::Instr::Load(ir::Load { memory, .. }) => Some(*memory),
616                ir::Instr::Store(ir::Store { memory, .. }) => Some(*memory),
617                _ => None,
618            })
619            .fold(Ok(Option::<MemoryId>::None), |a, b| match a? {
620                Some(a) if a == b => Ok(Some(a)),
621                None => Ok(Some(b)),
622                Some(_) => eyre::bail!("Anchor access double memory, cannot determine memory id"),
623            })?
624            .ok_or_else(|| eyre::eyre!("Memory not found"))?;
625
626        let anchor_name_ex = anchor_name
627            .strip_prefix(&format!("__wasip1_vfs_flag_{name}_memory"))
628            .unwrap();
629        let with_info = if anchor_name_ex.starts_with("_with_") {
630            Some(
631                anchor_name_ex
632                    .strip_prefix("_with_")
633                    .unwrap()
634                    .parse::<T>()
635                    .map_err(|e| eyre::eyre!("{e:?}"))
636                    .wrap_err_with(|| {
637                        eyre::eyre!("Failed to parse memory anchor info: {anchor_name_ex}")
638                    })?,
639            )
640        } else {
641            None
642        };
643
644        Ok((memory_id, with_info))
645    }
646
647    fn find_used_memory_id(&self, memory_hint: Option<usize>) -> eyre::Result<MemoryId> {
648        let memories = self
649            .memories
650            .iter()
651            .map(|memory| memory.id())
652            .collect::<Vec<_>>();
653
654        if memories.is_empty() {
655            eyre::bail!("No memories found");
656        }
657
658        // After calling environ_sizes_get,
659        // identify the memory using the memory referenced
660        // by the code trying to read the pointer
661        let memory_id = if memories.len() > 1 && memory_hint.is_none() {
662            let gen_memory_id = || -> eyre::Result<MemoryId> {
663                // environ_sizes_get
664                let import_id =
665                    ("wasi_snapshot_preview1", "environ_sizes_get").get_fid(&self.imports)?;
666
667                let using_funcs = self.get_using_func(import_id, true)?;
668
669                let ret_mem_id = std::sync::Arc::new(std::sync::Mutex::new(None));
670
671                for (fid, _, _) in using_funcs {
672                    let arg_ptr =
673                        std::sync::Arc::new(std::sync::Mutex::new(Option::<Vec<u64>>::None));
674                    let arg_ptr_c = arg_ptr.clone();
675
676                    let ret_mem_id_c = ret_mem_id.clone();
677
678                    let mut interpreter = walrus_simple_interpreter::Interpreter::new(self)
679                        .to_eyre()
680                        .wrap_err_with(|| eyre::eyre!("Failed to create interpreter"))?;
681
682                    interpreter.set_interrupt_handler_mem(move |_, _, _, (id, address, _, ty)| {
683
684                    if matches!(ty, walrus_simple_interpreter::MemoryAccessType::Load) {
685                        if let Some(v) = arg_ptr_c.lock().unwrap().as_ref() {
686                            if v.contains(&address) {
687                                if let Some(mem_id) = ret_mem_id_c.clone().lock().unwrap().as_ref() {
688                                    if *mem_id != id {
689                                        return Err(anyhow::anyhow!(
690                                            "Memory access double memory, cannot determine memory id"
691                                        ));
692                                    }
693                                } else {
694                                    ret_mem_id_c.clone().lock().unwrap().replace(id);
695                                }
696                            }
697                        }
698                    }
699
700                    Ok(())
701                });
702
703                    let memories = memories.clone();
704
705                    interpreter.add_function("environ_sizes_get", move |interpreter, args| {
706                        let args = args
707                            .iter()
708                            .map(|arg| {
709                                if let ir::Value::I32(arg) = arg {
710                                    Ok(*arg as u64)
711                                } else {
712                                    Err(anyhow::anyhow!("Invalid argument type"))
713                                }
714                            })
715                            .collect::<Result<Vec<_>, _>>()?;
716                        interpreter.mem_set_i32(memories[0], args[0], 0)?;
717                        interpreter.mem_set_i32(memories[0], args[1], 0)?;
718
719                        arg_ptr.lock().unwrap().replace(args);
720
721                        Ok(vec![ir::Value::I32(0)])
722                    });
723
724                    let args = self
725                        .types
726                        .get(self.funcs.get(fid).ty())
727                        .params()
728                        .iter()
729                        .map(|ty| ty.normal())
730                        .collect::<eyre::Result<Vec<_>>>()
731                        .wrap_err_with(|| eyre::eyre!("Failed to get function args"))?;
732                    if let Err(e) = interpreter.call(fid, self, &args).to_eyre() {
733                        if ret_mem_id.lock().unwrap().is_none() {
734                            eprintln!("Error: {e}");
735                        }
736                    }
737                }
738
739                if let Some(mem_id) = ret_mem_id.lock().unwrap().as_ref() {
740                    Ok(*mem_id)
741                } else {
742                    return Err(eyre::eyre!("Memory not found"));
743                }
744            };
745            gen_memory_id().wrap_err_with(|| {
746                eyre::eyre!("Failed to detect memory id. You can use memory hint.")
747            })?
748        } else if let Some(memory_hint) = memory_hint {
749            if memory_hint >= memories.len() {
750                return Err(eyre::eyre!(
751                    "Memory hint {} is out of bounds for memories: {:?}",
752                    memory_hint,
753                    memories
754                ));
755            }
756            memories[memory_hint]
757        } else {
758            memories[0]
759        };
760
761        Ok(memory_id)
762    }
763
764    fn create_memory_anchor_with_info(
765        &mut self,
766        name: impl AsRef<str>,
767        memory_id: MemoryId,
768        with_info: Option<impl ToString + FromStr>,
769    ) -> eyre::Result<()> {
770        let name = name.as_ref();
771
772        // unsafe extern "C" fn __wasip1_vfs_flag_vfs_memory(ptr: *mut u8, src: *mut u8) {
773        //     unsafe { core::ptr::copy_nonoverlapping(src, ptr, 1) };
774        // }
775        let id = self.add_func(&[ValType::I32, ValType::I32], &[], |builder, arg_locals| {
776            let mut func_body = builder.func_body();
777
778            func_body
779                .local_get(arg_locals[0])
780                .local_get(arg_locals[1])
781                .load(
782                    memory_id,
783                    ir::LoadKind::I32_8 {
784                        kind: ir::ExtendedLoad::ZeroExtend,
785                    },
786                    ir::MemArg {
787                        offset: 0,
788                        align: 0,
789                    },
790                )
791                .store(
792                    memory_id,
793                    ir::StoreKind::I32_8 { atomic: false },
794                    ir::MemArg {
795                        offset: 0,
796                        align: 0,
797                    },
798                );
799
800            func_body.return_();
801
802            Ok(())
803        })?;
804
805        let ex_name = if let Some(with_info) = with_info {
806            format!(
807                "__wasip1_vfs_flag_{name}_memory_with_{}",
808                with_info.to_string()
809            )
810        } else {
811            format!("__wasip1_vfs_flag_{name}_memory")
812        };
813        self.exports.add(&ex_name, id);
814
815        Ok(())
816    }
817
818    fn get_global_anchor(&mut self, name: impl AsRef<str>) -> eyre::Result<Box<[GlobalId]>> {
819        let name = name.as_ref();
820        let anchor_name = format!("__wasip1_vfs_flag_{name}_global");
821
822        let anchor_func_id = anchor_name.get_fid(&self.exports)?;
823
824        self.exports.erase(anchor_func_id)?;
825
826        let anchor_body = &self.funcs.get(anchor_func_id).kind;
827        if let FunctionKind::Local(local_func) = anchor_body {
828            let entry_id = local_func.entry_block();
829            let func_body = local_func.block(entry_id);
830            let global_ids = func_body
831                .iter()
832                .map(|(block, _)| block)
833                .filter_map(|block| match block {
834                    ir::Instr::GlobalSet(ir::GlobalSet { global, .. })
835                    | ir::Instr::GlobalGet(ir::GlobalGet { global, .. }) => Some(*global),
836                    _ => None,
837                })
838                .collect::<Box<_>>();
839
840            Ok(global_ids)
841        } else {
842            Err(eyre::eyre!(
843                "anchor (local function) {anchor_name} not found",
844            ))
845        }
846    }
847
848    fn create_global_anchor(&mut self, name: impl AsRef<str>) -> eyre::Result<()> {
849        let name = name.as_ref();
850
851        let global_ids = self
852            .globals
853            .iter()
854            .map(|global| (global.id(), global.ty, global.mutable))
855            .collect::<Vec<_>>();
856
857        let results = global_ids
858            .iter()
859            .filter(|(_, _, mutable)| !*mutable)
860            .map(|(_, ty, _)| ty)
861            .cloned()
862            .collect::<Vec<_>>();
863
864        let id = self.add_func(&[], &results, |builder, _| {
865            let mut func_body = builder.func_body();
866
867            for (id, ty, mutable) in global_ids.iter() {
868                if *mutable {
869                    func_body
870                        .const_(
871                            ty.normal()
872                                .wrap_err_with(|| eyre::eyre!("Failed to get global type"))?,
873                        )
874                        .global_set(*id);
875                } else {
876                    func_body.global_get(*id);
877                }
878            }
879
880            func_body.return_();
881
882            Ok(())
883        })?;
884
885        self.exports
886            .add(&format!("__wasip1_vfs_flag_{name}_global"), id);
887
888        Ok(())
889    }
890
891    fn get_using_func<A>(
892        &self,
893        as_fn: impl WalrusFID<A>,
894        allow_call_indirect: bool,
895    ) -> eyre::Result<Vec<(FunctionId, InstrSeqId, usize)>> {
896        let fid = as_fn.get_fid(self)?;
897
898        self.funcs
899            .iter_local()
900            .map(|(id, func)| {
901                func.read(|instr, place| {
902                    use walrus::ir::*;
903                    match instr {
904                        Instr::Call(Call { func }) | Instr::ReturnCall(ReturnCall { func })
905                            if fid == *func =>
906                        {
907                            Ok(Some((id, place)))
908                        }
909                        Instr::CallIndirect(CallIndirect { table: _, ty: _ })
910                            if !allow_call_indirect =>
911                        {
912                            eyre::bail!("call_indirect is not supported in get_using_func");
913                        }
914                        _ => Ok(None),
915                    }
916                })
917                .and_then(|v| {
918                    v.into_iter()
919                        .filter_map_ok(|v| v)
920                        .map_ok(|(a, (b, c))| (a, c, b))
921                        .collect::<eyre::Result<Vec<_>>>()
922                })
923            })
924            .flatten_ok()
925            .collect::<eyre::Result<Vec<_>>>()
926    }
927
928    fn renew_id_on_table<A, B>(
929        &mut self,
930        old: impl WalrusFID<A>,
931        new: impl WalrusFID<B>,
932    ) -> eyre::Result<()>
933    where
934        Self: Sized,
935    {
936        let old_id = old.get_fid(self)?;
937        let new_id = new.get_fid(self)?;
938
939        self.check_function_type(old_id, new_id)
940            .wrap_err("Function types do not match on renew id on table")?;
941
942        for table in self.tables.iter_mut() {
943            for elem in &table.elem_segments {
944                let elem = self.elements.get_mut(*elem);
945                if let walrus::ElementKind::Active {
946                    table: table_id, ..
947                } = elem.kind
948                {
949                    if table_id != table.id() {
950                        unreachable!();
951                    }
952                } else {
953                    unreachable!();
954                }
955                match &mut elem.items {
956                    walrus::ElementItems::Functions(ids) => {
957                        ids.iter_mut().for_each(|id| {
958                            if *id == old_id {
959                                log::info!(
960                                    "Rewriting function id on table. Old: {:?}, New: {:?}",
961                                    old_id,
962                                    new_id
963                                );
964                                *id = new_id;
965                            }
966                        });
967                    }
968                    walrus::ElementItems::Expressions(..) => unimplemented!(),
969                }
970            }
971        }
972
973        Ok(())
974    }
975
976    fn fid_pos_on_table<A>(&self, fid: impl WalrusFID<A>) -> eyre::Result<Box<[(TableId, usize)]>> {
977        let fid = fid.get_fid(self)?;
978
979        let mut positions = vec![];
980        for table in self.tables.iter() {
981            for elem in &table.elem_segments {
982                let elem = self.elements.get(*elem);
983                if let walrus::ElementKind::Active {
984                    table: table_id, ..
985                } = elem.kind
986                {
987                    if table_id != table.id() {
988                        unreachable!();
989                    }
990                } else {
991                    unreachable!();
992                }
993                match &elem.items {
994                    walrus::ElementItems::Functions(ids) => {
995                        ids.iter().copied().enumerate().for_each(|(i, id)| {
996                            if id == fid {
997                                positions.push((table.id(), i));
998                            }
999                        });
1000                    }
1001                    walrus::ElementItems::Expressions(..) => unimplemented!(),
1002                }
1003            }
1004        }
1005        Ok(positions.into_boxed_slice())
1006    }
1007
1008    fn renew_call_fn<A, B>(
1009        &mut self,
1010        old: impl WalrusFID<A>,
1011        new: impl WalrusFID<B>,
1012    ) -> eyre::Result<()>
1013    where
1014        Self: Sized,
1015    {
1016        let old_id = old.get_fid(self)?;
1017        let new_id = new.get_fid(self)?;
1018
1019        for (id, _, _) in self
1020            .get_using_func(old_id, true)
1021            .wrap_err("Failed to get using func")?
1022        {
1023            self.funcs
1024                .rewrite(
1025                    |instr, _| {
1026                        if let walrus::ir::Instr::Call(call) = instr {
1027                            if call.func == old_id {
1028                                call.func = new_id;
1029                            }
1030                        }
1031                    },
1032                    id,
1033                )
1034                .wrap_err("Failed to renew function call")?;
1035        }
1036
1037        self.renew_id_on_table(old_id, new_id)?;
1038
1039        // if old function is imported
1040        if let walrus::FunctionKind::Import(import) = &self.funcs.get(old_id).kind {
1041            self.imports.delete(import.import);
1042        }
1043        // renew export
1044        self.exports
1045            .iter_mut()
1046            .filter(|export| match export.item {
1047                walrus::ExportItem::Function(f) if f == old_id => true,
1048                _ => false,
1049            })
1050            .for_each(|export| {
1051                export.item = walrus::ExportItem::Function(new_id);
1052            });
1053        self.funcs.delete(old_id);
1054
1055        Ok(())
1056    }
1057
1058    fn gen_new_function(
1059        &mut self,
1060        params: &[ValType],
1061        results: &[ValType],
1062        fn_: impl FnOnce(&mut FunctionBuilder, &Vec<LocalId>) -> eyre::Result<()>,
1063    ) -> eyre::Result<FunctionId>
1064    where
1065        Self: Sized,
1066    {
1067        let args = params
1068            .iter()
1069            .map(|ty| self.locals.add(*ty))
1070            .collect::<Vec<_>>();
1071
1072        let mut func = FunctionBuilder::new(&mut self.types, &params, &results);
1073
1074        fn_(&mut func, &args)?;
1075
1076        Ok(func.finish(args, &mut self.funcs))
1077    }
1078
1079    fn check_function_type<A, B>(
1080        &self,
1081        before: impl WalrusFID<A>,
1082        after: impl WalrusFID<B>,
1083    ) -> eyre::Result<()>
1084    where
1085        Self: Sized,
1086    {
1087        let before = before.get_fid(self)?;
1088        let after = after.get_fid(self)?;
1089
1090        let a_ty = self.funcs.get(before).ty();
1091        let a_ty_params = self.types.get(a_ty).params();
1092        let a_ty_results = self.types.get(a_ty).results();
1093
1094        let b_ty = self.funcs.get(after).ty();
1095        let b_ty_params = self.types.get(b_ty).params();
1096        let b_ty_results = self.types.get(b_ty).results();
1097
1098        if a_ty_params != b_ty_params || a_ty_results != b_ty_results {
1099            eyre::bail!(
1100                "Function types do not match. Before: {a_ty_params:?} -> {a_ty_results:?}, After: {b_ty_params:?} -> {b_ty_results:?}"
1101            );
1102        }
1103
1104        Ok(())
1105    }
1106
1107    // Insert a specific function into every call_indirect within all functions.
1108    // The type of the received function is fn (table_id, pos);
1109    fn debug_call_indirect<A>(&mut self, id: impl WalrusFID<A>) -> eyre::Result<()>
1110    where
1111        Self: Sized,
1112    {
1113        let id = id.get_fid(self)?;
1114
1115        // check id type
1116        if self.types.get(self.funcs.get(id).ty()).params() != [ValType::I32, ValType::I32]
1117            || self.types.get(self.funcs.get(id).ty()).results() != []
1118        {
1119            eyre::bail!("Function type must be (i32, i32) -> ()");
1120        }
1121
1122        let ids = self.funcs.find_children_with(id, false)?;
1123
1124        let tables = self
1125            .funcs
1126            .iter_local()
1127            .filter(|(fid, _)| !ids.contains(fid))
1128            .map(|(fid, fn_)| {
1129                fn_.read(|instr, pos| {
1130                    if let walrus::ir::Instr::CallIndirect(call) = instr {
1131                        Some((call.table, (fid, pos)))
1132                    } else if let walrus::ir::Instr::ReturnCallIndirect(..) = instr {
1133                        unimplemented!("return_call_indirect is not supported yet")
1134                    } else {
1135                        None
1136                    }
1137                })
1138            })
1139            .flatten_ok()
1140            .filter_map_ok(|x| x)
1141            .collect::<eyre::Result<Vec<_>>>()?;
1142
1143        let table_fns = tables
1144            .iter()
1145            .map(|(table, _)| *table)
1146            .collect::<std::collections::HashSet<_>>()
1147            .into_iter()
1148            .map(|table| {
1149                // As if nothing had happened, it passes the value again.
1150                let middle_fn_id =
1151                    self.add_func(&[ValType::I32], &[ValType::I32], |builder, args| {
1152                        builder
1153                            .func_body()
1154                            .i32_const(table.index() as i32)
1155                            .local_get(args[0])
1156                            .call(id)
1157                            .local_get(args[0])
1158                            .return_();
1159                        Ok(())
1160                    })?;
1161
1162                Ok((table, middle_fn_id))
1163            })
1164            .collect::<eyre::Result<std::collections::HashMap<_, _>>>()?;
1165
1166        for (tid, (fid, (pos, seq_id))) in tables
1167            .into_iter()
1168            .sorted_by(
1169                |(_, (fid_a, (pos_a, seq_id_a))), (_, (fid_b, (pos_b, seq_id_b)))| match fid_a
1170                    .cmp(&fid_b)
1171                {
1172                    std::cmp::Ordering::Equal => match seq_id_a.cmp(&seq_id_b) {
1173                        std::cmp::Ordering::Equal => pos_a.cmp(&pos_b),
1174                        other => other,
1175                    },
1176                    other => other,
1177                },
1178            )
1179            .rev()
1180        {
1181            match self.funcs.get_mut(fid).kind {
1182                FunctionKind::Local(ref mut local_func) => {
1183                    if let Some(walrus::ir::Instr::CallIndirect(walrus::ir::CallIndirect {
1184                        table,
1185                        ..
1186                    })) = local_func
1187                        .builder_mut()
1188                        .instr_seq(seq_id)
1189                        .instrs()
1190                        .get(pos)
1191                        .map(|(instr, _)| instr)
1192                    {
1193                        if *table != tid {
1194                            eyre::bail!("Table id mismatch");
1195                        }
1196                    } else {
1197                        eyre::bail!("Instruction at position is not call_indirect");
1198                    }
1199                    local_func
1200                        .builder_mut()
1201                        .instr_seq(seq_id)
1202                        .call_at(pos, table_fns[&tid]);
1203                }
1204                _ => unreachable!(),
1205            }
1206        }
1207
1208        Ok(())
1209    }
1210
1211    fn gen_inspect_with_finalize<const N: usize, A, B>(
1212        &mut self,
1213        inspector: Option<impl WalrusFID<A>>,
1214        finalize: Option<impl WalrusFID<B>>,
1215        params: &[ValType],
1216        results: &[ValType],
1217        exclude: &[impl Borrow<FunctionId>],
1218        mut filter: impl FnMut(&ir::Instr) -> Option<[i32; N]>,
1219    ) -> eyre::Result<()>
1220    where
1221        Self: Sized,
1222    {
1223        let inspector: Option<FunctionId> = inspector.map(|id| id.get_fid(self)).transpose()?;
1224        let finalize: Option<FunctionId> = finalize.map(|id| id.get_fid(self)).transpose()?;
1225
1226        // check inspector type
1227        let check_inspector = |params: &[ValType], name: &str, fid| {
1228            if self.types.get(self.funcs.get(fid).ty()).params()
1229                != params
1230                    .iter()
1231                    .cloned()
1232                    .chain(std::iter::repeat(ValType::I32).take(N))
1233                    .collect::<Vec<_>>()
1234            {
1235                eyre::bail!("{name} function type must be ({params:?}) -> ()",);
1236            }
1237
1238            Ok(())
1239        };
1240
1241        if let Some(inspector) = inspector {
1242            check_inspector(params, "Inspector", inspector)?;
1243        }
1244
1245        if let Some(finalize) = finalize {
1246            check_inspector(results, "Finalize", finalize)?;
1247        }
1248
1249        let exclude = [inspector, finalize]
1250            .iter()
1251            .filter_map(|id| *id)
1252            .map(|f| self.funcs.find_children_with(f, false))
1253            .flatten_ok()
1254            .chain(exclude.iter().map(|id| Ok(*id.borrow())))
1255            .collect::<eyre::Result<std::collections::HashSet<_>>>()
1256            .wrap_err("Failed to find exclude functions")?;
1257
1258        let instrs = self
1259            .funcs
1260            .iter_local()
1261            .filter(|(fid, _)| !exclude.contains(fid))
1262            .map(|(fid, fn_)| {
1263                fn_.read(|instr, pos| {
1264                    if let Some(ret) = filter(instr) {
1265                        Some((ret, fid, pos))
1266                    } else {
1267                        None
1268                    }
1269                })
1270            })
1271            .flatten_ok()
1272            .filter_map_ok(|x| x)
1273            .collect::<eyre::Result<Vec<_>>>()?;
1274
1275        let instrs_set = instrs
1276            .iter()
1277            .map(|(ret, _, _)| *ret)
1278            .collect::<std::collections::HashSet<_>>();
1279
1280        let mut group_by_fns = |fns: Option<FunctionId>, params: &[ValType]| {
1281            fns.map(|fns| {
1282                instrs_set
1283                    .iter()
1284                    .map(|ret| {
1285                        let middle_fn_id = self.add_func(&params, &params, |builder, args| {
1286                            let mut func_body = builder.func_body();
1287                            for ret in ret {
1288                                func_body.i32_const(*ret);
1289                            }
1290                            for arg in args {
1291                                func_body.local_get(*arg);
1292                            }
1293                            func_body.call(fns);
1294                            for arg in args {
1295                                func_body.local_get(*arg);
1296                            }
1297                            func_body.return_();
1298                            Ok(())
1299                        })?;
1300                        Ok((ret, middle_fn_id))
1301                    })
1302                    .collect::<eyre::Result<std::collections::HashMap<_, _>>>()
1303            })
1304            .transpose()
1305        };
1306
1307        let group_inspector_fns = group_by_fns(inspector, params)?;
1308        let group_finalize_fns = group_by_fns(finalize, results)?;
1309
1310        let ids = [inspector, finalize]
1311            .iter()
1312            .filter_map(|id| *id)
1313            .map(|fid| self.funcs.find_children_with(fid, false))
1314            .flatten_ok()
1315            .collect::<eyre::Result<std::collections::HashSet<_>>>()
1316            .wrap_err("Failed to find exclude functions")?;
1317
1318        for (ret, fid, (pos, seq_id)) in instrs
1319            .into_iter()
1320            .sorted_by(
1321                |(_, fid_a, (pos_a, seq_id_a)), (_, fid_b, (pos_b, seq_id_b))| match fid_a
1322                    .cmp(&fid_b)
1323                {
1324                    std::cmp::Ordering::Equal => match seq_id_a.cmp(&seq_id_b) {
1325                        std::cmp::Ordering::Equal => pos_a.cmp(&pos_b),
1326                        other => other,
1327                    },
1328                    other => other,
1329                },
1330            )
1331            .rev()
1332        {
1333            if ids.contains(&fid) {
1334                continue;
1335            }
1336
1337            match self.funcs.get_mut(fid).kind {
1338                FunctionKind::Local(ref mut local_func) => {
1339                    let mut instr_seq = local_func.builder_mut().instr_seq(seq_id);
1340                    let instr = instr_seq
1341                        .instrs()
1342                        .get(pos)
1343                        .map(|(instr, _)| instr)
1344                        .ok_or_else(|| eyre::eyre!("Instruction at position not found"))?;
1345
1346                    if filter(instr).is_none() {
1347                        eyre::bail!("Instruction at position does not match filter");
1348                    }
1349
1350                    if let Some(_) = finalize {
1351                        instr_seq.call_at(pos + 1, group_finalize_fns.as_ref().unwrap()[&ret]);
1352                    }
1353                    if let Some(_) = inspector {
1354                        instr_seq.call_at(pos, group_inspector_fns.as_ref().unwrap()[&ret]);
1355                    }
1356                }
1357                _ => unreachable!(),
1358            }
1359        }
1360
1361        Ok(())
1362    }
1363
1364    fn assert_i32_const(
1365        &mut self,
1366        val: i32,
1367    ) -> eyre::Result<impl FnMut(&mut walrus::InstrSeqBuilder) -> eyre::Result<()> + 'static> {
1368        use walrus::ValType::I32;
1369        let fid = self.add_func(&[I32], &[I32], |builder, args| {
1370            builder
1371                .func_body()
1372                .i32_const(val)
1373                .local_get(args[0])
1374                .binop(walrus::ir::BinaryOp::I32Eq)
1375                .if_else(
1376                    None,
1377                    |cons| {
1378                        cons.local_get(args[0]);
1379                        cons.return_();
1380                    },
1381                    |els| {
1382                        els.unreachable();
1383                    },
1384                );
1385            Ok(())
1386        })?;
1387
1388        Ok(
1389            move |func_body: &mut walrus::InstrSeqBuilder| -> eyre::Result<()> {
1390                func_body.call(fid);
1391                Ok(())
1392            },
1393        )
1394    }
1395
1396    fn load(path: impl AsRef<Path>, dwarf: bool) -> eyre::Result<Self>
1397    where
1398        Self: Sized,
1399    {
1400        let mut config = walrus::ModuleConfig::new();
1401        config.generate_dwarf(dwarf);
1402        let module = walrus::Module::from_file_with_config(path.as_ref(), &config)
1403            .to_eyre()
1404            .wrap_err_with(|| {
1405                eyre::eyre!("Failed to load Wasm file: {}", path.as_ref().display())
1406            })?;
1407        Ok(module)
1408    }
1409
1410    fn connect_func_alt<A, B>(
1411        &mut self,
1412        import: impl WalrusFID<A>,
1413        export: impl WalrusFID<B>,
1414    ) -> eyre::Result<()> {
1415        let err_msg = || {
1416            format!(
1417                "Function types do not match on connect func alt: {} -> {}",
1418                import.as_str(),
1419                export.as_str()
1420            )
1421        };
1422        let export = export
1423            .get_fid(&self.exports)
1424            .wrap_err("Export function not found")
1425            .wrap_err_with(err_msg)?;
1426
1427        self.renew_call_fn(import, export)
1428            .wrap_err("Failed to renew call function")
1429            .wrap_err_with(err_msg)?;
1430
1431        Ok(())
1432    }
1433
1434    fn copy_func<A>(&mut self, from: impl WalrusFID<A>) -> eyre::Result<walrus::FunctionId>
1435    where
1436        Self: Sized,
1437    {
1438        let from = from.get_fid(self)?;
1439
1440        let func_base = self.funcs.get(from);
1441        let ty_base = func_base.ty();
1442        let types_base = self.types.get(ty_base);
1443        let params_base = types_base.params().to_vec();
1444        let results_base = types_base.results().to_vec();
1445        let local_func_base = func_base.kind.unwrap_local();
1446
1447        let local_ids_base = local_func_base
1448            .args
1449            .iter()
1450            .copied()
1451            .chain(
1452                local_func_base
1453                    .read(|instr, _| match instr {
1454                        walrus::ir::Instr::LocalGet(walrus::ir::LocalGet { local }) => Some(*local),
1455                        walrus::ir::Instr::LocalSet(walrus::ir::LocalSet { local }) => Some(*local),
1456                        walrus::ir::Instr::LocalTee(walrus::ir::LocalTee { local }) => Some(*local),
1457                        _ => None,
1458                    })?
1459                    .into_iter()
1460                    .filter_map(|x| x)
1461                    .filter(|id| !local_func_base.args.contains(id))
1462                    .collect::<std::collections::HashSet<_>>()
1463                    .into_iter(),
1464            )
1465            .collect::<Vec<_>>();
1466
1467        let locals_base = local_ids_base
1468            .iter()
1469            .map(|ty| self.locals.get(*ty).ty())
1470            .collect::<Vec<_>>();
1471
1472        let entry_base = local_func_base.entry_block();
1473        let mut instrs_base = local_func_base
1474            .read(|instr, (pos, id)| (pos, id, instr.clone()))?
1475            .into_iter()
1476            .into_group_map_by(|(_, id, _)| *id)
1477            .into_iter()
1478            .map(|(id, vec)| {
1479                let instrs = vec
1480                    .into_iter()
1481                    .map(|(pos, _, instr)| (pos, instr))
1482                    .sorted_by_key(|(pos, _)| *pos)
1483                    .enumerate()
1484                    .inspect(|(i, (pos, _))| assert_eq!(i, pos))
1485                    .map(|(_, (_, instr))| instr)
1486                    .collect::<Vec<_>>();
1487
1488                (id, instrs)
1489            })
1490            .collect::<HashMap<_, _>>();
1491
1492        let mut builder = FunctionBuilder::new(&mut self.types, &params_base, &results_base);
1493
1494        let new_locals = locals_base
1495            .iter()
1496            .map(|ty| self.locals.add(*ty))
1497            .collect::<Vec<_>>();
1498
1499        let new_args = new_locals
1500            .iter()
1501            .copied()
1502            .take(local_func_base.args.len())
1503            .collect::<Vec<_>>();
1504
1505        let local_map = local_ids_base
1506            .iter()
1507            .zip(new_locals.iter())
1508            .map(|(a, b)| (*a, *b))
1509            .collect::<HashMap<_, _>>();
1510
1511        let new_body_id = builder.func_body_id();
1512
1513        let mut seq_map = instrs_base
1514            .keys()
1515            .filter(|id| **id != entry_base)
1516            .map(|id| {
1517                (
1518                    *id,
1519                    builder
1520                        .dangling_instr_seq(local_func_base.block(*id).ty)
1521                        .id(),
1522                )
1523            })
1524            .chain(std::iter::once((entry_base, new_body_id)))
1525            .collect::<HashMap<_, _>>();
1526
1527        use walrus::ir::*;
1528
1529        for (seq, instrs_base) in instrs_base.drain() {
1530            instrs_base
1531                .iter()
1532                .map(|instr| match instr {
1533                    Instr::Block(Block { seq }) => {
1534                        vec![seq]
1535                    }
1536                    Instr::Loop(Loop { seq }) => {
1537                        vec![seq]
1538                    }
1539                    Instr::Br(Br { block }) => {
1540                        vec![block]
1541                    }
1542                    Instr::BrIf(BrIf { block }) => {
1543                        vec![block]
1544                    }
1545                    Instr::IfElse(IfElse {
1546                        alternative,
1547                        consequent,
1548                    }) => {
1549                        vec![alternative, consequent]
1550                    }
1551                    Instr::BrTable(BrTable { blocks, default }) => blocks
1552                        .iter()
1553                        .chain(std::iter::once(default))
1554                        .collect::<Vec<_>>(),
1555                    _ => Vec::new(),
1556                })
1557                .flatten()
1558                .for_each(|b| {
1559                    if !seq_map.contains_key(&b) {
1560                        let blank_seq = builder
1561                            .dangling_instr_seq(local_func_base.block(*b).ty)
1562                            .id();
1563                        seq_map.insert(*b, blank_seq);
1564                    }
1565                });
1566
1567            let mut now_seq = builder.instr_seq(seq_map[&seq]);
1568
1569            for instr in instrs_base {
1570                match instr {
1571                    Instr::Block(Block { seq }) => {
1572                        now_seq.instr(Instr::Block(Block { seq: seq_map[&seq] }));
1573                    }
1574                    Instr::Loop(Loop { seq }) => {
1575                        now_seq.instr(Instr::Loop(Loop { seq: seq_map[&seq] }));
1576                    }
1577                    Instr::Br(Br { block }) => {
1578                        now_seq.instr(Instr::Br(Br {
1579                            block: seq_map[&block],
1580                        }));
1581                    }
1582                    Instr::BrIf(BrIf { block }) => {
1583                        now_seq.instr(Instr::BrIf(BrIf {
1584                            block: seq_map[&block],
1585                        }));
1586                    }
1587                    Instr::IfElse(IfElse {
1588                        consequent,
1589                        alternative,
1590                    }) => {
1591                        now_seq.instr(Instr::IfElse(IfElse {
1592                            consequent: seq_map[&consequent],
1593                            alternative: seq_map[&alternative],
1594                        }));
1595                    }
1596                    Instr::BrTable(BrTable { blocks, default }) => {
1597                        now_seq.instr(Instr::BrTable(BrTable {
1598                            blocks: blocks
1599                                .iter()
1600                                .map(|b| seq_map[b])
1601                                .collect::<Vec<_>>()
1602                                .into_boxed_slice(),
1603                            default: seq_map[&default],
1604                        }));
1605                    }
1606                    Instr::LocalGet(LocalGet { local }) => {
1607                        now_seq.instr(Instr::LocalGet(LocalGet {
1608                            local: local_map[&local],
1609                        }));
1610                    }
1611                    Instr::LocalSet(LocalSet { local }) => {
1612                        now_seq.instr(Instr::LocalSet(LocalSet {
1613                            local: local_map[&local],
1614                        }));
1615                    }
1616                    Instr::LocalTee(LocalTee { local }) => {
1617                        now_seq.instr(Instr::LocalTee(LocalTee {
1618                            local: local_map[&local],
1619                        }));
1620                    }
1621                    _ => {
1622                        now_seq.instr(instr);
1623                    }
1624                }
1625            }
1626        }
1627
1628        Ok(builder.finish(new_args, &mut self.funcs))
1629    }
1630
1631    fn nested_copy_func<A>(
1632        &mut self,
1633        from: impl WalrusFID<A>,
1634        exclude: &[impl Borrow<FunctionId>],
1635        allow_import_func: bool,
1636        allow_call_indirect: bool,
1637    ) -> eyre::Result<walrus::FunctionId>
1638    where
1639        Self: Sized,
1640    {
1641        let from = from.get_fid(self)?;
1642        let exclude = exclude.iter().map(|e| *e.borrow()).collect::<Vec<_>>();
1643
1644        let mut fid_map: HashMap<FunctionId, FunctionId> = HashMap::new();
1645
1646        let fids = self
1647            .funcs
1648            .find_children_with(from, allow_call_indirect)
1649            .wrap_err("Failed to find children functions")?;
1650
1651        for fid in fids {
1652            if exclude.contains(&fid) {
1653                fid_map.insert(fid, fid);
1654                continue;
1655            }
1656            if fid_map.contains_key(&fid) {
1657                unreachable!();
1658            }
1659
1660            let func = self.funcs.get(fid);
1661            match &func.kind {
1662                FunctionKind::Import(import) => {
1663                    if !allow_import_func {
1664                        let import = self.imports.get(import.import);
1665                        eyre::bail!("Import function found: {:?}", import);
1666                    }
1667                    fid_map.insert(fid, fid);
1668                }
1669                FunctionKind::Local(_) => {
1670                    let new_fid = self.copy_func(fid)?;
1671                    fid_map.insert(fid, new_fid);
1672                }
1673                _ => {
1674                    eyre::bail!("Unknown function kind: {:?}", func.kind);
1675                }
1676            }
1677        }
1678
1679        for (old_fid, new_fid) in fid_map.iter() {
1680            // If included in the exclude list, it is normally ignored; however, in its own case, it is rewritten.
1681            if (old_fid == new_fid || exclude.contains(new_fid)) && *new_fid != from {
1682                continue;
1683            }
1684
1685            let local = self.funcs.get_mut(*new_fid).kind.unwrap_local_mut();
1686            local
1687                .builder_mut()
1688                .func_body()
1689                .rewrite(|instr, _| {
1690                    use walrus::ir::*;
1691                    match instr {
1692                        Instr::Call(Call { func, .. })
1693                        | Instr::ReturnCall(ReturnCall { func, .. }) => {
1694                            if let Some(new_func) = fid_map.get(func) {
1695                                *func = *new_func;
1696                            }
1697                        }
1698                        Instr::CallIndirect(call) if !allow_call_indirect => {
1699                            eyre::bail!("Call indirect found: {call:?} in nested copy");
1700                        }
1701                        Instr::ReturnCallIndirect(call) if !allow_call_indirect => {
1702                            eyre::bail!("Return call indirect found: {call:?} in nested copy");
1703                        }
1704                        _ => {}
1705                    }
1706                    Ok(())
1707                })
1708                .wrap_err("Failed to renew function call")?;
1709        }
1710
1711        Ok(fid_map[&from])
1712    }
1713
1714    fn renew_export<A, B>(
1715        &mut self,
1716        old: impl WalrusFID<A>,
1717        new: impl WalrusFID<B>,
1718    ) -> eyre::Result<()>
1719    where
1720        Self: Sized,
1721    {
1722        let old_id = old.get_fid(self)?;
1723        let new_id = new.get_fid(self)?;
1724
1725        self.check_function_type(old_id, new_id)
1726            .wrap_err("Function types do not match on renew export")?;
1727
1728        self.exports
1729            .iter_mut()
1730            .filter(|export| matches!(export.item, walrus::ExportItem::Function(f) if f == old_id))
1731            .for_each(|export| {
1732                export.item = walrus::ExportItem::Function(new_id);
1733            });
1734
1735        Ok(())
1736    }
1737
1738    fn get_memory_type(&mut self, is_remove: bool) -> eyre::Result<TargetMemoryType> {
1739        let (target_memory_type, eid) = self
1740            .exports
1741            .iter()
1742            .find(|e| e.name == "__wasip1_vfs_flag_vfs_multi_memory")
1743            .map(|e| Ok((TargetMemoryType::Multi, e.id())))
1744            .unwrap_or(
1745                self.exports
1746                    .iter()
1747                    .find(|e| e.name == "__wasip1_vfs_flag_vfs_single_memory")
1748                    .map(|e| Ok((TargetMemoryType::Single, e.id())))
1749                    .unwrap_or(Err(eyre::eyre!("No target memory type found"))),
1750            )?;
1751
1752        if is_remove {
1753            self.exports.delete(eid);
1754        }
1755
1756        Ok(target_memory_type)
1757    }
1758
1759    fn save_info(
1760        &mut self,
1761        key: impl AsRef<str>,
1762        info: impl ToString + FromStr,
1763    ) -> eyre::Result<()> {
1764        let blank_fn = self.add_func(&[], &[], |builder, _| {
1765            builder.func_body().unreachable();
1766            Ok(())
1767        })?;
1768
1769        let name = format!(
1770            "__wasip1_vfs_flag_info_{}_{}",
1771            key.as_ref(),
1772            info.to_string()
1773        );
1774
1775        self.exports.add(&name, blank_fn);
1776
1777        Ok(())
1778    }
1779
1780    fn load_info<T: ToString + FromStr>(&mut self, key: impl AsRef<str>) -> eyre::Result<T>
1781    where
1782        <T as std::str::FromStr>::Err: Debug,
1783    {
1784        let name = format!("__wasip1_vfs_flag_info_{}_", key.as_ref());
1785        let export = self
1786            .exports
1787            .iter()
1788            .find(|e| e.name.starts_with(&name))
1789            .ok_or_else(|| eyre::eyre!("No info found"))?;
1790        let info_str = &export.name[name.len()..];
1791        let info = info_str
1792            .parse::<T>()
1793            .map_err(|e| eyre::eyre!("Failed to parse info: {:?}", e))?;
1794
1795        self.exports.delete(export.id());
1796
1797        Ok(info)
1798    }
1799
1800    fn connect_func_alt_with_remove_export<A>(
1801        &mut self,
1802        import: impl WalrusFID<A>,
1803        export: impl AsRef<str>,
1804        is_debug: bool,
1805    ) -> eyre::Result<()> {
1806        let export = export.as_ref();
1807        self.connect_func_alt(import, export)?;
1808        if is_debug {
1809            self.exports
1810                .iter_mut()
1811                .find(|e| e.name == export)
1812                .unwrap()
1813                .name = format!("_____debug_left_{export}");
1814        } else {
1815            self.exports.remove(export).unwrap();
1816        }
1817
1818        Ok(())
1819    }
1820
1821    // fn flatten_tables(&mut self) -> eyre::Result<()> {
1822    //     let table_ids: Vec<_> = self.tables.iter().map(|t| t.id()).collect();
1823    //     if table_ids.len() <= 1 {
1824    //         return Ok(());
1825    //     }
1826
1827    //     log::info!("Flattening {} tables into one...", table_ids.len());
1828
1829    //     let target_table_id = table_ids[0];
1830    //     let mut current_offset = self.tables.get(target_table_id).initial;
1831
1832    //     let mut table_offsets = std::collections::HashMap::new();
1833    //     table_offsets.insert(target_table_id, 0);
1834
1835    //     for &table_id in &table_ids[1..] {
1836    //         let table = self.tables.get(table_id);
1837    //         let table_size = table.initial;
1838    //         let offset = current_offset;
1839    //         table_offsets.insert(table_id, offset);
1840
1841    //         current_offset += table_size;
1842    //     }
1843
1844    //     // 1. Move all element segments to target table
1845    //     let elem_ids: Vec<_> = self.elements.iter().map(|e| e.id()).collect();
1846    //     for eid in elem_ids {
1847    //         let elem = self.elements.get_mut(eid);
1848    //         match &mut elem.kind {
1849    //             walrus::ElementKind::Active { table, offset } => {
1850    //                 if let Some(&off) = table_offsets.get(table) {
1851    //                     if off > 0 {
1852    //                         *table = target_table_id;
1853    //                         // Adjust the offset expression.
1854    //                         // Element segments typically use a single i32.const instruction.
1855    //                         match offset {
1856    //                             walrus::ConstExpr::Value(walrus::ir::Value::I32(val)) => {
1857    //                                 *val += off as i32;
1858    //                             }
1859    //                             _ => eyre::bail!("Unsupported element offset expression type: only i32.const is supported for table flattening"),
1860    //                         }
1861    //                     }
1862    //                 }
1863    //             }
1864    //             _ => {}
1865    //         }
1866    //     }
1867
1868    //     // 2. Update instructions in all functions
1869    //     for func in self.funcs.iter_mut() {
1870    //         if let walrus::FunctionKind::Local(local) = &mut func.kind {
1871    //             let mut stack = vec![local.entry_block()];
1872    //             let mut visited = std::collections::HashSet::new();
1873
1874    //             while let Some(seq_id) = stack.pop() {
1875    //                 if !visited.insert(seq_id) {
1876    //                     continue;
1877    //                 }
1878
1879    //                 // Collect next sequences to visit
1880    //                 {
1881    //                     let seq = local.block(seq_id);
1882    //                     for (instr, _) in &seq.instrs {
1883    //                         match instr {
1884    //                             walrus::ir::Instr::Block(b) => stack.push(b.seq),
1885    //                             walrus::ir::Instr::Loop(l) => stack.push(l.seq),
1886    //                             walrus::ir::Instr::IfElse(if_) => {
1887    //                                 stack.push(if_.consequent);
1888    //                                 stack.push(if_.alternative);
1889    //                             }
1890    //                             _ => {}
1891    //                         }
1892    //                     }
1893    //                 }
1894
1895    //                 // Now modify instructions in the current block
1896    //                 let instrs = &mut local.block_mut(seq_id).instrs;
1897    //                 let mut i = 0;
1898    //                 while i < instrs.len() {
1899    //                     let mut injected = Vec::new();
1900    //                     let loc = instrs[i].1;
1901
1902    //                     match &mut instrs[i].0 {
1903    //                         walrus::ir::Instr::CallIndirect(call) => {
1904    //                             if let Some(&off) = table_offsets.get(&call.table) {
1905    //                                 if off > 0 {
1906    //                                     call.table = target_table_id;
1907    //                                     injected.push((walrus::ir::Instr::Const(walrus::ir::Const { value: walrus::ir::Value::I32(off as i32) }), loc));
1908    //                                     injected.push((walrus::ir::Instr::Binop(walrus::ir::Binop { op: walrus::ir::BinaryOp::I32Add }), loc));
1909    //                                 }
1910    //                             }
1911    //                         }
1912    //                         walrus::ir::Instr::TableGet(table) => {
1913    //                             if let Some(&off) = table_offsets.get(&table.table) {
1914    //                                 if off > 0 {
1915    //                                     table.table = target_table_id;
1916    //                                     injected.push((walrus::ir::Instr::Const(walrus::ir::Const { value: walrus::ir::Value::I32(off as i32) }), loc));
1917    //                                     injected.push((walrus::ir::Instr::Binop(walrus::ir::Binop { op: walrus::ir::BinaryOp::I32Add }), loc));
1918    //                                 }
1919    //                             }
1920    //                         }
1921    //                         _ => {}
1922    //                     }
1923
1924    //                     if !injected.is_empty() {
1925    //                         instrs.splice(i..i, injected);
1926    //                         i += 2;
1927    //                     }
1928    //                     i += 1;
1929    //                 }
1930    //             }
1931    //         }
1932    //     }
1933
1934    //     // 3. Delete other tables
1935    //     for &table_id in &table_ids[1..] {
1936    //         self.tables.delete(table_id);
1937    //     }
1938
1939    //     // 4. Update target table size
1940    //     let target_table = self.tables.get_mut(target_table_id);
1941    //     target_table.initial = current_offset;
1942    //     if let Some(ref mut max) = target_table.maximum {
1943    //         *max = std::cmp::max(*max, current_offset);
1944    //     }
1945
1946    //     Ok(())
1947    // }
1948}
1949
1950impl WalrusUtilFuncs for walrus::ModuleFunctions {
1951    fn find_children(
1952        &self,
1953        fid: impl Borrow<FunctionId>,
1954        allow_call_indirect: bool,
1955    ) -> eyre::Result<Vec<FunctionId>> {
1956        let fid = *fid.borrow();
1957
1958        let mut children = vec![];
1959        let mut stack = vec![fid];
1960        while let Some(fid) = stack.pop() {
1961            match &self.get(fid).kind {
1962                FunctionKind::Local(imported_function) => {
1963                    imported_function
1964                        .read(|instr, _| {
1965                            use walrus::ir::*;
1966                            match instr {
1967                                Instr::Call(Call { func })
1968                                | Instr::ReturnCall(ReturnCall { func, .. }) => {
1969                                    if !children.contains(func) {
1970                                        children.push(*func);
1971                                        stack.push(*func);
1972                                    }
1973                                }
1974                                Instr::CallIndirect(call) if !allow_call_indirect => {
1975                                    eyre::bail!("Call indirect found: {call:?} in find children");
1976                                }
1977                                Instr::ReturnCallIndirect(call) if !allow_call_indirect => {
1978                                    eyre::bail!(
1979                                        "Return call indirect found: {call:?} in find children"
1980                                    );
1981                                }
1982                                _ => {}
1983                            }
1984                            Ok(())
1985                        })?
1986                        .into_iter()
1987                        .collect::<eyre::Result<Vec<_>>>()?;
1988                }
1989                _ => {}
1990            }
1991        }
1992        Ok(children)
1993    }
1994
1995    fn rewrite<T>(
1996        &mut self,
1997        find: impl FnMut(&mut ir::Instr, (usize, InstrSeqId)) -> T,
1998        fid: impl Borrow<FunctionId>,
1999    ) -> eyre::Result<Vec<T>>
2000    where
2001        Self: Sized,
2002    {
2003        let fid = *fid.borrow();
2004
2005        let func = self.get_mut(fid);
2006        if let FunctionKind::Local(local_func) = &mut func.kind {
2007            local_func.builder_mut().func_body().rewrite(find)
2008        } else {
2009            eyre::bail!("Function is not local");
2010        }
2011    }
2012
2013    fn read<T>(
2014        &self,
2015        mut find: impl FnMut(&ir::Instr, (usize, InstrSeqId)) -> T,
2016        fid: impl Borrow<FunctionId>,
2017    ) -> eyre::Result<Vec<T>>
2018    where
2019        Self: Sized,
2020    {
2021        let fid = *fid.borrow();
2022
2023        let func = self.get(fid);
2024        if let FunctionKind::Local(local_func) = &func.kind {
2025            local_func.read(&mut find)
2026        } else {
2027            eyre::bail!("Function is not local");
2028        }
2029    }
2030
2031    fn flat_rewrite<T>(
2032        &mut self,
2033        mut find: impl FnMut(&mut ir::Instr, (usize, InstrSeqId)) -> T,
2034        fid: impl Borrow<FunctionId>,
2035        allow_call_indirect: bool,
2036    ) -> eyre::Result<Vec<T>>
2037    where
2038        Self: Sized,
2039    {
2040        self.find_children_with(fid, allow_call_indirect)?
2041            .into_iter()
2042            .filter(|fid| {
2043                if let walrus::FunctionKind::Local(_) = self.get(*fid).kind {
2044                    true
2045                } else {
2046                    false
2047                }
2048            })
2049            .collect::<Vec<_>>()
2050            .into_iter()
2051            .map(|fid| self.rewrite(&mut find, fid))
2052            .flatten_ok()
2053            .collect()
2054    }
2055
2056    fn flat_read<T>(
2057        &self,
2058        mut find: impl FnMut(&ir::Instr, (usize, InstrSeqId)) -> T,
2059        fid: impl Borrow<FunctionId>,
2060    ) -> eyre::Result<Vec<T>>
2061    where
2062        Self: Sized,
2063    {
2064        self.find_children_with(fid, false)?
2065            .into_iter()
2066            .filter(|fid| {
2067                if let walrus::FunctionKind::Local(_) = self.get(*fid).kind {
2068                    true
2069                } else {
2070                    false
2071                }
2072            })
2073            .map(|fid| self.read(&mut find, fid))
2074            .flatten_ok()
2075            .collect()
2076    }
2077
2078    fn all_read<T>(
2079        &self,
2080        mut find: impl FnMut(&ir::Instr, (usize, InstrSeqId)) -> T,
2081        exclude: &[impl Borrow<FunctionId>],
2082    ) -> eyre::Result<Vec<T>>
2083    where
2084        Self: Sized,
2085    {
2086        let exclude = exclude.iter().map(|e| *e.borrow()).collect::<Vec<_>>();
2087        self.iter_local()
2088            .filter(|(fid, _)| !exclude.contains(fid))
2089            .map(|(fid, _)| self.read(&mut find, fid))
2090            .flatten_ok()
2091            .collect()
2092    }
2093
2094    fn par_flat_read<T: Send>(
2095        &self,
2096        find: impl Fn(&ir::Instr, (usize, InstrSeqId)) -> T + Sync + Send,
2097        fid: impl Borrow<FunctionId>,
2098    ) -> eyre::Result<Vec<T>>
2099    where
2100        Self: Sized,
2101    {
2102        use rayon::prelude::*;
2103        let children = self.find_children_with(fid, false)?;
2104        
2105        let funcs: Vec<&walrus::LocalFunction> = children.iter()
2106            .filter_map(|fid| {
2107                if let walrus::FunctionKind::Local(loc) = &self.get(*fid).kind {
2108                    Some(loc)
2109                } else {
2110                    None
2111                }
2112            })
2113            .collect();
2114            
2115        funcs.into_par_iter()
2116            .map(|func| {
2117                let mut results = vec![];
2118                func.read(&mut |instr: &walrus::ir::Instr, loc: (usize, InstrSeqId)| -> Result<(), eyre::Error> {
2119                    results.push(find(instr, loc));
2120                    Ok(())
2121                }).unwrap();
2122                results
2123            })
2124            .collect::<Vec<Vec<T>>>()
2125            .into_iter()
2126            .flatten()
2127            .map(Ok)
2128            .collect::<eyre::Result<Vec<T>>>()
2129    }
2130
2131    fn all_rewrite<T>(
2132        &mut self,
2133        mut find: impl FnMut(&mut ir::Instr, (usize, InstrSeqId)) -> T,
2134        exclude: &[impl Borrow<FunctionId>],
2135    ) -> eyre::Result<Vec<T>>
2136    where
2137        Self: Sized,
2138    {
2139        let exclude = exclude.iter().map(|e| *e.borrow()).collect::<Vec<_>>();
2140        self.iter_local()
2141            .filter(|(fid, _)| !exclude.contains(fid))
2142            .map(|(fid, _)| fid)
2143            .collect::<Vec<_>>()
2144            .into_iter()
2145            .map(|fid| self.rewrite(&mut find, fid))
2146            .flatten_ok()
2147            .collect()
2148    }
2149
2150    fn par_all_rewrite<T: Send>(
2151        &mut self,
2152        find: impl Fn(&mut ir::Instr, (usize, InstrSeqId)) -> T + Sync + Send,
2153        exclude: &[impl Borrow<FunctionId> + Sync],
2154    ) -> eyre::Result<Vec<T>>
2155    where
2156        Self: Sized,
2157    {
2158        use rayon::prelude::*;
2159        let exclude = exclude.iter().map(|e| *e.borrow()).collect::<Vec<_>>();
2160        
2161        let funcs: Vec<(FunctionId, &mut walrus::LocalFunction)> = self.iter_local_mut()
2162            .filter(|(fid, _)| !exclude.contains(fid))
2163            .collect();
2164            
2165        funcs.into_par_iter()
2166            .map(|(_, func)| {
2167                func.builder_mut().func_body().rewrite(|instr, loc| find(instr, loc))
2168            })
2169            .collect::<eyre::Result<Vec<Vec<T>>>>()
2170            .map(|res| res.into_iter().flatten().collect())
2171    }
2172
2173    fn par_flat_rewrite<T: Send>(
2174        &mut self,
2175        find: impl Fn(&mut ir::Instr, (usize, InstrSeqId)) -> T + Sync + Send,
2176        fid: impl Borrow<FunctionId>,
2177        allow_call_indirect: bool,
2178    ) -> eyre::Result<Vec<T>>
2179    where
2180        Self: Sized,
2181    {
2182        use rayon::prelude::*;
2183        let children = self.find_children_with(fid, allow_call_indirect)?;
2184        
2185        let funcs: Vec<(FunctionId, &mut walrus::LocalFunction)> = self.iter_local_mut()
2186            .filter(|(fid, _)| children.contains(fid))
2187            .collect();
2188            
2189        funcs.into_par_iter()
2190            .map(|(_, func)| {
2191                func.builder_mut().func_body().rewrite(|instr, loc| find(instr, loc))
2192            })
2193            .collect::<eyre::Result<Vec<Vec<T>>>>()
2194            .map(|res| res.into_iter().flatten().collect())
2195    }
2196}
2197
2198/// Extension trait for Camino paths to extract the main module file name.
2199pub trait CaminoUtilModule {
2200    /// Gets the base compact string name without extension and specific postfixes.
2201    fn get_file_main_name(&self) -> Option<CompactString>;
2202}
2203
2204impl CaminoUtilModule for camino::Utf8Path {
2205    fn get_file_main_name(&self) -> Option<CompactString> {
2206        let binding = self.file_name().unwrap().split(".").collect::<Vec<_>>();
2207        let file_name_poss = binding.iter().rev();
2208        let mut file_name = None;
2209        for name in file_name_poss {
2210            if *name == "opt"
2211                || *name == "adjusted"
2212                || *name == "wasm"
2213                || *name == "core"
2214                || *name == "component"
2215            {
2216                continue;
2217            }
2218            file_name = Some(name);
2219            break;
2220        }
2221        let file_name = file_name.map(ToOwned::to_owned).or_else(|| {
2222            self.file_name()
2223                .unwrap()
2224                .split(".")
2225                .next()
2226                .as_ref()
2227                .cloned()
2228        });
2229
2230        file_name.map(CompactString::from)
2231    }
2232}
2233
2234impl CaminoUtilModule for PathBuf {
2235    fn get_file_main_name(&self) -> Option<CompactString> {
2236        camino::Utf8Path::new(self.to_str().unwrap()).get_file_main_name()
2237    }
2238}
2239
2240impl CaminoUtilModule for Path {
2241    fn get_file_main_name(&self) -> Option<CompactString> {
2242        camino::Utf8Path::new(self.to_str().unwrap()).get_file_main_name()
2243    }
2244}
2245
2246/// Utility trait for converting generic or `anyhow` results into `eyre::Result`.
2247pub trait ResultUtil<T> {
2248    /// Converts the result into an `eyre::Result`.
2249    fn to_eyre(self) -> eyre::Result<T>;
2250}
2251
2252// https://github.com/eyre-rs/eyre/issues/31
2253impl<T> ResultUtil<T> for anyhow::Result<T> {
2254    fn to_eyre(self) -> eyre::Result<T> {
2255        self.map_err(|e| {
2256            eyre::eyre!(Box::<dyn std::error::Error + Send + Sync + 'static>::from(
2257                e
2258            ))
2259        })
2260    }
2261}
2262
2263impl<T, I: Iterator> ResultUtil<T> for Result<T, itertools::ExactlyOneError<I>> {
2264    fn to_eyre(self) -> eyre::Result<T> {
2265        self.map_err(|e| eyre::eyre!(e.to_string()))
2266    }
2267}
2268
2269/// Normalization trait for value types (e.g., getting a zeroed-out value).
2270pub trait Normal<T> {
2271    /// Returns the generalized normal or default representation of a type.
2272    fn normal(self) -> eyre::Result<T>;
2273}
2274
2275impl Normal<walrus::ir::Value> for walrus::ValType {
2276    fn normal(self) -> eyre::Result<walrus::ir::Value> {
2277        match self {
2278            walrus::ValType::I32 => Ok(walrus::ir::Value::I32(0)),
2279            walrus::ValType::I64 => Ok(walrus::ir::Value::I64(0)),
2280            walrus::ValType::F32 => Ok(walrus::ir::Value::F32(0.0)),
2281            walrus::ValType::F64 => Ok(walrus::ir::Value::F64(0.0)),
2282            walrus::ValType::V128 => Err(eyre::eyre!("V128 not supported")),
2283            ValType::Ref(_) => Err(eyre::eyre!("Ref not supported")),
2284        }
2285    }
2286}
2287
2288/// Provides unified Function ID resolution for different markers (like tuples of module/name).
2289pub trait WalrusFID<Marker>: Copy {
2290    /// Resolves and retrieves the FunctionId via an assisting context, erroring if not found.
2291    fn get_fid(self, assist: &impl WalrusFIDAssister) -> eyre::Result<FunctionId>;
2292    /// Resolves and retrieves the FunctionId via an assisting context optionally.
2293    fn find_fid(self, assist: &impl WalrusFIDAssister) -> Option<FunctionId>;
2294    /// Formats the identity marker into a standard string representation.
2295    fn as_str(self) -> String;
2296}
2297
2298/// Provides the actual lookup operations for FID resolution.
2299pub trait WalrusFIDAssister {
2300    /// Gets a function ID by its existing ID, failing if it does not exist.
2301    fn get_fid_by_fid(&self, fid: FunctionId) -> eyre::Result<FunctionId>;
2302    /// Attempts to find a function ID by its existing ID.
2303    fn find_fid_by_fid(&self, fid: FunctionId) -> Option<FunctionId>;
2304    /// Gets a function ID by its name, failing if it does not exist.
2305    fn get_fid_by_name(&self, name: &str) -> eyre::Result<FunctionId>;
2306    /// Attempts to find a function ID by its name.
2307    fn find_fid_by_name(&self, name: &str) -> Option<FunctionId>;
2308    /// Gets a function ID by its module and name, failing if it does not exist.
2309    fn get_fid_by_double_name(&self, module: &str, name: &str) -> eyre::Result<FunctionId>;
2310    /// Attempts to find a function ID by its module and name.
2311    fn find_fid_by_double_name(&self, module: &str, name: &str) -> Option<FunctionId>;
2312}
2313
2314/// Marker for looking up FIDs by `FunctionId` values.
2315pub struct FunctionIdMarker;
2316/// Marker for looking up FIDs by string names.
2317pub struct StrMarker;
2318/// Marker for looking up FIDs using `UniqueName` constants.
2319pub struct UniqueMarker;
2320/// Marker for looking up FIDs by a module-name and item-name tuple.
2321pub struct DoubleStrMarker;
2322/// Marker for looking up FIDs using a string module-name and `UniqueName` item.
2323pub struct StrAndUniqueNameMarker;
2324
2325impl<B: Borrow<FunctionId> + Copy> WalrusFID<FunctionIdMarker> for B {
2326    fn as_str(self) -> String {
2327        format!("{:?}", self.borrow())
2328    }
2329
2330    fn get_fid(self, assist: &impl WalrusFIDAssister) -> eyre::Result<FunctionId> {
2331        let fid = *self.borrow();
2332        assist
2333            .get_fid_by_fid(fid)
2334            .wrap_err_with(|| eyre::eyre!("FunctionId {:?} not found in get_fid", fid))
2335    }
2336
2337    fn find_fid(self, assist: &impl WalrusFIDAssister) -> Option<FunctionId> {
2338        let fid = *self.borrow();
2339        assist.find_fid_by_fid(fid)
2340    }
2341}
2342
2343impl<S: AsRef<str> + Copy> WalrusFID<StrMarker> for S {
2344    fn as_str(self) -> String {
2345        self.as_ref().to_string()
2346    }
2347
2348    fn get_fid(self, assist: &impl WalrusFIDAssister) -> eyre::Result<FunctionId> {
2349        let name = self.as_ref();
2350        assist
2351            .get_fid_by_name(name)
2352            .wrap_err_with(|| eyre::eyre!("Function name {name} not found in get_fid"))
2353    }
2354
2355    fn find_fid(self, assist: &impl WalrusFIDAssister) -> Option<FunctionId> {
2356        let name = self.as_ref();
2357        assist.find_fid_by_name(name)
2358    }
2359}
2360
2361impl<U: UniqueNameMarker> WalrusFID<UniqueMarker> for U {
2362    fn as_str(self) -> String {
2363        self.to_string()
2364    }
2365
2366    fn get_fid(self, assist: &impl WalrusFIDAssister) -> eyre::Result<FunctionId> {
2367        let name = self.to_string();
2368        assist
2369            .get_fid_by_name(&name)
2370            .wrap_err_with(|| eyre::eyre!("Function name {name} not found in get_fid"))
2371    }
2372
2373    fn find_fid(self, assist: &impl WalrusFIDAssister) -> Option<FunctionId> {
2374        let name = self.to_string();
2375        assist.find_fid_by_name(&name)
2376    }
2377}
2378
2379impl<S1: AsRef<str> + Copy, S2: AsRef<str> + Copy> WalrusFID<DoubleStrMarker> for (S1, S2) {
2380    fn as_str(self) -> String {
2381        format!("{}.{}", self.0.as_ref(), self.1.as_ref())
2382    }
2383
2384    fn get_fid(self, assist: &impl WalrusFIDAssister) -> eyre::Result<FunctionId> {
2385        let module = self.0.as_ref();
2386        let name = self.1.as_ref();
2387        assist
2388            .get_fid_by_double_name(module, name)
2389            .wrap_err_with(|| eyre::eyre!("Function name {module}.{name} not found in get_fid"))
2390    }
2391
2392    fn find_fid(self, assist: &impl WalrusFIDAssister) -> Option<FunctionId> {
2393        let module = self.0.as_ref();
2394        let name = self.1.as_ref();
2395        assist.find_fid_by_double_name(module, name)
2396    }
2397}
2398
2399impl<S: AsRef<str> + Copy, U: UniqueNameMarker> WalrusFID<StrAndUniqueNameMarker> for (S, U) {
2400    fn as_str(self) -> String {
2401        format!("{}.{}", self.0.as_ref(), self.1.to_string())
2402    }
2403
2404    fn get_fid(self, assist: &impl WalrusFIDAssister) -> eyre::Result<FunctionId> {
2405        let module = self.0.as_ref();
2406        let name = self.1.to_string();
2407        assist
2408            .get_fid_by_double_name(module, &name)
2409            .wrap_err_with(|| eyre::eyre!("Function name {module}.{name} not found in get_fid"))
2410    }
2411
2412    fn find_fid(self, assist: &impl WalrusFIDAssister) -> Option<FunctionId> {
2413        let module = self.0.as_ref();
2414        let name = self.1.to_string();
2415        assist.find_fid_by_double_name(module, &name)
2416    }
2417}
2418
2419impl WalrusFIDAssister for walrus::Module {
2420    fn get_fid_by_fid(&self, fid: FunctionId) -> eyre::Result<FunctionId> {
2421        if self.funcs.iter().any(|f| f.id() == fid) {
2422            Ok(fid)
2423        } else {
2424            eyre::bail!("FunctionId {:?} not found in get_fid_by_fid", fid);
2425        }
2426    }
2427
2428    fn find_fid_by_fid(&self, fid: FunctionId) -> Option<FunctionId> {
2429        if self.funcs.iter().any(|f| f.id() == fid) {
2430            Some(fid)
2431        } else {
2432            None
2433        }
2434    }
2435
2436    fn find_fid_by_name(&self, name: &str) -> Option<FunctionId> {
2437        if let Ok(id) = self.exports.get_fid_by_name(name) {
2438            Some(id)
2439        } else {
2440            self.imports.find_fid_by_name(name)
2441        }
2442    }
2443
2444    fn get_fid_by_name(&self, name: &str) -> eyre::Result<FunctionId> {
2445        if let Ok(id) = self.exports.get_fid_by_name(name) {
2446            Ok(id)
2447        } else {
2448            self.imports.get_fid_by_name(name)
2449        }
2450    }
2451
2452    fn get_fid_by_double_name(&self, module: &str, name: &str) -> eyre::Result<FunctionId> {
2453        self.imports.get_fid_by_double_name(module, name)
2454    }
2455
2456    fn find_fid_by_double_name(&self, module: &str, name: &str) -> Option<FunctionId> {
2457        self.imports.find_fid_by_double_name(module, name)
2458    }
2459}
2460
2461impl WalrusFIDAssister for walrus::ModuleImports {
2462    fn get_fid_by_fid(&self, fid: FunctionId) -> eyre::Result<FunctionId> {
2463        if self.iter().any(|im| match im.kind {
2464            walrus::ImportKind::Function(f) if f == fid => true,
2465            _ => false,
2466        }) {
2467            Ok(fid)
2468        } else {
2469            eyre::bail!("FunctionId {fid:?} not found in get_fid_by_fid");
2470        }
2471    }
2472
2473    fn find_fid_by_fid(&self, fid: FunctionId) -> Option<FunctionId> {
2474        if self.iter().any(|im| match im.kind {
2475            walrus::ImportKind::Function(f) if f == fid => true,
2476            _ => false,
2477        }) {
2478            Some(fid)
2479        } else {
2480            None
2481        }
2482    }
2483
2484    fn find_fid_by_name(&self, name: &str) -> Option<FunctionId> {
2485        self.iter()
2486            .filter_map(|im| match im.kind {
2487                walrus::ImportKind::Function(fid) if im.name == name => Some(fid),
2488                _ => None,
2489            })
2490            .exactly_one()
2491            .ok()
2492    }
2493
2494    fn get_fid_by_name(&self, name: &str) -> eyre::Result<FunctionId> {
2495        self.iter()
2496            .filter_map(|im| match im.kind {
2497                walrus::ImportKind::Function(fid) if im.name == name => Some(fid),
2498                _ => None,
2499            })
2500            .exactly_one()
2501            .to_eyre()
2502            .wrap_err_with(|| {
2503                eyre::eyre!("Multiple or no function name {name} found in get_fid_by_name")
2504            })
2505    }
2506
2507    fn get_fid_by_double_name(&self, module: &str, name: &str) -> eyre::Result<FunctionId> {
2508        self.iter()
2509            .filter_map(|im| match im.kind {
2510                walrus::ImportKind::Function(fid) if im.name == name && im.module == module => {
2511                    Some(fid)
2512                }
2513                _ => None,
2514            })
2515            .exactly_one()
2516            .to_eyre()
2517            .wrap_err_with(|| {
2518                eyre::eyre!("Function name {module}.{name} not found in get_fid_by_double_name")
2519            })
2520    }
2521
2522    fn find_fid_by_double_name(&self, module: &str, name: &str) -> Option<FunctionId> {
2523        self.iter()
2524            .filter_map(|im| match im.kind {
2525                walrus::ImportKind::Function(fid) if im.name == name && im.module == module => {
2526                    Some(fid)
2527                }
2528                _ => None,
2529            })
2530            .exactly_one()
2531            .ok()
2532    }
2533}
2534
2535impl WalrusFIDAssister for ModuleExports {
2536    fn get_fid_by_fid(&self, fid: FunctionId) -> eyre::Result<FunctionId> {
2537        if self.iter().any(|ex| match ex.item {
2538            walrus::ExportItem::Function(f) if f == fid => true,
2539            _ => false,
2540        }) {
2541            Ok(fid)
2542        } else {
2543            eyre::bail!("FunctionId {:?} not found in get_fid_by_fid", fid);
2544        }
2545    }
2546
2547    fn find_fid_by_fid(&self, fid: FunctionId) -> Option<FunctionId> {
2548        if self.iter().any(|ex| match ex.item {
2549            walrus::ExportItem::Function(f) if f == fid => true,
2550            _ => false,
2551        }) {
2552            Some(fid)
2553        } else {
2554            None
2555        }
2556    }
2557
2558    fn find_fid_by_name(&self, name: &str) -> Option<FunctionId> {
2559        self.iter().find_map(|ex| match ex.item {
2560            walrus::ExportItem::Function(fid) if ex.name == name => Some(fid),
2561            _ => None,
2562        })
2563    }
2564
2565    fn get_fid_by_name(&self, name: &str) -> eyre::Result<FunctionId> {
2566        self.iter()
2567            .find_map(|ex| match ex.item {
2568                walrus::ExportItem::Function(fid) if ex.name == name => Some(fid),
2569                _ => None,
2570            })
2571            .wrap_err_with(|| eyre::eyre!("Function name {name} not found in get_fid_by_name"))
2572    }
2573
2574    fn get_fid_by_double_name(&self, _: &str, _: &str) -> eyre::Result<FunctionId> {
2575        panic!("Module name is not stored in exports, cannot get by double name");
2576    }
2577
2578    fn find_fid_by_double_name(&self, _: &str, _: &str) -> Option<FunctionId> {
2579        panic!("Module name is not stored in exports, cannot find by double name");
2580    }
2581}
2582
2583// pub fn init_data_set(buff: &mut walrus::ModuleData, offset: u32, data: &[u8]) -> eyre::Result<()> {
2584//     let data_ids = buff.iter().map(|data| data.id()).collect::<Vec<_>>();
2585
2586//     for id in data_ids {
2587//         let data = buff.get_mut(id);
2588//         if let walrus::DataKind::Active(walrus::ActiveData {
2589//             memory: _,
2590//             offset: walrus::ir::Value::I32(current_offset),
2591//             ..
2592//         }) = &data.kind
2593//         {
2594//             let current_offset = *current_offset as u32;
2595//             if current_offset <= offset && offset < current_offset + data.value.len() as u32 {
2596//                 let start = (offset - current_offset) as usize;
2597//                 let end = std::cmp::min(start + data.value.len(), start + data.len());
2598//                 data.value[start..end].copy_from_slice(&data[..(end - start)]);
2599//                 return Ok(());
2600//             }
2601//         }
2602//     }
2603
2604//     Ok(())
2605// }
2606
2607/// A container holding global statics for tracking Wasm Names.
2608#[derive(Debug)]
2609pub struct WasmNameHolder(&'static [compact_str::CompactString], &'static AtomicUsize);
2610
2611impl WasmNameHolder {
2612    /// Creates a new `WasmNameHolder`, leaking the provided names into static memory.
2613    pub fn new(strings: Box<[compact_str::CompactString]>) -> Self {
2614        let count = Box::leak(Box::new(AtomicUsize::new(0)));
2615
2616        let strings = Box::leak(strings);
2617        WasmNameHolder(strings, count)
2618    }
2619
2620    /// Returns an iterator over the underlying tracked `WasmName` items.
2621    pub fn iter(&self) -> impl Iterator<Item = WasmName> {
2622        self.0.iter().map(|s| WasmName::new(s.as_str(), self.1))
2623    }
2624}
2625
2626impl Drop for WasmNameHolder {
2627    fn drop(&mut self) {
2628        unsafe {
2629            let _ = Box::from_raw(self.0 as *const _ as *mut [compact_str::CompactString]);
2630            let count = self.1.load(std::sync::atomic::Ordering::SeqCst);
2631            let _ = Box::from_raw(self.1 as *const _ as *mut AtomicUsize);
2632            if count != 0 {
2633                panic!(
2634                    "WasmNameHolder dropped while there are still {count} WasmName instances alive"
2635                );
2636            }
2637        }
2638    }
2639}
2640
2641/// Context-aware wrapper for a copied string slice with lifecycle tracking.
2642pub struct WasmName(&'static str, &'static AtomicUsize);
2643impl WasmName {
2644    /// Creates a new tracked `WasmName`.
2645    pub fn new(s: &'static str, counter: &'static AtomicUsize) -> Self {
2646        counter.fetch_add(1, std::sync::atomic::Ordering::SeqCst);
2647        WasmName(s, counter)
2648    }
2649}
2650impl Drop for WasmName {
2651    fn drop(&mut self) {
2652        self.1.fetch_sub(1, std::sync::atomic::Ordering::SeqCst);
2653    }
2654}
2655impl Clone for WasmName {
2656    fn clone(&self) -> Self {
2657        self.1.fetch_add(1, std::sync::atomic::Ordering::SeqCst);
2658        WasmName(self.0, self.1)
2659    }
2660}
2661impl std::hash::Hash for WasmName {
2662    fn hash<H: std::hash::Hasher>(&self, state: &mut H) {
2663        (self.0 as *const str).hash(state);
2664    }
2665}
2666impl PartialEq for WasmName {
2667    fn eq(&self, other: &Self) -> bool {
2668        std::ptr::addr_eq(self.0 as *const _, other.0 as *const _)
2669    }
2670}
2671impl Eq for WasmName {}
2672impl std::fmt::Debug for WasmName {
2673    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
2674        write!(f, "{:?}", self.0)
2675    }
2676}
2677impl std::fmt::Display for WasmName {
2678    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
2679        write!(f, "{}", self.0)
2680    }
2681}
2682impl AsRef<str> for WasmName {
2683    fn as_ref(&self) -> &str {
2684        &self.0
2685    }
2686}
2687impl Borrow<str> for WasmName {
2688    fn borrow(&self) -> &str {
2689        &self.0
2690    }
2691}
2692
2693/// Generates a standardized static import string for WASM component architectures.
2694pub fn gen_component_name(namespace: &str, name: &str) -> String {
2695    format!("[static]{namespace}.{}-import", name.replace("_", "-"))
2696}
2697
2698/// Iterator for enumerating combinations of boolean features.
2699#[derive(Debug)]
2700pub struct BitIterator {
2701    current: FeatureCombinationIteratorInnerBits,
2702    skip: FeatureCombinationIteratorInnerBits, // if this bit is set, skip this iteration
2703    kind: u8,
2704}
2705
2706impl BitIterator {
2707    const MAX_KIND: u8 = core::mem::size_of::<FeatureCombinationIteratorInnerBits>() as u8 * 8;
2708
2709    /// Constructs a new `BitIterator` for a given feature count.
2710    pub fn new(kind: u8) -> Self {
2711        if kind >= Self::MAX_KIND {
2712            panic!("Kind must be between 0 and {}", Self::MAX_KIND - 1);
2713        }
2714
2715        BitIterator {
2716            current: FeatureCombinationIteratorInnerBits::ZERO,
2717            kind,
2718            skip: FeatureCombinationIteratorInnerBits::ZERO,
2719        }
2720    }
2721
2722    /// Retrieves the current bit state representation.
2723    pub fn now(&self) -> FeatureCombinationIteratorInnerBits {
2724        self.current
2725    }
2726
2727    /// Registers a specific bit index to be skipped during iteration.
2728    pub fn register_skip(&mut self, bit: u8) {
2729        if bit >= Self::MAX_KIND {
2730            panic!("Bit must be between 0 and {}", Self::MAX_KIND - 1);
2731        }
2732        self.skip.set(bit as usize, true);
2733    }
2734
2735    /// Unregisters a raw mask of underlying bits from being skipped.
2736    pub fn skip_raw(&mut self, mask: FeatureCombinationIteratorInnerBits) {
2737        self.skip |= mask;
2738    }
2739
2740    /// Unregisters a specific skipped bit index.
2741    pub fn unregister_skip(&mut self, bit: u8) {
2742        if bit >= Self::MAX_KIND {
2743            panic!("Bit must be between 0 and {}", Self::MAX_KIND - 1);
2744        }
2745        self.skip.set(bit as usize, false);
2746    }
2747
2748    /// Unregisters an exact sequence of raw iteration bits.
2749    pub fn unregister_skip_raw(&mut self, mask: FeatureCombinationIteratorInnerBits) {
2750        self.skip &= !mask;
2751    }
2752
2753    /// Clears any registered skip states.
2754    pub fn clear_skip(&mut self) {
2755        self.skip = FeatureCombinationIteratorInnerBits::ZERO;
2756    }
2757}
2758
2759/// Underlying bit representations for the iterator generator.
2760pub mod bits {
2761    use bitvec::prelude::*;
2762    type FeatureCombinationIteratorInnerBitsInner = BitArray<[u64; 2]>;
2763
2764    #[derive(Copy, Clone, Debug)]
2765    /// Strongly typed inner bit representation optimized for combination tracking.
2766    pub struct FeatureCombinationIteratorInnerBits(FeatureCombinationIteratorInnerBitsInner);
2767
2768    impl core::ops::BitAnd for FeatureCombinationIteratorInnerBits {
2769        type Output = Self;
2770
2771        fn bitand(self, rhs: Self) -> Self::Output {
2772            FeatureCombinationIteratorInnerBits { 0: self.0 & rhs.0 }
2773        }
2774    }
2775
2776    impl core::ops::BitAndAssign for FeatureCombinationIteratorInnerBits {
2777        fn bitand_assign(&mut self, rhs: Self) {
2778            self.0 &= rhs.0;
2779        }
2780    }
2781
2782    impl core::ops::BitOr for FeatureCombinationIteratorInnerBits {
2783        type Output = Self;
2784
2785        fn bitor(self, rhs: Self) -> Self::Output {
2786            FeatureCombinationIteratorInnerBits { 0: self.0 | rhs.0 }
2787        }
2788    }
2789
2790    impl core::ops::BitOrAssign for FeatureCombinationIteratorInnerBits {
2791        fn bitor_assign(&mut self, rhs: Self) {
2792            self.0 |= rhs.0;
2793        }
2794    }
2795
2796    impl core::ops::BitXor for FeatureCombinationIteratorInnerBits {
2797        type Output = Self;
2798
2799        fn bitxor(self, rhs: Self) -> Self::Output {
2800            FeatureCombinationIteratorInnerBits { 0: self.0 ^ rhs.0 }
2801        }
2802    }
2803
2804    impl core::ops::Not for FeatureCombinationIteratorInnerBits {
2805        type Output = Self;
2806
2807        fn not(self) -> Self::Output {
2808            FeatureCombinationIteratorInnerBits { 0: !self.0 }
2809        }
2810    }
2811
2812    impl core::ops::AddAssign for FeatureCombinationIteratorInnerBits {
2813        fn add_assign(&mut self, rhs: Self) {
2814            // arbitrary-precision integer
2815            let raw_lhs = &mut self.0.data;
2816            let raw_rhs = &rhs.0.data;
2817            let mut carry = 0u64;
2818
2819            for i in 0..raw_lhs.len() {
2820                let (sum1, carry1) = raw_lhs[i].overflowing_add(raw_rhs[i]);
2821                let (sum2, carry2) = sum1.overflowing_add(carry);
2822                raw_lhs[i] = sum2;
2823                carry = (carry1 as u64) + (carry2 as u64);
2824            }
2825        }
2826    }
2827
2828    impl core::cmp::PartialOrd for FeatureCombinationIteratorInnerBits {
2829        fn partial_cmp(&self, other: &Self) -> Option<core::cmp::Ordering> {
2830            self.0.partial_cmp(&other.0)
2831        }
2832    }
2833
2834    impl core::cmp::Ord for FeatureCombinationIteratorInnerBits {
2835        fn cmp(&self, other: &Self) -> core::cmp::Ordering {
2836            self.0.cmp(&other.0)
2837        }
2838    }
2839
2840    impl core::cmp::PartialEq for FeatureCombinationIteratorInnerBits {
2841        fn eq(&self, other: &Self) -> bool {
2842            self.0 == other.0
2843        }
2844    }
2845
2846    impl core::cmp::Eq for FeatureCombinationIteratorInnerBits {}
2847
2848    impl core::ops::Index<usize> for FeatureCombinationIteratorInnerBits {
2849        type Output = bool;
2850
2851        fn index(&self, index: usize) -> &bool {
2852            &self.0[index]
2853        }
2854    }
2855
2856    impl FeatureCombinationIteratorInnerBits {
2857        /// Represents zero bits or no combinations active.
2858        pub const ZERO: Self = FeatureCombinationIteratorInnerBits {
2859            0: FeatureCombinationIteratorInnerBitsInner::ZERO,
2860        };
2861        /// Represents a standard first iteration or bit-start active.
2862        pub const ONE: Self = Self::from_number(1);
2863
2864        /// Sets a specific position in the underlying representation.
2865        pub fn set(&mut self, index: usize, value: bool) {
2866            self.0.set(index, value);
2867        }
2868
2869        /// Checks if this completely represents zeros.
2870        pub fn is_zero(&self) -> bool {
2871            self.0 == FeatureCombinationIteratorInnerBitsInner::ZERO
2872        }
2873
2874        /// Checks if this is fully saturated.
2875        pub fn is_full(&self) -> bool {
2876            self.0.all()
2877        }
2878
2879        /// Counts empty zeroes towards the most significant bit.
2880        pub fn leading_zeros(&self) -> usize {
2881            self.0.leading_zeros()
2882        }
2883
2884        /// Counts empty zeroes towards the least significant bit.
2885        pub fn trailing_zeros(&self) -> usize {
2886            self.0.trailing_zeros()
2887        }
2888
2889        /// Retrieves memory layout mapping to underlying pointers.
2890        pub fn as_raw_slice(&self) -> &[u64] {
2891            self.0.as_raw_slice()
2892        }
2893
2894        /// Wraps static number initializations.
2895        pub const fn from_number(num: u64) -> Self {
2896            let mut bits: FeatureCombinationIteratorInnerBitsInner =
2897                FeatureCombinationIteratorInnerBitsInner::ZERO;
2898            bits.data[0] = num;
2899            FeatureCombinationIteratorInnerBits { 0: bits }
2900        }
2901
2902        /// Generates an instance securely masked to the indicated position.
2903        pub fn from_one_pos(pos: usize) -> Self {
2904            let mut bits: FeatureCombinationIteratorInnerBitsInner =
2905                FeatureCombinationIteratorInnerBitsInner::ZERO;
2906            bits.set(pos, true);
2907            FeatureCombinationIteratorInnerBits { 0: bits }
2908        }
2909
2910        /// Rapidly progresses to the next combination variant manually.
2911        pub fn increment(&mut self) {
2912            // arbitrary-precision integer
2913            let raw = &mut self.0.data;
2914            let mut carry = 1u64;
2915
2916            for i in 0..raw.len() {
2917                let (new_value, new_carry) = raw[i].overflowing_add(carry);
2918                raw[i] = new_value;
2919                carry = if new_carry { 1 } else { 0 };
2920                if carry == 0 {
2921                    break;
2922                }
2923            }
2924        }
2925    }
2926
2927    #[cfg(test)]
2928    mod tests {
2929        use super::FeatureCombinationIteratorInnerBits;
2930
2931        #[test]
2932        fn test_increment() {
2933            let mut s = FeatureCombinationIteratorInnerBits::ZERO;
2934            assert_eq!(s.leading_zeros(), 128);
2935            s.set(1, true);
2936            println!("{:?}", s.as_raw_slice());
2937            assert_eq!(s.leading_zeros(), 1);
2938
2939            let mut a = FeatureCombinationIteratorInnerBits::ONE;
2940            a.increment();
2941            assert_eq!(a.as_raw_slice()[0], 2);
2942
2943            let mut b = FeatureCombinationIteratorInnerBits::from_number(u64::MAX);
2944            b.increment();
2945            assert_eq!(b.as_raw_slice()[0], 0);
2946            assert_eq!(b.as_raw_slice()[1], 1);
2947
2948            let mut c = FeatureCombinationIteratorInnerBits::from_number(u64::MAX);
2949            c.set(64, true);
2950            c.increment();
2951            assert_eq!(c.as_raw_slice()[0], 0);
2952            assert_eq!(c.as_raw_slice()[1], 2);
2953        }
2954
2955        #[test]
2956        fn test_add_assign() {
2957            let mut a = FeatureCombinationIteratorInnerBits::from_number(1);
2958            let b = FeatureCombinationIteratorInnerBits::from_number(2);
2959            a += b;
2960            assert_eq!(a.as_raw_slice()[0], 3);
2961
2962            let mut c = FeatureCombinationIteratorInnerBits::from_number(u64::MAX);
2963            let d = FeatureCombinationIteratorInnerBits::from_number(1);
2964            c += d;
2965            assert_eq!(c.as_raw_slice()[0], 0);
2966            assert_eq!(c.as_raw_slice()[1], 1);
2967
2968            let mut e = FeatureCombinationIteratorInnerBits::from_number(u64::MAX);
2969            e.set(64, true);
2970            let f = FeatureCombinationIteratorInnerBits::from_number(1);
2971            e += f;
2972            assert_eq!(e.as_raw_slice()[0], 0);
2973            assert_eq!(e.as_raw_slice()[1], 2);
2974        }
2975    }
2976}
2977pub use bits::FeatureCombinationIteratorInnerBits;
2978
2979impl Iterator for BitIterator {
2980    type Item = FeatureCombinationIteratorInnerBits;
2981
2982    fn next(&mut self) -> Option<Self::Item> {
2983        let count = core::mem::size_of::<FeatureCombinationIteratorInnerBits>() * 8
2984            - self.current.trailing_zeros();
2985        if count > self.kind as usize {
2986            None
2987        } else {
2988            let result = self.current;
2989            self.current.increment();
2990
2991            loop {
2992                let flag = self.current & self.skip;
2993                if flag.is_zero() {
2994                    break;
2995                } else {
2996                    self.current +=
2997                        FeatureCombinationIteratorInnerBits::from_one_pos(flag.leading_zeros());
2998                }
2999            }
3000            Some(result)
3001        }
3002    }
3003}
3004
3005#[derive(Debug)]
3006/// Facilitates multi-state combination testing iteration mapping arrays.
3007pub struct FeatureCombinationIterator<C: Borrow<T>, T: ?Sized> {
3008    features: Vec<(
3009        C,
3010        FeatureCombinationIteratorInnerBits,
3011        FeatureCombinationIteratorInnerBits,
3012    )>,
3013    current: BitIterator,
3014    __marker: std::marker::PhantomData<T>,
3015}
3016
3017impl<'a, T: 'a + ?Sized, B: Borrow<T>, C: Borrow<T>, I: IntoIterator<Item = B>> FromIterator<(C, I)>
3018    for FeatureCombinationIterator<C, T>
3019where
3020    for<'c> &'c T: std::cmp::Eq + std::hash::Hash,
3021{
3022    fn from_iter<U: IntoIterator<Item = (C, I)>>(iter: U) -> Self {
3023        // What T refers to
3024        let data = iter
3025            .into_iter()
3026            .map(|(v, includes)| (v, includes.into_iter().collect::<Vec<_>>()))
3027            .collect::<Vec<_>>();
3028
3029        // Referring to T
3030        let num = {
3031            let mut counts = HashMap::new();
3032            // Initialize counts for all items to 0
3033            for (v, _) in &data {
3034                counts.insert(v.borrow(), 0isize);
3035            }
3036            // Count references
3037            for (_, inc) in &data {
3038                for v in inc {
3039                    if let Some(c) = counts.get_mut(&v.borrow()) {
3040                        *c += 1;
3041                    }
3042                }
3043            }
3044
3045            data.iter()
3046                .map(|(v, _)| -*counts.get(&v.borrow()).unwrap_or(&0))
3047                .collect::<Vec<_>>()
3048        };
3049
3050        let data = data.into_iter().zip(num).collect::<Vec<_>>();
3051
3052        // TODO!(); fix with behavior change
3053        // data.sort_by_key(|(_, v)| *v);
3054        // Remove 'num' from data, but keep dependencies
3055        let mut data: Vec<(C, Vec<B>)> = data.into_iter().map(|(v, _)| v).collect();
3056
3057        // Check for non-trivial cycles (mutual references)
3058        {
3059            let index_map: std::collections::HashMap<&T, usize> = data
3060                .iter()
3061                .enumerate()
3062                .map(|(i, (v, _))| (v.borrow(), i))
3063                .collect();
3064
3065            let mut visited = vec![0u8; data.len()]; // 0: White, 1: Gray, 2: Black
3066            let mut stack = Vec::new();
3067
3068            for i in 0..data.len() {
3069                if visited[i] != 0 {
3070                    continue;
3071                }
3072
3073                stack.push((i, 0));
3074                visited[i] = 1; // Gray
3075
3076                while let Some((u, dep_idx)) = stack.last_mut() {
3077                    let u = *u;
3078                    let deps = &data[u].1;
3079                    if *dep_idx < deps.len() {
3080                        let dep = &deps[*dep_idx];
3081                        *dep_idx += 1;
3082
3083                        if let Some(&v) = index_map.get(&dep.borrow()) {
3084                            if u == v {
3085                                continue;
3086                            }
3087                            if visited[v] == 1 {
3088                                panic!("Mutual reference detected!");
3089                            }
3090                            if visited[v] == 0 {
3091                                visited[v] = 1;
3092                                stack.push((v, 0));
3093                            }
3094                        }
3095                    } else {
3096                        // Finished processing u
3097                        visited[u] = 2; // Black
3098                        stack.pop();
3099                    }
3100                }
3101            }
3102        }
3103
3104        // Ensure that values referencing themselves are always placed on the right.
3105        // if sortable, swap with a value that does not reference itself so we check it.
3106        let mut count = 0i32;
3107        loop {
3108            let mut changed = false;
3109            for i in 0..data.len() {
3110                let mut swap_idx = None;
3111                {
3112                    let (ref_value, ref_includes) = &data[i];
3113                    if ref_includes
3114                        .iter()
3115                        .any(|v| v.borrow() == ref_value.borrow())
3116                    {
3117                        // Find a value to swap with
3118                        for j in (i + 1)..data.len() {
3119                            let (_, swap_includes) = &data[j];
3120                            if !swap_includes
3121                                .iter()
3122                                .any(|v| v.borrow() == ref_value.borrow())
3123                            {
3124                                swap_idx = Some(j);
3125                                break;
3126                            }
3127                        }
3128                    }
3129                }
3130
3131                if let Some(j) = swap_idx {
3132                    data.swap(i, j);
3133                    changed = true;
3134                }
3135            }
3136            if !changed {
3137                break;
3138            }
3139            if count.checked_add(1).is_none() {
3140                break;
3141            }
3142            count += 1;
3143            if count as u128 > 1u128.checked_shl(data.len() as u32).unwrap_or(u128::MAX) {
3144                panic!("Mutual reference detected!");
3145            }
3146        }
3147
3148        let (data, _): (Vec<_>, Vec<_>) = data.into_iter().map(|v| (v, ())).unzip();
3149
3150        let len = data.len();
3151
3152        let map = data
3153            .iter()
3154            .enumerate()
3155            .map(|(i, (v, _))| (v.borrow(), i))
3156            .collect::<HashMap<&T, usize>>();
3157
3158        // Rebuild dependents map from sorted data
3159        let dependents_map = {
3160            let mut dmap = data
3161                .iter()
3162                .map(|(v, _)| (v.borrow(), vec![]))
3163                .collect::<HashMap<&T, Vec<&C>>>();
3164
3165            for (t, inc) in &data {
3166                for v in inc {
3167                    if let Some(list) = dmap.get_mut(&v.borrow()) {
3168                        list.push(t);
3169                    }
3170                }
3171            }
3172            dmap
3173        };
3174
3175        let mut features_base = Vec::with_capacity(data.len());
3176        let mut dependencies_masks = Vec::with_capacity(data.len());
3177        for (v, inc) in &data {
3178            let deps = dependents_map
3179                .get(&v.borrow())
3180                .map(|v| v.as_slice())
3181                .unwrap_or(&[]);
3182            let mut mask = FeatureCombinationIteratorInnerBits::ZERO;
3183            let mut indices = Vec::new();
3184
3185            for dep in deps {
3186                let idx = map[&(*dep).borrow()];
3187                mask.set(idx, true);
3188                indices.push(idx);
3189            }
3190            features_base.push((indices, mask));
3191
3192            // Compute dependencies mask
3193            let mut dep_mask = FeatureCombinationIteratorInnerBits::ZERO;
3194            for d in inc {
3195                if let Some(idx) = map.get(&d.borrow()) {
3196                    dep_mask.set(*idx, true);
3197                }
3198            }
3199            dependencies_masks.push(dep_mask);
3200        }
3201
3202        let mut features_masks: Vec<FeatureCombinationIteratorInnerBits> =
3203            features_base.iter().map(|(_, m)| *m).collect();
3204
3205        for _ in 0..data.len() {
3206            let mut changed = false;
3207            for i in 0..data.len() {
3208                let (indices, _) = &features_base[i];
3209                let mut mask = features_masks[i];
3210                for &dep_idx in indices {
3211                    mask |= features_masks[dep_idx];
3212                    if mask != features_masks[i] { // Check against current stored mask, not 'old' local var if we updated it?
3213                        // Logic: mask |= dep_mask.
3214                        // If mask grew, changed=true.
3215                    }
3216                }
3217                if mask != features_masks[i] {
3218                    features_masks[i] = mask;
3219                    changed = true;
3220                }
3221            }
3222            if !changed {
3223                break;
3224            }
3225        }
3226
3227        let features = features_masks
3228            .into_iter()
3229            .zip(dependencies_masks)
3230            .zip(data)
3231            .map(|((mask, dep_mask), (v, _))| (v, mask, dep_mask))
3232            .collect::<Vec<_>>();
3233
3234        FeatureCombinationIterator {
3235            features,
3236            current: BitIterator::new(len as u8),
3237            __marker: std::marker::PhantomData,
3238        }
3239    }
3240}
3241
3242impl<C: Borrow<T> + std::cmp::Eq + std::hash::Hash + Clone, T: ?Sized> Iterator
3243    for FeatureCombinationIterator<C, T>
3244{
3245    type Item = std::collections::HashSet<C>;
3246
3247    fn next(&mut self) -> Option<Self::Item> {
3248        loop {
3249            let bits = self.current.now();
3250
3251            // Check termination
3252            let count = core::mem::size_of::<FeatureCombinationIteratorInnerBits>() * 8
3253                - bits.trailing_zeros();
3254            if count > self.current.kind as usize {
3255                return None;
3256            }
3257
3258            // Compute skip mask (dependents of absent features)
3259            let mut _mask = FeatureCombinationIteratorInnerBits::ZERO;
3260            for (i, (_, feature_bits, _)) in self.features.iter().enumerate() {
3261                if !bits[i] {
3262                    // Feature i is absent
3263                    _mask |= *feature_bits; // Dependents of i are forbidden
3264                }
3265            }
3266
3267            // Compute skip mask (dependents of absent features)
3268            // AND resolve violations (features present without dependencies)
3269            let _mask = FeatureCombinationIteratorInnerBits::ZERO;
3270
3271            // Check for Forbidden features (because dependency is missing)
3272            // This is equivalent to checking "Present features have all dependencies".
3273
3274            // Strategy: Iterate all features.
3275            // If feature i is PRESENT:
3276            //    Check dependencies_masks[i].
3277            //    If ANY dependency d is ABSENT -> Violation.
3278            //    violation |= (1 << i).
3279            //    To resolve: Either Clear i (add 1<<i) OR Set d (add 1<<d).
3280            //    We should pick the one that adds the LEAST to current.
3281            //    If d < i: Set d.
3282            //    If d > i: Clear i.
3283            //    Also if Clear i, we might need to carry.
3284
3285            // We can compute minimum jump.
3286
3287            let mut min_jump = None;
3288
3289            for (i, (_, _, dependencies)) in self.features.iter().enumerate() {
3290                if bits[i] {
3291                    // Feature i is Present.
3292                    // Dependencies must be Present.
3293                    // Missing = dependencies & !bits.
3294                    let missing = *dependencies & !bits;
3295                    if !missing.is_zero() {
3296                        // Violation! Feature i needs missing dependencies.
3297                        // Options:
3298                        // 1. Clear i (add 1<<i).
3299                        // 2. Set d (for each d in missing). (add distance to d).
3300
3301                        // Option 1: Clear i.
3302
3303                        // Option 2: Set d.
3304                        // For each d in missing:
3305                        //   d_pos = trailing_zeros(d)?
3306                        //   d_jump = 1<<d_pos - (bits & low_mask)?
3307                        //   Wait. next_valid(bits, d) = (bits | (1<<d)) & !((1<<d)-1).
3308                        //   jump = next_valid - bits.
3309                        //   Or simplistically: 1<<d?
3310                        //   If bits has lower bits set, 1<<d might not be enough or too much?
3311                        //   Actually, we want to reach the *next* state where d=1.
3312                        //   (bits | (1<<d)) & !((1<<d)-1).
3313
3314                        // Let's implement calculate_jump(current, target_bit).
3315                        // But FeatureCombinationInnerBits doesn't expose arithmetic easily.
3316                        // It has `from_one_pos`.
3317                        // It has `+`.
3318
3319                        // If d < i.
3320                        // Then bits[d]=0. bits[i]=1.
3321                        // We want d=1.
3322                        // Since d < i, d is a lower bit.
3323                        // If we increment, d will toggle soon.
3324                        // E.g. d=0. 0->1 is +1.
3325                        // d=1. 00->10 is +2 (if 00).
3326
3327                        // If we just track "smallest bit that needs to change".
3328                        // If any d < i.
3329                        // Then we assume natural increment will handle it?
3330                        // But we want to SKIP invalid states.
3331                        // If d < i. We can jump to next d=1.
3332                        // If d > i. We MUST clear i. (Jump to next i=0).
3333
3334                        // If d > i. Jump = 1<<i (Clear i).
3335                        // If d < i. Jump = Next d=1.
3336                        // Next d=1 is <= 1<<d (relative to cleared lower).
3337
3338                        // Let's optimize:
3339                        // If ANY d > i: We MUST clear i.
3340                        // Jump = 1<<i.
3341
3342                        // If ALL d < i:
3343                        // We can wait for d.
3344                        // Can we skip to d?
3345                        // Yes. Jump to smallest d.
3346                        // But we can't easily compute "Jump to d" with abstract bits.
3347                        // But if d < i, and we assume Lsb0.
3348                        // 1<<d is smaller than 1<<i.
3349                        // So jump is smaller?
3350                        // If we iterate violations and pick minimum 1<<pos.
3351                        // If we pick 1<<i (Clear i).
3352                        // If we pick 1<<d (Set d? No, 1<<d might not set d correctly if lower bits are messy).
3353                        // But generally, adding 1<<d will toggle d (0->1) and clear lower.
3354                        // So adding 1<<d IS correct to jump to next d=1.
3355
3356                        // So:
3357                        // Candidates:
3358                        // 1. 1<<i.
3359                        // 2. 1<<d (for all d in missing).
3360
3361                        // Pick the SMALLEST candidate (lowest index).
3362                        // And apply it.
3363
3364                        // If we find MULTIPLE violations.
3365                        // We should pick the global minimum jump.
3366
3367                        // So loop over all i.
3368                        // Collect candidates.
3369                        // Pick min.
3370
3371                        // Candidate from i: i.
3372                        // Candidates from missing: d's.
3373
3374                        // Wait. If d < i.
3375                        // Should we set d or clear i?
3376                        // If we set d (jump 1<<d), we keep i set. Result valid (i=1, d=1).
3377                        // If we clear i (jump 1<<i), we get i=0. Result valid (i=0, d=0).
3378                        // Which is next?
3379                        // 1<<d is smaller. So we set d.
3380
3381                        // If d > i.
3382                        // Set d (jump 1<<d). Keep i set.
3383                        // Clear i (jump 1<<i).
3384                        // 1<<i is smaller. So we clear i.
3385
3386                        // So strategy:
3387                        // Collect all `i` (violation bits) and all `d` (missing dependencies).
3388                        // Find the MINIMUM index `m` among them.
3389                        // Add `1 << m`.
3390
3391                        // Example: i=1 (B). d=0 (A).
3392                        // Min(1, 0) = 0.
3393                        // Add 1<<0 (1).
3394                        // 0010 + 1 = 0011 (A=1, B=1). Correct.
3395
3396                        // Example: i=0 (A). d=2 (C). (If A depended on C).
3397                        // Min(0, 2) = 0.
3398                        // Add 1<<0 (1).
3399                        // 0001 + 1 = 0010 (A=0). Correct.
3400
3401                        // This logic is beautiful.
3402                        // Just find the lowest bit involved in any violation (either the feature itself or its missing dependency).
3403                        // And add 1 << that bit.
3404
3405                        // Iterate bits of missing.
3406
3407                        // Let's accumulate a "jump_mask".
3408                        // jump_mask |= (1 << i).
3409                        // jump_mask |= missing.
3410
3411                        if min_jump.is_none() {
3412                            min_jump = Some(FeatureCombinationIteratorInnerBits::ZERO);
3413                        }
3414                        if let Some(ref mut j) = min_jump {
3415                            j.set(i, true);
3416                            *j |= missing;
3417                        }
3418                    }
3419                }
3420            }
3421
3422            if let Some(jump_mask) = min_jump {
3423                // Found violations.
3424                // We want smallest bit in jump_mask.
3425                // Wait. trailing_zeros counts from MSB in BitArray (Lsb0)???
3426                // NO. I decided earlier it counted from MSB.
3427                // But leading_zeros counted from LSB?
3428                // `from_one_pos` uses index.
3429                // If I want index of lowest bit.
3430                // If `Lsb0`: Index 0 is lowest.
3431                // If `trailing_zeros` counts from End (127).
3432                // `leading_zeros` counts from Start (0).
3433                // So I want `leading_zeros`.
3434
3435                // Let's use `leading_zeros`.
3436                let bit = jump_mask.leading_zeros(); // Index of first set bit (lowest index).
3437                self.current.current += FeatureCombinationIteratorInnerBits::from_one_pos(bit);
3438
3439                // Continue loop
3440            } else {
3441                // Valid!
3442                // ... return result ...
3443                let mut result = std::collections::HashSet::new();
3444                for (i, (feature, _, _)) in self.features.iter().enumerate() {
3445                    if bits[i] {
3446                        result.insert(feature.clone());
3447                    }
3448                }
3449                self.current.current.increment();
3450                return Some(result);
3451            }
3452        }
3453    }
3454}
3455
3456#[cfg(test)]
3457mod tests {
3458    use std::{collections::HashSet, sync::Arc};
3459
3460    use super::*;
3461
3462    #[test]
3463    fn test_get_file_main_name() {
3464        let path = camino::Utf8Path::new("name.opt.adjusted.wasm");
3465        let file_name = path.get_file_main_name();
3466        assert_eq!(file_name.unwrap(), "name");
3467    }
3468
3469    #[test]
3470    fn test_bit_generator() {
3471        let bits = BitIterator::new(3).collect::<Vec<_>>();
3472
3473        assert_eq!(
3474            &bits
3475                .iter()
3476                .map(|b| b.as_raw_slice()[0])
3477                .collect::<Vec<u64>>(),
3478            &[0b000, 0b001, 0b010, 0b011, 0b100, 0b101, 0b110, 0b111]
3479        );
3480
3481        let count = BitIterator::new(10).count();
3482        assert_eq!(count, 1024);
3483
3484        let mut generator = BitIterator::new(5);
3485        generator.register_skip(1);
3486        generator.register_skip(3);
3487        let bits = generator.collect::<Vec<_>>();
3488
3489        assert_eq!(
3490            &bits
3491                .iter()
3492                .map(|b| b.as_raw_slice()[0])
3493                .collect::<Vec<u64>>(),
3494            &[
3495                0b00000, 0b00001, 0b00100, 0b00101, 0b10000, 0b10001, 0b10100, 0b10101
3496            ]
3497        );
3498    }
3499
3500    #[test]
3501    fn test_feature_combination_iterator() {
3502        let data = vec![
3503            ("A", vec![]),
3504            ("B", vec!["A"]),
3505            ("C", vec!["A"]),
3506            ("D", vec!["B", "C"]),
3507        ];
3508
3509        let iterator = data
3510            .into_iter()
3511            .collect::<FeatureCombinationIterator<_, str>>();
3512
3513        println!("Iterator created: {:?}", iterator);
3514
3515        let combinations = iterator.collect::<Vec<_>>();
3516
3517        let expected = vec![
3518            HashSet::from([]),
3519            HashSet::from(["A"]),
3520            HashSet::from(["A", "B"]),
3521            HashSet::from(["A", "C"]),
3522            HashSet::from(["A", "B", "C"]),
3523            HashSet::from(["A", "B", "C", "D"]),
3524        ];
3525
3526        assert_eq!(combinations, expected);
3527
3528        let data = vec![
3529            (String::from("A"), vec![]),
3530            (String::from("B"), vec![String::from("A")]),
3531            (String::from("C"), vec![String::from("A")]),
3532            (
3533                String::from("D"),
3534                vec![String::from("B"), String::from("C")],
3535            ),
3536        ];
3537        let data_ref = data
3538            .iter()
3539            .map(|(v, inc)| (v, inc.iter().map(|s| s).collect::<Vec<_>>()))
3540            .collect::<Vec<_>>();
3541
3542        let iterator = data
3543            .clone()
3544            .into_iter()
3545            .collect::<FeatureCombinationIterator<_, String>>();
3546
3547        let iterator2 = data_ref
3548            .into_iter()
3549            .collect::<FeatureCombinationIterator<_, String>>();
3550
3551        println!("Iterator created: {:?}", iterator);
3552
3553        let combinations = iterator.collect::<Vec<_>>();
3554        let _combinations2 = iterator2.collect::<Vec<_>>();
3555
3556        let expected = vec![
3557            HashSet::from([]),
3558            HashSet::from([String::from("A")]),
3559            HashSet::from([String::from("A"), String::from("B")]),
3560            HashSet::from([String::from("A"), String::from("C")]),
3561            HashSet::from([String::from("A"), String::from("B"), String::from("C")]),
3562            HashSet::from([
3563                String::from("A"),
3564                String::from("B"),
3565                String::from("C"),
3566                String::from("D"),
3567            ]),
3568        ];
3569
3570        assert_eq!(combinations, expected);
3571
3572        let data = data
3573            .iter()
3574            .map(|(u, v)| (Arc::new(u.clone()), v))
3575            .collect::<Vec<_>>();
3576
3577        let iterator = data
3578            .into_iter()
3579            .collect::<FeatureCombinationIterator<_, String>>();
3580
3581        println!("Iterator created: {:?}", iterator);
3582
3583        let _combinations = iterator.collect::<Vec<_>>();
3584    }
3585
3586    #[test]
3587    #[should_panic(expected = "Mutual reference detected!")]
3588    fn test_feature_combination_iterator_mutual_ref() {
3589        // A includes B
3590        // B includes A
3591        // Cycle!
3592        let data = vec![
3593            (String::from("A"), vec![String::from("B")]),
3594            (String::from("B"), vec![String::from("A")]),
3595        ];
3596
3597        let _iterator = data
3598            .into_iter()
3599            .collect::<FeatureCombinationIterator<_, String>>();
3600    }
3601
3602    #[test]
3603    #[should_panic(expected = "Mutual reference detected!")]
3604    fn test_feature_combination_iterator_complex_cycle() {
3605        // A -> B -> C -> A
3606        let data = vec![
3607            (String::from("A"), vec![String::from("B")]),
3608            (String::from("B"), vec![String::from("C")]),
3609            (String::from("C"), vec![String::from("A")]),
3610        ];
3611
3612        let _iterator = data
3613            .into_iter()
3614            .collect::<FeatureCombinationIterator<_, String>>();
3615    }
3616
3617    #[test]
3618    fn test_feature_combination_iterator_complex_valid() {
3619        // Valid graph:
3620        // A -> B, C
3621        // B -> D
3622        // C -> D
3623        // D -> []
3624        // Order should handle this (D comes first, then B/C, then A)
3625
3626        let data = vec![
3627            (
3628                String::from("A"),
3629                vec![String::from("B"), String::from("C")],
3630            ),
3631            (String::from("B"), vec![String::from("D")]),
3632            (String::from("C"), vec![String::from("D")]),
3633            (String::from("D"), vec![]),
3634        ];
3635
3636        let iterator = data
3637            .into_iter()
3638            .collect::<FeatureCombinationIterator<_, String>>();
3639
3640        let combinations = iterator.collect::<Vec<_>>();
3641        // If it didn't panic and produced combinations, the topological sort/check worked for this valid case.
3642        assert!(combinations.len() > 0);
3643    }
3644
3645    #[test]
3646    fn test_feature_combination_iterator_complex_diamond() {
3647        use std::collections::{HashMap, HashSet};
3648        // Diamond:
3649        // Root -> Left, Right
3650        // Left -> Base
3651        // Right -> Base
3652        // Base -> []
3653
3654        let data = vec![
3655            (
3656                String::from("Root"),
3657                vec![String::from("Left"), String::from("Right")],
3658            ),
3659            (String::from("Left"), vec![String::from("Base")]),
3660            (String::from("Right"), vec![String::from("Base")]),
3661            (String::from("Base"), vec![]),
3662        ];
3663
3664        let iterator = data
3665            .into_iter()
3666            .collect::<FeatureCombinationIterator<_, String>>();
3667
3668        let combinations: Vec<HashSet<String>> = iterator.collect();
3669
3670        // Verify that for every combination, if a feature is present, its dependencies are also present.
3671        // We can check this property for all combinations.
3672
3673        // Dependency map for checking
3674        let deps: HashMap<String, Vec<String>> = HashMap::from([
3675            (
3676                String::from("Root"),
3677                vec![String::from("Left"), String::from("Right")],
3678            ),
3679            (String::from("Left"), vec![String::from("Base")]),
3680            (String::from("Right"), vec![String::from("Base")]),
3681            (String::from("Base"), vec![]),
3682        ]);
3683
3684        for combo in &combinations {
3685            for feature in combo {
3686                if let Some(required) = deps.get(feature) {
3687                    for req in required {
3688                        assert!(
3689                            combo.contains(req),
3690                            "Combination {:?} invalid: {} requires {}",
3691                            combo,
3692                            feature,
3693                            req
3694                        );
3695                    }
3696                }
3697            }
3698        }
3699
3700        // Also verify some known valid combinations are present
3701        assert!(combinations.contains(&HashSet::from([])));
3702        assert!(combinations.contains(&HashSet::from([String::from("Base")])));
3703        assert!(
3704            combinations.contains(&HashSet::from([String::from("Base"), String::from("Left")]))
3705        );
3706        assert!(combinations.contains(&HashSet::from([
3707            String::from("Base"),
3708            String::from("Left"),
3709            String::from("Right"),
3710            String::from("Root")
3711        ])));
3712
3713        // Verify invalid ones are NOT present
3714        // Root only
3715        assert!(!combinations.contains(&HashSet::from([String::from("Root")])));
3716        // Left only
3717        assert!(!combinations.contains(&HashSet::from([String::from("Left")])));
3718    }
3719}