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
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
//! Muse-defined custom types.

use kempt::Map;
use refuse::{CollectionGuard, ContainsNoRefs, Trace};
use serde::{Deserialize, Serialize};

use super::symbol::{Symbol, SymbolRef};
use super::value::{CustomType, Rooted, Type, TypeRef, Value};
use crate::vm::bitcode::{Access, Accessable, BitcodeFunction, ValueOrSource};
use crate::vm::{Arity, Fault, Function, ModuleId, Register, VmContext};

/// An IR Muse-defined struct.
#[derive(PartialEq, Clone, Debug, Serialize, Deserialize)]
pub struct BitcodeStruct {
    /// The name of the struct.
    pub name: Symbol,
    /// The functions defined on the struct.
    pub functions: Map<Symbol, Accessable<BitcodeFunction>>,
    /// The fields defined on members of this struct.
    pub fields: Map<Symbol, Access>,
}

impl BitcodeStruct {
    pub(crate) fn load(&self, guard: &CollectionGuard<'_>, module: ModuleId) -> RuntimeStruct {
        let functions = self
            .functions
            .iter()
            .map(|field| (field.key().clone(), field.value.to_function(guard, module)))
            .collect::<Map<_, _>>();

        let mut ty = Type::new(self.name.clone());

        ty = ty.with_invoke(|fallback| {
            let functions = functions.clone();
            move |this, vm, name, arity| {
                if let Some(func) = functions.get(name) {
                    if func.access < vm.caller_access_level_by_index(module) {
                        return Err(Fault::Forbidden);
                    }

                    if arity == 255 {
                        return Err(Fault::InvalidArity);
                    } else if arity.0 > 0 {
                        vm.registers_mut().copy_within(0..usize::from(arity.0), 1);
                    }
                    vm[Register(0)] = Value::Dynamic(*this);
                    (func.accessable.muse_type().vtable.call)(
                        &func.accessable.as_any_dynamic(),
                        vm,
                        Arity(arity.0 + 1),
                    )
                } else if name == Symbol::get_symbol() && arity == 1 {
                    let Some(field_name) = vm[Register(0)].as_symbol_ref() else {
                        return Err(Fault::ExpectedSymbol);
                    };
                    let loaded = this
                        .downcast_ref::<StructInstance>(vm.guard())
                        .ok_or(Fault::ValueFreed)?;
                    if let Some(field) = loaded.fields.get(field_name) {
                        if field.access < vm.caller_access_level_by_index(module) {
                            return Err(Fault::Forbidden);
                        }
                        Ok(field.accessable)
                    } else {
                        Err(Fault::UnknownSymbol)
                    }
                } else {
                    fallback(this, vm, name, arity)
                }
            }
        });

        let instance = ty.seal(guard);

        // TODO the type name for the type itself should probably be distinctive.
        let mut ty = Type::new(self.name.clone()).with_call(|_| {
            let fields = self.fields.clone();
            move |_this, vm, arity| {
                let fields = (0..arity.0 / 2)
                    .map(|index| {
                        let name = vm[Register(index * 2)]
                            .take()
                            .as_symbol(vm.guard())
                            .ok_or(Fault::ExpectedSymbol)?;
                        let access = *fields.get(&name).ok_or(Fault::UnknownSymbol)?;
                        Ok((
                            name.downgrade(),
                            Accessable {
                                access,
                                accessable: vm[Register(index * 2 + 1)].take(),
                            },
                        ))
                    })
                    .collect::<Result<_, Fault>>()?;
                Ok(Value::dynamic(
                    StructInstance {
                        ty: instance.clone(),
                        fields,
                    },
                    vm.guard(),
                ))
            }
        });

        ty = ty.with_invoke(|fallback| {
            let functions = functions.clone();
            move |this, vm, name, arity| {
                if let Some(func) = functions.get(name) {
                    if func.access < vm.caller_access_level_by_index(module) {
                        return Err(Fault::Forbidden);
                    }

                    (func.accessable.muse_type().vtable.call)(
                        &func.accessable.as_any_dynamic(),
                        vm,
                        arity,
                    )
                } else {
                    fallback(this, vm, name, arity)
                }
            }
        });

        let loaded = ty.seal(guard);

        RuntimeStruct {
            loaded,
            functions,
            fields: self.fields.clone(),
        }
    }
}

impl Accessable<BitcodeFunction> {
    fn to_function(
        &self,
        guard: &CollectionGuard<'_>,
        module: ModuleId,
    ) -> Accessable<Rooted<Function>> {
        Accessable {
            access: self.access,
            accessable: Rooted::new(self.accessable.to_function(guard).in_module(module), guard),
        }
    }
}

/// A loaded Muse-defined type.
#[derive(Debug, Clone)]
pub struct RuntimeStruct {
    loaded: TypeRef,
    functions: Map<Symbol, Accessable<Rooted<Function>>>,
    fields: Map<Symbol, Access>,
}

impl RuntimeStruct {
    /// Converts this type back into a [`BitcodeStruct`].
    #[must_use]
    pub fn to_bitcode_type(&self, guard: &CollectionGuard<'_>) -> BitcodeStruct {
        BitcodeStruct {
            name: self.loaded.name.clone(),
            functions: self
                .functions
                .iter()
                .map(|field| {
                    (
                        field.key().clone(),
                        Accessable {
                            access: field.value.access,
                            accessable: BitcodeFunction::from_function(
                                &field.value.accessable,
                                guard,
                            ),
                        },
                    )
                })
                .collect(),
            fields: self.fields.clone(),
        }
    }
}

impl CustomType for RuntimeStruct {
    fn muse_type(&self) -> &TypeRef {
        &self.loaded
    }
}

impl ContainsNoRefs for RuntimeStruct {}

#[derive(Debug, Trace)]
struct StructInstance {
    ty: TypeRef,
    fields: Map<SymbolRef, Accessable<Value>>,
}

impl CustomType for StructInstance {
    fn muse_type(&self) -> &TypeRef {
        &self.ty
    }
}

/// An IR representation of an enum definition.
#[derive(PartialEq, Clone, Debug, Serialize, Deserialize)]
pub struct BitcodeEnum {
    /// The name of this enum.
    pub name: Symbol,
    /// The variants defined in this enum.
    pub variants: Vec<EnumVariant<ValueOrSource>>,
}

impl BitcodeEnum {
    pub(crate) fn load(&self, vm: &VmContext<'_, '_>) -> Result<RuntimeEnum, Fault> {
        let instance = Type::new(self.name.clone())
            .with_total_cmp(|fallback| {
                move |this, vm, rhs| {
                    if let (Some(lhs), Some(rhs)) = (
                        this.downcast_ref::<VariantInstance>(vm.guard()),
                        rhs.as_downcast_ref::<VariantInstance>(vm.guard()),
                    ) {
                        let lhs = lhs.value;
                        let rhs = rhs.value;
                        lhs.total_cmp(vm, &rhs)
                    } else {
                        fallback(this, vm, rhs)
                    }
                }
            })
            .seal(vm.guard());

        let mut variants = Vec::with_capacity(self.variants.len());
        let mut variants_by_name = Map::with_capacity(self.variants.len());

        for (index, variant) in self.variants.iter().enumerate() {
            variants_by_name.insert(variant.name.clone(), index);
            variants.push(EnumVariant {
                name: variant.name.clone(),
                value: Value::dynamic(
                    VariantInstance {
                        ty: instance.clone(),
                        name: variant.name.clone(),
                        value: variant.value.load(vm)?,
                    },
                    vm.guard(),
                ),
            });
        }

        // TODO the type name for the type itself should probably be distinctive.
        let ty = Type::new(self.name.clone()).with_invoke(|fallback| {
            let variants = variants.clone();
            let variants_by_name = variants_by_name.clone();
            move |this, vm, name, arity| {
                if name == Symbol::get_symbol() && arity == 1 {
                    let Some(field_name) = vm[Register(0)].as_symbol_ref() else {
                        return Err(Fault::ExpectedSymbol);
                    };
                    Ok(variants[*variants_by_name
                        .get(field_name)
                        .ok_or(Fault::UnknownSymbol)?]
                    .value)
                } else {
                    fallback(this, vm, name, arity)
                }
            }
        });

        let ty = ty.seal(vm.guard());

        Ok(RuntimeEnum {
            ty,
            variants,
            variants_by_name,
        })
    }
}

/// A Muse enum definition.
#[derive(Debug, Trace, Clone)]
pub struct RuntimeEnum {
    ty: TypeRef,
    variants: Vec<EnumVariant<Value>>,
    variants_by_name: Map<Symbol, usize>,
}

impl RuntimeEnum {
    #[cfg(feature = "dispatched")]
    pub(crate) fn to_bitcode_type(&self, guard: &CollectionGuard) -> BitcodeEnum {
        BitcodeEnum {
            name: self.ty.name.clone(),
            variants: self
                .variants
                .iter()
                .map(|v| EnumVariant {
                    name: v.name.clone(),
                    value: v.value.as_source(guard),
                })
                .collect(),
        }
    }
}

impl CustomType for RuntimeEnum {
    fn muse_type(&self) -> &TypeRef {
        &self.ty
    }
}

/// A variant of an enum.
#[derive(PartialEq, Clone, Debug, Serialize, Deserialize, Trace)]
pub struct EnumVariant<T> {
    /// The name of the variant.
    pub name: Symbol,
    /// The value of the variant.
    pub value: T,
}

#[derive(Debug, Trace)]
struct VariantInstance {
    ty: TypeRef,
    name: Symbol,
    value: Value,
}

impl CustomType for VariantInstance {
    fn muse_type(&self) -> &TypeRef {
        &self.ty
    }
}