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