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
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
use std::{
    fmt::{Debug, Display, Formatter, Write},
    hash::{Hash, Hasher},
    sync::Arc,
};

use indexmap::IndexMap;

use crate::{
    dag::DependentGraph,
    encoder::WastEncoder,
    helpers::{AliasOuter, ComponentDefine, EmitDefault, TypeDefinition, TypeReference},
    wasi_types::{
        array::NyarArray,
        functions::{WasiFunctionBody, WasiNativeFunction},
        resources::WasiResource,
        variants::WasiVariantType,
    },
    DependenciesTrace, Identifier, WasiFunction, WasiModule, WasiRecordType, WasiTypeReference,
};
use std::{cmp::Ordering, ops::AddAssign};
use WasiType::{Float32, Float64, Integer16, Integer32, Integer64, Integer8};

pub mod array;
mod display;
pub mod enumerations;
pub mod functions;
pub mod records;
pub mod reference;
pub mod resources;
pub mod variants;

#[derive(Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub enum WasiType {
    Boolean,
    /// `s8` or `u8` type in WASI
    Integer8 {
        /// Whether the integer is signed or not
        signed: bool,
    },
    /// `s16` or `u16` type in WASI
    Integer16 {
        /// Whether the integer is signed or not
        signed: bool,
    },
    /// `s32` or `u32` type in WASI
    Integer32 {
        /// Whether the integer is signed or not
        signed: bool,
    },
    /// `s64` or `u64` type in WASI
    Integer64 {
        /// Whether the integer is signed or not
        signed: bool,
    },
    /// `f32` type in WASI
    Float32,
    /// `f64` type in WASI
    Float64,
    Option {
        inner: Box<WasiType>,
    },
    Result {
        success: Option<Box<WasiType>>,
        failure: Option<Box<WasiType>>,
    },
    /// `resource` type in WASI
    Resource(WasiResource),
    /// `record` type in WASI
    Record(WasiRecordType),
    /// `variant` type in WASI
    Variant(WasiVariantType),
    /// type reference in WASI
    TypeHandler(WasiTypeReference),
    /// `list` type in WASI
    Array(Box<NyarArray>),
    /// `function` type in WASI
    Function(Box<WasiNativeFunction>),
    /// The host function type in WASI
    External(Box<WasiFunction>),
}

impl WasiType {
    /// Get the type definition of the type, composite type returns `None`
    pub fn wasm_module(&self) -> Option<&WasiModule> {
        match self {
            Self::Resource(v) => Some(&v.wasi_module),
            Self::External(v) => match &v.body {
                WasiFunctionBody::External { wasi_module, .. } => Some(wasi_module),
                WasiFunctionBody::Normal { .. } => None,
            },
            _ => None,
        }
    }
    /// Returns the language identifier of the type, anonymous type returns `None`
    pub fn language_id(&self) -> Option<&Identifier> {
        match self {
            Self::Variant(v) => Some(&v.symbol),
            Self::Resource(v) => Some(&v.symbol),
            Self::External(v) => Some(&v.symbol),
            _ => None,
        }
    }
}

impl DependenciesTrace for WasiType {
    #[track_caller]
    fn define_language_types(&self, _: &mut DependentGraph) {
        panic!("Invalid Call");
    }

    fn collect_wasi_types<'a, 'i>(&'a self, dict: &'i DependentGraph, collected: &mut Vec<&'i WasiType>)
    where
        'a: 'i,
    {
        match self {
            WasiType::Option { inner } => inner.collect_wasi_types(dict, collected),
            WasiType::Result { success, failure } => {
                success.iter().for_each(|s| s.collect_wasi_types(dict, collected));
                failure.iter().for_each(|f| f.collect_wasi_types(dict, collected));
            }
            WasiType::Resource(_) => collected.push(self),
            WasiType::Variant(_) => collected.push(self),
            WasiType::TypeHandler(v) => collected.push(dict.get(v)),
            WasiType::External(_) => collected.push(self),
            _ => {}
        };
    }
}

impl EmitDefault for WasiType {
    fn emit_default<W: Write>(&self, w: &mut WastEncoder<W>) -> std::fmt::Result {
        match self {
            WasiType::Boolean => {
                write!(w, "i32.const 0")
            }
            Integer8 { .. } => {
                write!(w, "i32.const 0")
            }
            Integer16 { .. } => {
                write!(w, "i32.const 0")
            }
            Integer32 { .. } => {
                write!(w, "i32.const 0")
            }
            Integer64 { .. } => {
                write!(w, "i64.const 0")
            }
            Float32 => {
                write!(w, "f32.const 0")
            }
            Float64 => {
                write!(w, "f64.const 0")
            }
            WasiType::Option { .. } => {
                todo!()
            }
            WasiType::Result { .. } => {
                todo!()
            }
            WasiType::Resource(_) => {
                todo!()
            }
            WasiType::Record(_) => {
                todo!()
            }
            WasiType::Variant(_) => {
                todo!()
            }
            WasiType::TypeHandler { .. } => {
                todo!()
            }

            WasiType::Array(_) => {
                todo!()
            }
            WasiType::External(_) => {
                todo!()
            }
            WasiType::Function(_) => {
                todo!()
            }
        }
    }
}

impl WasiType {
    pub fn emit_convert<W: Write>(&self, target: &WasiType, w: &mut WastEncoder<W>) -> std::fmt::Result {
        match (self, target) {
            // any to i32
            (Integer8 { .. } | Integer16 { .. } | Integer32 { .. }, Integer64 { .. }) => write!(w, "i32.wrap_i64")?,
            (Float32, Integer8 { signed: true } | Integer16 { signed: true } | Integer32 { signed: true }) => {
                write!(w, "i32.trunc_f32_s")?
            }
            (Float32, Integer8 { signed: false } | Integer16 { signed: false } | Integer32 { signed: false }) => {
                write!(w, "i32.trunc_f32_u")?
            }
            (Float64, Integer8 { signed: true } | Integer16 { signed: true } | Integer32 { signed: true }) => {
                write!(w, "i32.trunc_f64_s")?
            }
            (Float64, Integer8 { signed: false } | Integer16 { signed: false } | Integer32 { signed: false }) => {
                write!(w, "i32.trunc_f64_u")?
            }
            // any to i64
            (Integer8 { .. } | Integer16 { .. } | Integer32 { .. }, Integer64 { signed: true }) => {
                write!(w, "i64.extend_i32_s")?
            }
            (Integer8 { .. } | Integer16 { .. } | Integer32 { .. }, Integer64 { signed: false }) => {
                write!(w, "i64.extend_i32_u")?
            }
            (Float32, Integer64 { signed: true }) => write!(w, "i64.trunc_f32_s")?,
            (Float32, Integer64 { signed: false }) => write!(w, "i64.trunc_f32_u")?,
            (Float64, Integer64 { signed: true }) => write!(w, "i64.trunc_f64_s")?,
            (Float64, Integer64 { signed: false }) => write!(w, "i64.trunc_f64_u")?,
            // any to f32
            (Integer8 { signed: true } | Integer16 { signed: true } | Integer32 { signed: true }, Float32) => {
                write!(w, "f32.convert_i32_s")?
            }
            (Integer8 { signed: false } | Integer16 { signed: false } | Integer32 { signed: false }, Float32) => {
                write!(w, "f32.convert_i32_u")?
            }
            (Integer64 { signed: true }, Float32) => write!(w, "f32.convert_i64_s")?,
            (Integer64 { signed: false }, Float32) => write!(w, "f32.convert_i64_u")?,
            (Float32, Float32) => write!(w, "f32.demote_f64")?,
            // any to f64
            (Integer8 { signed: true } | Integer16 { signed: true } | Integer32 { signed: true }, Float64) => {
                write!(w, "f64.convert_i32_s")?
            }
            (Integer8 { signed: false } | Integer16 { signed: false } | Integer32 { signed: false }, Float64) => {
                write!(w, "f64.convert_i32_u")?
            }
            (Integer64 { signed: true }, Float64) => write!(w, "f64.convert_i64_s")?,
            (Integer64 { signed: false }, Float64) => write!(w, "f64.convert_i64_u")?,
            (Float32, Float64) => write!(w, "f64.promote_f32")?,
            _ => unimplemented!("convert {} to {}", self, target),
        }
        Ok(())
    }
    pub fn emit_transmute<W: Write>(&self, target: &WasiType, w: &mut WastEncoder<W>) -> std::fmt::Result {
        match (self, target) {
            (Float32, Integer32 { .. }) => write!(w, "i32.reinterpret_f32")?,
            (Float64, Integer64 { .. }) => write!(w, "i64.reinterpret_f64")?,
            (Integer32 { .. }, Float32) => write!(w, "f32.reinterpret_i32")?,
            (Integer64 { .. }, Float64) => write!(w, "f64.reinterpret_i64")?,
            _ => unimplemented!("transmute {} to {}", self, target),
        }
        Ok(())
    }
}