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