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
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
//! Dynamically typed values.
//!
//! This module abstracts platform specifics such as NaN boxing away into a common interface.

mod closures;
mod dicts;
mod impls;
mod lists;
mod structs;
mod traits;

use std::{any::Any, borrow::Cow, cmp::Ordering, fmt, fmt::Write, marker::PhantomData, ops::Deref};

pub use closures::*;
pub use dicts::*;
use impls::ValueImpl;
pub use lists::*;
pub use structs::*;
pub use traits::*;

use crate::ll::{bytecode::DispatchTable, error::LanguageErrorKind, gc::GcRaw};

/// The kind of a [`RawValue`].
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum ValueKind {
    Nil,
    Boolean,
    Number,
    String,
    Function,
    Struct,
    Trait,
    List,
    Dict,
    UserData,
}

/// Common interface each `ValueImpl` must implement.
trait ValueCommon: Clone + PartialEq {
    fn new_nil() -> Self;
    fn new_boolean(b: bool) -> Self;
    fn new_number(n: f64) -> Self;
    fn new_string(s: GcRaw<String>) -> Self;
    fn new_function(f: GcRaw<Closure>) -> Self;
    fn new_struct(s: GcRaw<Struct>) -> Self;
    fn new_trait(s: GcRaw<Trait>) -> Self;
    fn new_list(s: GcRaw<List>) -> Self;
    fn new_dict(d: GcRaw<Dict>) -> Self;
    fn new_user_data(u: GcRaw<Box<dyn UserData>>) -> Self;

    fn kind(&self) -> ValueKind;

    unsafe fn get_boolean_unchecked(&self) -> bool;
    // This returns a reference such that mica-hl can use `f64` as a `self` parameter in methods.
    unsafe fn get_number_unchecked(&self) -> &f64;
    unsafe fn get_raw_string_unchecked(&self) -> GcRaw<String>;
    unsafe fn get_raw_function_unchecked(&self) -> GcRaw<Closure>;
    unsafe fn get_raw_struct_unchecked(&self) -> GcRaw<Struct>;
    unsafe fn get_raw_trait_unchecked(&self) -> GcRaw<Trait>;
    unsafe fn get_raw_list_unchecked(&self) -> GcRaw<List>;
    unsafe fn get_raw_dict_unchecked(&self) -> GcRaw<Dict>;
    unsafe fn get_raw_user_data_unchecked(&self) -> GcRaw<Box<dyn UserData>>;
}

fn _check_implementations() {
    fn check_value<T: ValueCommon>() {}
    check_value::<ValueImpl>();
}

/// An **unsafe** value used internally in the VM.
///
/// Does not provide any safety guarantees as to GC'd object lifetimes.
/// You almost always want [`Value`][crate::Value] instead of this.
#[derive(Clone, Copy, PartialEq)]
#[repr(transparent)]
pub struct RawValue(ValueImpl, PhantomData<*const ()>);

impl RawValue {
    /// Returns the kind of value stored.
    pub fn kind(&self) -> ValueKind {
        self.0.kind()
    }

    fn type_name(&self) -> Cow<'static, str> {
        match self.0.kind() {
            ValueKind::Nil => "Nil".into(),
            ValueKind::Boolean => "Boolean".into(),
            ValueKind::Number => "Number".into(),
            ValueKind::String => "String".into(),
            ValueKind::Function => "Function".into(),
            ValueKind::List => "List".into(),
            ValueKind::Dict => "Dict".into(),
            ValueKind::Struct => unsafe { self.0.get_raw_struct_unchecked().get().dtable() }
                .type_name
                .deref()
                .to_owned()
                .into(),
            ValueKind::Trait => unsafe { self.0.get_raw_trait_unchecked().get().dtable() }
                .type_name
                .deref()
                .to_owned()
                .into(),
            ValueKind::UserData => unsafe { self.0.get_raw_user_data_unchecked().get().dtable() }
                .type_name
                .deref()
                .to_owned()
                .into(),
        }
    }

    fn type_error(&self, expected: &'static str) -> LanguageErrorKind {
        LanguageErrorKind::TypeError { expected: Cow::from(expected), got: self.type_name() }
    }

    /// Returns a boolean value without performing any checks.
    ///
    /// # Safety
    /// Calling this on a value that isn't known to be a boolean is undefined behavior.
    pub unsafe fn get_boolean_unchecked(&self) -> bool {
        self.0.get_boolean_unchecked()
    }

    /// Returns a number value without performing any checks.
    ///
    /// # Safety
    /// Calling this on a value that isn't known to be a number is undefined behavior.
    pub unsafe fn get_number_unchecked(&self) -> &f64 {
        self.0.get_number_unchecked()
    }

    /// Returns a string value without performing any checks.
    ///
    /// # Safety
    /// Calling this on a value that isn't known to be a string is undefined behavior.
    pub unsafe fn get_raw_string_unchecked(&self) -> GcRaw<String> {
        self.0.get_raw_string_unchecked()
    }

    /// Returns a function value without performing any checks.
    ///
    /// # Safety
    /// Calling this on a value that isn't known to be a function is undefined behavior.
    pub unsafe fn get_raw_function_unchecked(&self) -> GcRaw<Closure> {
        self.0.get_raw_function_unchecked()
    }

    /// Returns a struct value without performing any checks.
    ///
    /// # Safety
    /// Calling this on a value that isn't known to be a struct is undefined behavior.
    pub unsafe fn get_raw_struct_unchecked(&self) -> GcRaw<Struct> {
        self.0.get_raw_struct_unchecked()
    }

    /// Returns a trait value without performing any checks.
    ///
    /// # Safety
    /// Calling this on a value that isn't known to be a trait is undefined behavior.
    pub unsafe fn get_raw_trait_unchecked(&self) -> GcRaw<Trait> {
        self.0.get_raw_trait_unchecked()
    }

    /// Returns a list value without performing any checks.
    ///
    /// # Safety
    /// Calling this on a value that isn't known to be a list is undefined behavior.
    pub unsafe fn get_raw_list_unchecked(&self) -> GcRaw<List> {
        self.0.get_raw_list_unchecked()
    }

    /// Returns a dict value without performing any checks.
    ///
    /// # Safety
    /// Calling this on a value that isn't known to be a dict is undefined behavior.
    pub unsafe fn get_raw_dict_unchecked(&self) -> GcRaw<Dict> {
        self.0.get_raw_dict_unchecked()
    }

    /// Returns a user data value without performing any checks.
    ///
    /// # Safety
    /// Calling this on a value that isn't known to be a user data is undefined behavior.
    pub unsafe fn get_raw_user_data_unchecked(&self) -> GcRaw<Box<dyn UserData>> {
        self.0.get_raw_user_data_unchecked()
    }

    /// Ensures the value is a `Nil`, returning a type mismatch error if that's not the case.
    pub fn ensure_nil(&self) -> Result<(), LanguageErrorKind> {
        if self.0.kind() == ValueKind::Nil {
            Ok(())
        } else {
            Err(self.type_error("Nil"))
        }
    }

    /// Ensures the value is a `Boolean`, returning a type mismatch error if that's not the case.
    pub fn ensure_boolean(&self) -> Result<bool, LanguageErrorKind> {
        if self.0.kind() == ValueKind::Boolean {
            Ok(unsafe { self.0.get_boolean_unchecked() })
        } else {
            Err(self.type_error("Boolean"))
        }
    }

    /// Ensures the value is a `Number`, returning a type mismatch error if that's not the case.
    pub fn ensure_number(&self) -> Result<f64, LanguageErrorKind> {
        if self.0.kind() == ValueKind::Number {
            Ok(unsafe { *self.0.get_number_unchecked() })
        } else {
            Err(self.type_error("Number"))
        }
    }

    /// Ensures the value is a `String`, returning a type mismatch error if that's not the case.
    pub fn ensure_raw_string(&self) -> Result<GcRaw<String>, LanguageErrorKind> {
        if self.0.kind() == ValueKind::String {
            Ok(unsafe { self.0.get_raw_string_unchecked() })
        } else {
            Err(self.type_error("String"))
        }
    }

    /// Ensures the value is a `Function`, returning a type mismatch error if that's not the case.
    pub fn ensure_raw_function(&self) -> Result<GcRaw<Closure>, LanguageErrorKind> {
        if self.0.kind() == ValueKind::Function {
            Ok(unsafe { self.0.get_raw_function_unchecked() })
        } else {
            Err(self.type_error("Function"))
        }
    }

    /// Ensures the value is a `Struct`, returning a type mismatch error if that's not the case.
    pub fn ensure_raw_struct(&self) -> Result<GcRaw<Struct>, LanguageErrorKind> {
        if self.0.kind() == ValueKind::Struct {
            Ok(unsafe { self.0.get_raw_struct_unchecked() })
        } else {
            Err(self.type_error("any struct"))
        }
    }

    /// Ensures the value is a `Trait`, returning a type mismatch error if that's not the case.
    pub fn ensure_raw_trait(&self) -> Result<GcRaw<Trait>, LanguageErrorKind> {
        if self.0.kind() == ValueKind::Trait {
            Ok(unsafe { self.0.get_raw_trait_unchecked() })
        } else {
            Err(self.type_error("any trait"))
        }
    }

    /// Ensures the value is a `UserData` of the given type `T`, returning a type mismatch error
    /// that's not the case.
    pub fn get_raw_user_data<T>(&self) -> Option<GcRaw<Box<dyn UserData>>>
    where
        T: UserData,
    {
        if self.0.kind() == ValueKind::UserData {
            Some(unsafe { self.0.get_raw_user_data_unchecked() })
        } else {
            None
        }
    }

    /// Returns whether the value is truthy. All values except `Nil` and `False` are truthy.
    pub fn is_truthy(&self) -> bool {
        !self.is_falsy()
    }

    /// Returns whether the values is falsy. The only falsy values are `Nil` and `False`.
    pub fn is_falsy(&self) -> bool {
        self.0.kind() == ValueKind::Nil
            || (self.0.kind() == ValueKind::Boolean && unsafe { !self.0.get_boolean_unchecked() })
    }

    /// Attempts to partially compare this value with another one.
    ///
    /// Returns an error if the types of the two values are not the same.
    pub fn try_partial_cmp(&self, other: &Self) -> Result<Option<Ordering>, LanguageErrorKind> {
        if self.0.kind() != other.0.kind() {
            Err(LanguageErrorKind::TypeError { expected: self.type_name(), got: other.type_name() })
        } else {
            match self.0.kind() {
                ValueKind::Nil => Ok(Some(Ordering::Equal)),
                ValueKind::Boolean => {
                    let a = unsafe { self.0.get_boolean_unchecked() };
                    let b = unsafe { other.0.get_boolean_unchecked() };
                    Ok(Some(a.cmp(&b)))
                }
                ValueKind::Number => {
                    let a = unsafe { self.0.get_number_unchecked() };
                    let b = unsafe { other.0.get_number_unchecked() };
                    Ok(a.partial_cmp(b))
                }
                ValueKind::String => unsafe {
                    let a = self.0.get_raw_string_unchecked();
                    let b = other.0.get_raw_string_unchecked();
                    Ok(Some(a.get().cmp(b.get())))
                },
                ValueKind::Function => Ok(None),
                ValueKind::Struct => Ok(None),
                ValueKind::Trait => Ok(None),
                ValueKind::List => unsafe {
                    let a = self.0.get_raw_list_unchecked();
                    let b = other.0.get_raw_list_unchecked();
                    a.get().try_partial_cmp(b.get())
                },
                ValueKind::Dict => todo!(),
                ValueKind::UserData => Ok(None),
            }
        }
    }
}

impl Default for RawValue {
    fn default() -> Self {
        Self(ValueImpl::new_nil(), PhantomData)
    }
}

impl From<()> for RawValue {
    fn from(_: ()) -> Self {
        Self(ValueImpl::new_nil(), PhantomData)
    }
}

impl From<bool> for RawValue {
    fn from(b: bool) -> Self {
        Self(ValueImpl::new_boolean(b), PhantomData)
    }
}

impl From<f64> for RawValue {
    fn from(x: f64) -> Self {
        Self(ValueImpl::new_number(x), PhantomData)
    }
}

impl From<GcRaw<String>> for RawValue {
    fn from(s: GcRaw<String>) -> Self {
        Self(ValueImpl::new_string(s), PhantomData)
    }
}

impl From<GcRaw<Closure>> for RawValue {
    fn from(f: GcRaw<Closure>) -> Self {
        Self(ValueImpl::new_function(f), PhantomData)
    }
}

impl From<GcRaw<Struct>> for RawValue {
    fn from(s: GcRaw<Struct>) -> Self {
        Self(ValueImpl::new_struct(s), PhantomData)
    }
}

impl From<GcRaw<Trait>> for RawValue {
    fn from(t: GcRaw<Trait>) -> Self {
        Self(ValueImpl::new_trait(t), PhantomData)
    }
}

impl From<GcRaw<List>> for RawValue {
    fn from(s: GcRaw<List>) -> Self {
        Self(ValueImpl::new_list(s), PhantomData)
    }
}

impl From<GcRaw<Dict>> for RawValue {
    fn from(s: GcRaw<Dict>) -> Self {
        Self(ValueImpl::new_dict(s), PhantomData)
    }
}

impl From<GcRaw<Box<dyn UserData>>> for RawValue {
    fn from(u: GcRaw<Box<dyn UserData>>) -> Self {
        Self(ValueImpl::new_user_data(u), PhantomData)
    }
}

impl fmt::Debug for RawValue {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        fn dtable(f: &mut fmt::Formatter, dtable: &DispatchTable) -> fmt::Result {
            let type_name = &dtable.pretty_name;
            write!(f, "<[{type_name}]>")
        }

        unsafe {
            match self.0.kind() {
                ValueKind::Nil => f.write_str("nil"),
                ValueKind::Boolean => write!(f, "{}", self.0.get_boolean_unchecked()),
                ValueKind::Number => write!(f, "{}", self.0.get_number_unchecked()),
                ValueKind::String => {
                    write!(f, "{:?}", self.0.get_raw_string_unchecked().get().deref())
                }
                ValueKind::Function => {
                    write!(f, "<func {:?}>", self.0.get_raw_function_unchecked().get_raw())
                }
                ValueKind::List => {
                    f.write_char('[')?;
                    let list = self.0.get_raw_list_unchecked();
                    let elements = list.get().as_slice();
                    for (i, element) in elements.iter().enumerate() {
                        if i != 0 {
                            f.write_str(", ")?;
                        }
                        fmt::Debug::fmt(element, f)?;
                    }
                    f.write_char(']')?;
                    Ok(())
                }
                ValueKind::Dict => {
                    let dict = self.0.get_raw_dict_unchecked();
                    let dict = dict.get();
                    if dict.is_empty() {
                        f.write_str("[:]")?;
                    } else {
                        f.write_char('[')?;
                        for (i, (key, value)) in dict.iter().enumerate() {
                            if i != 0 {
                                f.write_str(", ")?;
                            }
                            fmt::Debug::fmt(&key, f)?;
                            f.write_str(": ")?;
                            fmt::Debug::fmt(&value, f)?;
                        }
                        f.write_char(']')?;
                    }
                    Ok(())
                }
                ValueKind::Struct => dtable(f, self.0.get_raw_struct_unchecked().get().dtable()),
                ValueKind::Trait => dtable(f, self.0.get_raw_trait_unchecked().get().dtable()),
                ValueKind::UserData => {
                    dtable(f, self.0.get_raw_user_data_unchecked().get().dtable())
                }
            }
        }
    }
}

impl fmt::Display for RawValue {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        unsafe {
            match self.0.kind() {
                ValueKind::String => write!(f, "{}", self.0.get_raw_string_unchecked().get()),
                _ => fmt::Debug::fmt(&self, f),
            }
        }
    }
}

pub trait UserData: Any {
    /// Returns a GC reference to the user data's dispatch table.
    fn dtable_gcraw(&self) -> GcRaw<DispatchTable>;

    /// Returns the user data's dispatch table.
    ///
    /// # Safety
    /// This is basically sugar for `dtable_gcraw().get()`, so all the footguns of [`GcRaw::get`]
    /// apply.
    unsafe fn dtable(&self) -> &DispatchTable {
        self.dtable_gcraw().get()
    }

    fn visit_references(&self, _visit: &mut dyn FnMut(RawValue)) {}

    fn as_any(&self) -> &dyn Any;
}