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