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
80
81
use crate::{
    helpers::{IntoWasm, WasmName},
    values::WasmValue,
    WasmSymbol, WasmType,
};
use nyar_error::FileSpan;
use std::collections::BTreeMap;
use wast::{
    component::{ComponentDefinedType, Record, RecordField},
    core::{StructField, StructType},
    token::{NameAnnotation, Span},
};

mod codegen;
mod convert;

#[derive(Clone, Debug)]
pub struct StructureItem {
    pub symbol: WasmSymbol,
    pub fields: BTreeMap<String, FieldType>,
    pub span: FileSpan,
}

#[derive(Clone, Debug)]
pub struct StructureType {
    pub symbol: WasmSymbol,
    pub nullable: bool,
    pub fields: BTreeMap<String, FieldType>,
}

#[derive(Clone, Debug)]
pub struct FieldType {
    pub name: WasmSymbol,
    pub readonly: bool,
    pub r#type: WasmType,
    pub default: WasmValue,
}

impl StructureItem {
    pub fn new<S: Into<WasmSymbol>>(name: S) -> Self {
        Self { symbol: name.into(), fields: Default::default(), span: Default::default() }
    }
    pub fn name(&self) -> String {
        self.symbol.to_string()
    }
    pub fn set_field(&mut self, field: FieldType) {
        self.fields.insert(field.name.to_string(), field);
    }
    pub fn with_fields<I>(mut self, fields: I) -> Self
    where
        I: IntoIterator<Item = FieldType>,
    {
        for field in fields {
            self.set_field(field);
        }
        self
    }
}

impl FieldType {
    pub fn new<S: Into<WasmSymbol>>(name: S) -> Self {
        Self { name: name.into(), readonly: false, r#type: WasmType::Any { nullable: false }, default: WasmValue::Any }
    }
    pub fn with_type(self, r#type: WasmType) -> Self {
        Self { r#type, ..self }
    }
    pub fn with_default(self, default: WasmValue) -> Self {
        Self { default, ..self }
    }

    pub fn set_nullable(&mut self, nullable: bool) {
        self.r#type.set_nullable(nullable);
    }

    pub fn with_mutable(self) -> Self {
        Self { readonly: false, ..self }
    }
    pub fn with_readonly(self) -> Self {
        Self { readonly: true, ..self }
    }
}