Skip to main content

lamina_codegen/wasm/
abi.rs

1//! WASM ABI utilities
2//!
3//! WASM has a more standardized ABI compared to native platforms,
4//! but we still need utilities for function naming and module structure.
5
6use crate::abi::Abi;
7use lamina_platform::TargetOperatingSystem;
8
9/// Platform-specific ABI utilities for WASM code generation.
10pub struct WasmABI {
11    target_os: TargetOperatingSystem,
12}
13
14impl WasmABI {
15    /// Creates a new ABI instance for the specified target OS.
16    pub fn new(target_os: TargetOperatingSystem) -> Self {
17        Self { target_os }
18    }
19
20    /// Get the WASM function name (currently just the original name).
21    /// WASM doesn't require name mangling, but this method exists for consistency
22    /// with other backends and future extensibility.
23    pub fn mangle_function_name(&self, name: &str) -> String {
24        name.to_string()
25    }
26
27    /// Get the WASM import for the print function.
28    pub fn get_print_import(&self) -> &'static str {
29        "(import \"console\" \"log\" (func $log (param i64)))"
30    }
31
32    /// Get the WASM type for MIR types (currently only i64).
33    pub fn get_wasm_type(&self, ty: &lamina_mir::MirType) -> &'static str {
34        match ty {
35            lamina_mir::MirType::Scalar(lamina_mir::ScalarType::I64) => "i64",
36            _ => "i64",
37        }
38    }
39
40    /// Generate WASM global variable declaration for virtual registers.
41    pub fn generate_global_decl(&self, index: usize) -> String {
42        format!("  (global $vreg{} (mut i64) (i64.const 0))", index)
43    }
44
45    /// Generate WASM local variable declaration.
46    pub fn generate_local_decl(&self, index: usize) -> String {
47        format!("    (local $l{} i64)", index)
48    }
49}
50
51impl Abi for WasmABI {
52    fn target_os(&self) -> TargetOperatingSystem {
53        self.target_os
54    }
55
56    fn mangle_function_name(&self, name: &str) -> String {
57        WasmABI::mangle_function_name(self, name)
58    }
59}