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
use std::collections::HashMap;

use crate::chunk::ModuleChunk;
use serde::{Deserialize, Serialize};

use crate::native::NativeFn;
use crate::vm::{VMState, VM};

#[derive(Debug, Clone, Serialize, Deserialize)]
pub enum Value {
    Float(f32),
    Long(i64),
    Bool(bool),
    Nil,
    PhoenixString(String),
    PhoenixList(usize),
    // Index of the function in the functions Vec in VM // Fixme: Is this even reachable? Can this be completely removed and the parameter put in OpClosure?
    PhoenixFunction(usize),
    #[serde(skip)]
    NativeFunction(Option<usize>, NativeFn),
    PhoenixClass(usize),
    // similar to class, but for modules
    PhoenixModule(usize),
    PhoenixPointer(usize),
    PhoenixBoundMethod(ObjBoundMethod),
}

impl Eq for Value {}

impl PartialEq for Value {
    fn eq(&self, other: &Self) -> bool {
        values_equal((self, other))
    }
}

#[derive(Debug, Clone, Serialize, Deserialize, Default)]
pub struct ValueArray {
    pub values: Vec<Value>,
}

impl ValueArray {
    pub fn new() -> ValueArray {
        ValueArray { values: Vec::new() }
    }

    pub fn write(&mut self, value: Value) {
        self.values.push(value);
    }

    pub fn free(&mut self) {
        self.values.clear();
    }
}

impl Value {
    /// Used for print statements, use {:?} debug formatting for trace and stack examining
    pub fn to_string(&self, vm: &VM, state: &VMState, modules: &Vec<ModuleChunk>) -> String {
        match self {
            Value::Float(x) => format!("{}", x),
            Value::Long(x) => format!("{}", x),
            Value::Bool(x) => format!("{}", x),
            Value::PhoenixString(x) => x.to_string(),
            Value::PhoenixList(x) => state.deref(*x).to_string(vm, state, modules),
            Value::Nil => String::from("nil"),
            Value::PhoenixFunction(x) => format!(
                "<fn {}>",
                &modules[state.current_frame.module]
                    .functions
                    .get(*x)
                    .unwrap()
                    .name
                    .as_ref()
                    .unwrap()
            ),
            Value::NativeFunction(_x, _) => "<native_fn>".to_string(),
            Value::PhoenixClass(class) => format!("<class {}>", class),
            Value::PhoenixPointer(pointer) => {
                // hacky way to check if this is a list
                if let HeapObjVal::PhoenixList(_) = &state.deref(*pointer).obj {
                    state.deref(*pointer).to_string(vm, state, modules)
                } else {
                    format!(
                        "<pointer {}> to {}",
                        pointer,
                        state.deref(*pointer).to_string(vm, state, modules)
                    )
                }
            } // Suggestion: Don't reveal to the user the internals?
            Value::PhoenixBoundMethod(method) => format!(
                "<method {} from {}",
                &modules[state.current_frame.module]
                    .functions
                    .get(method.method)
                    .unwrap()
                    .name
                    .as_ref()
                    .unwrap(),
                state.deref(method.pointer).to_string(vm, state, modules)
            ),
            Value::PhoenixModule(module) => format!("<module {}>", module),
        }
    }

    pub fn as_float(&self) -> Option<f32> {
        if let Value::Float(val) = self {
            Some(*val)
        } else if let Value::Long(val) = self {
            Some(*val as f32)
        } else {
            None
        }
    }

    pub fn as_long(&self) -> Option<i64> {
        if let Value::Long(val) = self {
            Some(*val)
        } else if let Value::Float(val) = self {
            Some(*val as i64)
        } else {
            None
        }
    }

    pub fn as_bool(&self) -> Option<bool> {
        match self {
            Value::Bool(val) => Some(*val),
            Value::Long(val) => Some(*val != 0),
            Value::Float(val) => Some(*val != 0.0),
            _ => None,
        }
    }

    pub fn as_string(&self) -> Option<&String> {
        if let Value::PhoenixString(val) = self {
            Some(val)
        } else {
            None
        }
    }

    /// Hard cast to a ObjPointer. Panics if this value is not a PhoenixPointer
    pub fn as_pointer(&self) -> usize {
        if let Value::PhoenixPointer(ptr) = self {
            *ptr
        } else {
            panic!(
                "VM panic! Failed to cast value to a pointer. Found {:?} instead",
                self
            )
        }
    }
}

pub fn is_falsey(val: &Value) -> bool {
    matches!(val, Value::Bool(false) | Value::Nil)
}

pub fn values_equal(t: (&Value, &Value)) -> bool {
    match t {
        (Value::Float(x), Value::Float(y)) => x == y,
        (Value::Long(x), Value::Long(y)) => x == y,
        (Value::Bool(x), Value::Bool(y)) => x == y,
        (Value::Nil, Value::Nil) => true,
        (Value::PhoenixString(x), Value::PhoenixString(y)) => x.eq(y),
        (Value::PhoenixPointer(x), Value::PhoenixPointer(y)) => x == y,
        (Value::PhoenixClass(x), Value::PhoenixClass(y)) => x == y,
        (Value::PhoenixFunction(x), Value::PhoenixFunction(y)) => x == y,
        (Value::NativeFunction(x, x2), Value::NativeFunction(y, y2)) => x == y && x2 == y2,
        (Value::PhoenixBoundMethod(x), Value::PhoenixBoundMethod(y)) => x == y,
        _ => false,
    }
}

#[derive(Debug, Clone, Copy, PartialEq, Serialize, Deserialize, Ord, PartialOrd, Eq)]
pub struct ObjBoundMethod {
    pub method: usize,
    // Index into the functions vec for which function to call
    pub pointer: usize, // Pointer to the PhoenixInstance that this method is bound to
}

// End of stack/implicit copy objects

// Heap Objects

#[derive(Debug, Clone, Copy, PartialEq, Serialize, Deserialize)]
pub enum HeapObjType {
    HeapPlaceholder,
    PhoenixInstance,
    PhoenixClosure,
    PhoenixList,
}

#[derive(Debug, PartialEq, Serialize, Deserialize, Clone)]
pub struct HeapObj {
    pub obj: HeapObjVal,
    pub obj_type: HeapObjType,
    pub is_marked: bool,
}

impl HeapObj {
    fn to_string(&self, vm: &VM, state: &VMState, modules: &Vec<ModuleChunk>) -> String {
        self.obj.to_string(vm, state, modules)
    }

    pub fn new_instance(val: ObjInstance) -> HeapObj {
        HeapObj {
            obj: HeapObjVal::PhoenixInstance(val),
            obj_type: HeapObjType::PhoenixInstance,
            is_marked: false,
        }
    }

    pub fn new_closure(val: ObjClosure) -> HeapObj {
        HeapObj {
            obj: HeapObjVal::PhoenixClosure(val),
            obj_type: HeapObjType::PhoenixClosure,
            is_marked: false,
        }
    }

    pub fn new_placeholder() -> HeapObj {
        HeapObj {
            obj: HeapObjVal::HeapPlaceholder,
            obj_type: HeapObjType::HeapPlaceholder,
            is_marked: false,
        }
    }

    pub fn new_list(val: ObjList) -> HeapObj {
        HeapObj {
            obj: HeapObjVal::PhoenixList(val),
            obj_type: HeapObjType::PhoenixList,
            is_marked: false,
        }
    }
}

// I swear i really tried to not have this be duplicate with HeapObjType, but couldn't figure out a way to do it
#[derive(Debug, PartialEq, Serialize, Deserialize, Clone)]
pub enum HeapObjVal {
    HeapPlaceholder,
    PhoenixInstance(ObjInstance),
    PhoenixClosure(ObjClosure),
    // PhoenixString(String), // Maybe...
    PhoenixList(ObjList),
}

impl HeapObjVal {
    fn to_string(&self, vm: &VM, state: &VMState, modules: &Vec<ModuleChunk>) -> String {
        match self {
            HeapObjVal::PhoenixClosure(closure) => format!(
                "<fn {} | {:?}>",
                &modules[state.current_frame.module]
                    .functions
                    .get(closure.function)
                    .unwrap()
                    .name
                    .as_ref()
                    .unwrap(),
                closure
            ),
            HeapObjVal::PhoenixInstance(instance) => format!(
                "<instance {}>",
                &modules[state.current_frame.module]
                    .classes
                    .get(instance.class)
                    .unwrap()
                    .name
            ),
            HeapObjVal::PhoenixList(list) => format!(
                "[{}]",
                list.values
                    .iter()
                    .map(|x| x.to_string(vm, state, modules))
                    .collect::<Vec<String>>()
                    .join(", ")
            ),
            HeapObjVal::HeapPlaceholder => {
                panic!("VM panic! How did a placeholder value get here?")
            }
        }
    }

    pub fn as_closure(&self) -> &ObjClosure {
        if let HeapObjVal::PhoenixClosure(closure) = self {
            closure
        } else {
            panic!("VM panic!")
        }
    }

    pub fn as_closure_mut(&mut self) -> &mut ObjClosure {
        if let HeapObjVal::PhoenixClosure(closure) = self {
            closure
        } else {
            panic!("VM panic!")
        }
    }

    pub fn as_instance(&self) -> &ObjInstance {
        if let HeapObjVal::PhoenixInstance(instance) = self {
            instance
        } else {
            panic!("VM panic!")
        }
    }

    pub fn as_instance_mut(&mut self) -> &mut ObjInstance {
        if let HeapObjVal::PhoenixInstance(instance) = self {
            instance
        } else {
            panic!("VM panic!")
        }
    }

    pub fn as_list_mut(&mut self) -> &mut ObjList {
        if let HeapObjVal::PhoenixList(list) = self {
            list
        } else {
            panic!("VM panic!")
        }
    }
}

/// Runtime instantiation of class definitions
#[derive(Debug, PartialEq, Serialize, Deserialize, Clone)]
pub struct ObjInstance {
    pub class: usize,
    // Which class was this instance made from?
    pub fields: HashMap<usize, Value>, // Stores the field values. FunctionChunks are stored in the ClassChunk, which is not ideal since it adds an extra vec lookup before getting to the function
}

impl ObjInstance {
    pub fn new(class: usize) -> ObjInstance {
        ObjInstance {
            class,
            fields: HashMap::new(),
        }
    }
}

/// Runtime representation of the closure, ie what variables are in scope
#[derive(Debug, PartialEq, Serialize, Deserialize, Clone)]
pub struct ObjClosure {
    pub function: usize,
    pub values: Vec<Value>, // Will be filled at runtime
}

impl ObjClosure {
    pub fn new(function: usize) -> ObjClosure {
        ObjClosure {
            function,
            values: Vec::new(),
        }
    }
}

/// Runtime representation of a list
#[derive(Debug, PartialEq, Serialize, Deserialize, Clone)]
pub struct ObjList {
    pub values: Vec<Value>,
}

impl ObjList {
    pub fn new(v: Vec<Value>) -> ObjList {
        ObjList { values: v }
    }
}