wasi_virt_layer-cli 0.1.0

CLI for the wasi_virt_layer crate
Documentation
use strum::VariantNames;

use crate::{
    abi::Wasip1ABIFunc,
    generator::Generator,
    util::{CORE_MODULE_ROOT, WalrusUtilExport as _, WalrusUtilImport as _},
};

fn gen_component_name(namespace: &str, name: &str) -> String {
    format!("[static]{namespace}.{}-import", name.replace("_", "-"))
}

/// Apply the patch to use wit-bindgen.
/// As it will be rejected otherwise,
/// swap the import function generated by wit with the wasip1 import function.
#[derive(Debug, Default)]
pub struct PatchComponent;

impl Generator for PatchComponent {
    fn pre_vfs(
        &mut self,
        module: &mut walrus::Module,
        _: &crate::generator::GeneratorCtx,
    ) -> eyre::Result<()> {
        for (name, (namespace, root)) in <Wasip1ABIFunc as VariantNames>::VARIANTS
            .iter()
            .zip(core::iter::repeat(("wasip1", CORE_MODULE_ROOT)))
        {
            let component_name = gen_component_name(namespace, name);

            module.exports.erase(&format!("{name}_import_anchor"))?;

            module
                .imports
                .may_swap_import((root, &component_name), ("wasi_snapshot_preview1", name))?;
        }

        Ok(())
    }
}