wasi_virt_layer_cli/generator/
patch_component.rs

1use strum::VariantNames;
2
3use crate::{
4    abi::Wasip1ABIFunc,
5    generator::Generator,
6    util::{CORE_MODULE_ROOT, WalrusUtilExport as _, WalrusUtilImport as _},
7};
8
9fn gen_component_name(namespace: &str, name: &str) -> String {
10    format!("[static]{namespace}.{}-import", name.replace("_", "-"))
11}
12
13/// Apply the patch to use wit-bindgen.
14/// As it will be rejected otherwise,
15/// swap the import function generated by wit with the wasip1 import function.
16#[derive(Debug, Default)]
17pub struct PatchComponent;
18
19impl Generator for PatchComponent {
20    fn pre_vfs(
21        &mut self,
22        module: &mut walrus::Module,
23        _: &crate::generator::GeneratorCtx,
24    ) -> eyre::Result<()> {
25        for (name, (namespace, root)) in <Wasip1ABIFunc as VariantNames>::VARIANTS
26            .iter()
27            .zip(core::iter::repeat(("wasip1", CORE_MODULE_ROOT)))
28        {
29            let component_name = gen_component_name(namespace, name);
30
31            module.exports.erase(&format!("{name}_import_anchor"))?;
32
33            module
34                .imports
35                .may_swap_import((root, &component_name), ("wasi_snapshot_preview1", name))?;
36        }
37
38        Ok(())
39    }
40}