1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
use crate::{
    functions::FunctionType,
    helpers::{write_wasm_bytes, IntoWasm, WasmName},
    structures::StructureType,
    ArrayType, DataItem, DataSection, ExternalSection, ExternalType, WasmVariable,
};
use nyar_error::NyarError;
use std::{
    collections::BTreeMap,
    path::{Path, PathBuf},
};
use wast::{
    component::{Component, ComponentField, ComponentKind, CoreModule, CoreModuleKind},
    core::{InlineExport, Limits, Memory, MemoryKind, MemoryType, Module, ModuleField, ModuleKind, Producers},
    token::{Index, NameAnnotation, Span},
};

mod wast_component;
mod wast_module;

pub trait WasmItem {
    fn register(self, builder: &mut WasmBuilder);
}

#[derive(Default)]
pub struct WasmBuilder {
    pub name: String,
    pub entry: String,
    pub memory_pages: u64,
    pub globals: BTreeMap<String, WasmVariable>,
    pub structures: BTreeMap<String, StructureType>,
    pub arrays: BTreeMap<String, ArrayType>,
    pub data: DataSection,
    pub functions: BTreeMap<String, FunctionType>,
    pub externals: ExternalSection,
}

impl WasmItem for ExternalType {
    fn register(self, builder: &mut WasmBuilder) {
        builder.externals.insert(self);
    }
}

impl WasmItem for FunctionType {
    fn register(self, builder: &mut WasmBuilder) {
        if self.entry {
            builder.entry = self.name()
        }
        builder.functions.insert(self.name(), self);
    }
}
impl WasmItem for ArrayType {
    fn register(self, builder: &mut WasmBuilder) {
        builder.arrays.insert(self.symbol.to_string(), self);
    }
}

impl WasmBuilder {
    pub fn new<S: ToString>(name: S) -> Self {
        Self { name: name.to_string(), ..Default::default() }
    }

    pub fn get_module_name(&self) -> &str {
        &self.name
    }
    pub fn set_module_name<S: ToString>(&mut self, name: S) {
        self.name = name.to_string();
    }
    pub fn register<T: WasmItem>(&mut self, item: T) {
        item.register(self);
    }

    pub fn register_data(&mut self, item: DataItem) -> Option<DataItem> {
        self.data.insert(item)
    }
    pub fn register_global(&mut self, global: WasmVariable) {
        self.globals.insert(global.symbol.to_string(), global);
    }
}