~starkingdoms/starkingdoms

ref: 87db7538d05166cb8cdb701886b38b32de9bc708 starkingdoms/crates/kabel/src/vm.rs -rw-r--r-- 34.9 KiB
87db7538 — core cargo fmt 8 months ago
                                                                                
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
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
use crate::vm_error;
use crate::{
    runtime_error::{KabelRuntimeError, RuntimeErrorKind},
    vm_boolean_comparison, vm_boolean_equality,
};

#[derive(Debug, Clone)]
pub struct Unit {
    pub code: Vec<u8>,
    pub pool: Vec<Value>,
    pub lines: Vec<(usize, usize)>, // line #, repeats number of instructions
}
impl Unit {
    pub fn new(code: Vec<u8>, pool: Vec<Value>, lines: Vec<(usize, usize)>) -> Self {
        Self { code, pool, lines }
    }
    pub fn new_empty() -> Self {
        Self {
            code: Vec::new(),
            pool: Vec::new(),
            lines: Vec::new(),
        }
    }
}

#[derive(Clone)]
pub struct VM {
    pub ip: usize,
    pub unit_ptr: usize,
    pub call_stack: Vec<(usize, usize, usize)>, // (unit_ptr, ip, stack_offset)
    pub units: Vec<Unit>,
    pub stack: Vec<Value>,
    pub variables: Vec<Value>,
    pub variables_offset: usize,
    text: Vec<String>,
}

impl VM {
    pub fn new(
        bytecode: Vec<u8>,
        lines: Vec<(usize, usize)>,
        pool: Vec<Value>,
        text: String,
    ) -> Self {
        Self {
            ip: 0,
            unit_ptr: 0,
            call_stack: vec![(0, 0, 0)],
            units: vec![Unit::new(bytecode, pool, lines)],
            stack: Vec::new(),
            variables: Vec::new(),
            variables_offset: 0,
            text: text.lines().map(|s| s.to_string()).collect::<Vec<String>>(),
        }
    }
    pub fn run(&mut self, output: &mut String) -> Result<(), KabelRuntimeError> {
        use Value::*;
        while self.ip < self.units[self.unit_ptr].code.len() {
            match self.read() {
                0x00 => {
                    // LOAD
                    let byte = self.read() as usize;
                    println!("ip: {}", self.ip);
                    let value = self.units[self.unit_ptr].pool[byte].clone();
                    self.stack.push(value);
                }
                0x01 => {
                    // VAR
                    let ptr = self.read() as usize;
                    let value = self.variables[ptr + self.variables_offset].clone();
                    self.stack.push(value);
                }
                0x02 => {
                    // REF
                    let ptr = self.read() as usize;
                    self.stack.push(Ref(ptr));
                }
                0x03 => {
                    // ASN
                    let value = self.stack.pop().unwrap();
                    let ptr = self.read();
                    let offset = self.call_stack.last().expect("var call stack last").2;
                    self.variables[ptr as usize + offset] = value.clone();
                    self.stack.push(value);
                }
                0x04 => {
                    // ASNARR
                    let listref = self.stack.pop().unwrap();
                    let index = self.stack.pop().unwrap();
                    let value = self.stack.pop().unwrap();
                    if let Value::Num(index) = index {
                        if index.fract() != 0.0 {
                            return Err(vm_error!(
                                self,
                                RuntimeErrorKind::WrongType,
                                "Subscript index must be an integer but found {}",
                                index
                            ));
                        }
                        let index = index as usize;
                        if let Value::Ref(listref) = listref {
                            let list = &mut self.variables[listref];
                            if let Value::List(ref mut list) = list {
                                let len = list.len();
                                if index > len {
                                    return Err(vm_error!(
                                        self,
                                        RuntimeErrorKind::ArrayOutOfBounds,
                                        "List length is {} but found index {}",
                                        len,
                                        index
                                    ));
                                }
                                println!("index: {}", index);
                                list[index] = value.clone();
                                self.stack.push(value);
                            } else {
                                let type_str = list.type_str();
                                return Err(vm_error!(
                                    self,
                                    RuntimeErrorKind::WrongType,
                                    "Tried to subscript non-list type {}",
                                    type_str
                                ));
                            }
                        } else {
                            panic!("Something went wrong in kabel, listref was not a Ref");
                        }
                    } else {
                        return Err(vm_error!(
                            self,
                            RuntimeErrorKind::WrongType,
                            "Tried to use non-integer type {} to subscript list",
                            index.type_str()
                        ));
                    }
                }
                0x05 => {
                    // DECL
                    let value = self.stack.pop().unwrap();
                    self.variables.push(value);
                }
                0x06 => {
                    // ADD
                    match (self.stack.pop().unwrap(), self.stack.pop().unwrap()) {
                        (Num(v1), Num(v2)) => self.stack.push(Num(v1 + v2)),
                        (Str(v1), Str(v2)) => {
                            self.stack.push(Str(v1.clone() + &v2));
                        }
                        (Bool(_v1), Bool(_v2)) => {
                            return Err(vm_error!(
                                self,
                                RuntimeErrorKind::WrongType,
                                "Cannot add booleans"
                            ))
                        }
                        (v1, v2) => {
                            return Err(vm_error!(
                                self,
                                RuntimeErrorKind::MismatchedTypes,
                                "Mismatched types: {} and {}",
                                v1.type_str(),
                                v2.type_str()
                            ))
                        }
                    }
                }
                0x07 => {
                    // SUB
                    match (self.stack.pop().unwrap(), self.stack.pop().unwrap()) {
                        (Num(v1), Num(v2)) => self.stack.push(Num(v1 - v2)),
                        (Str(_v1), Str(_v2)) => {
                            return Err(vm_error!(
                                self,
                                RuntimeErrorKind::WrongType,
                                "Cannot subtract strings"
                            ))
                        }
                        (Bool(_v1), Bool(_v2)) => {
                            return Err(vm_error!(
                                self,
                                RuntimeErrorKind::WrongType,
                                "Cannot subtract booleans"
                            ))
                        }
                        (v1, v2) => {
                            return Err(vm_error!(
                                self,
                                RuntimeErrorKind::MismatchedTypes,
                                "Mismatched types: {} and {}",
                                v1.type_str(),
                                v2.type_str()
                            ))
                        }
                    }
                }
                0x08 => {
                    // MUL
                    match (self.stack.pop().unwrap(), self.stack.pop().unwrap()) {
                        (Num(v1), Num(v2)) => self.stack.push(Num(v1 * v2)),
                        (Str(v1), Num(v2)) => {
                            if v2.fract() == 0.0 {
                                self.stack.push(Str(v1.repeat(v2 as usize)));
                            } else {
                                return Err(vm_error!(
                                    self,
                                    RuntimeErrorKind::WrongType,
                                    "Number must be an integer"
                                ));
                            }
                        }
                        (Str(_v1), Str(_v2)) => {
                            return Err(vm_error!(
                                self,
                                RuntimeErrorKind::WrongType,
                                "Cannot multiply strings"
                            ))
                        }
                        (Bool(_v1), Bool(_v2)) => {
                            return Err(vm_error!(
                                self,
                                RuntimeErrorKind::WrongType,
                                "Cannot multiply booleans"
                            ))
                        }
                        (v1, v2) => {
                            return Err(vm_error!(
                                self,
                                RuntimeErrorKind::MismatchedTypes,
                                "Mismatched types: {} and {}",
                                v1.type_str(),
                                v2.type_str()
                            ))
                        }
                    }
                }
                0x09 => {
                    // DIV
                    match (self.stack.pop().unwrap(), self.stack.pop().unwrap()) {
                        (Num(v1), Num(v2)) => self.stack.push(Num(v1 / v2)),
                        (Str(_v1), Str(_v2)) => {
                            return Err(vm_error!(
                                self,
                                RuntimeErrorKind::WrongType,
                                "Cannot divide strings"
                            ))
                        }
                        (Bool(_v1), Bool(_v2)) => {
                            return Err(vm_error!(
                                self,
                                RuntimeErrorKind::WrongType,
                                "Cannot divide booleans"
                            ))
                        }
                        (v1, v2) => {
                            return Err(vm_error!(
                                self,
                                RuntimeErrorKind::MismatchedTypes,
                                "Mismatched types: {} and {}",
                                v1.type_str(),
                                v2.type_str()
                            ))
                        }
                    }
                }
                0x0A => {
                    // MOD
                    match (self.stack.pop().unwrap(), self.stack.pop().unwrap()) {
                        (Num(v1), Num(v2)) => self.stack.push(Num(v1 % v2)),
                        (Str(_v1), Str(_v2)) => {
                            return Err(vm_error!(
                                self,
                                RuntimeErrorKind::WrongType,
                                "Cannot perform modulus on strings"
                            ))
                        }
                        (Bool(_v1), Bool(_v2)) => {
                            return Err(vm_error!(
                                self,
                                RuntimeErrorKind::WrongType,
                                "Cannot perform modulus on booleans"
                            ))
                        }
                        (v1, v2) => {
                            return Err(vm_error!(
                                self,
                                RuntimeErrorKind::MismatchedTypes,
                                "Mismatched types: {} and {}",
                                v1.type_str(),
                                v2.type_str()
                            ))
                        }
                    }
                }
                0x0B => {
                    // BITAND
                    match (self.stack.pop().unwrap(), self.stack.pop().unwrap()) {
                        (Num(v1), Num(v2)) => {
                            if v1.fract() != 0.0 {
                                return Err(vm_error!(
                                    self,
                                    RuntimeErrorKind::WrongType,
                                    "Cannot perform bitwise AND on {}",
                                    v1
                                ));
                            }
                            if v2.fract() != 0.0 {
                                return Err(vm_error!(
                                    self,
                                    RuntimeErrorKind::WrongType,
                                    "Cannot perform bitwise AND on {}",
                                    v2
                                ));
                            }
                            self.stack.push(Num((v1 as u32 & v2 as u32) as f32))
                        }
                        (Str(_v1), Str(_v2)) => {
                            return Err(vm_error!(
                                self,
                                RuntimeErrorKind::WrongType,
                                "Cannot perform bitwise AND on strings"
                            ))
                        }
                        (Bool(_v1), Bool(_v2)) => {
                            return Err(vm_error!(
                                self,
                                RuntimeErrorKind::WrongType,
                                "Cannot perform bitwise AND on booleans"
                            ))
                        }
                        (v1, v2) => {
                            return Err(vm_error!(
                                self,
                                RuntimeErrorKind::MismatchedTypes,
                                "Mismatched types: {} and {}",
                                v1.type_str(),
                                v2.type_str()
                            ))
                        }
                    }
                }
                0x0C => {
                    // BITXOR
                    match (self.stack.pop().unwrap(), self.stack.pop().unwrap()) {
                        (Num(v1), Num(v2)) => {
                            if v1.fract() != 0.0 {
                                return Err(vm_error!(
                                    self,
                                    RuntimeErrorKind::WrongType,
                                    "Cannot perform bitwise XOR on {}",
                                    v1
                                ));
                            }
                            if v2.fract() != 0.0 {
                                return Err(vm_error!(
                                    self,
                                    RuntimeErrorKind::WrongType,
                                    "Cannot perform bitwise XOR on {}",
                                    v2
                                ));
                            }
                            self.stack.push(Num((v1 as u32 ^ v2 as u32) as f32))
                        }
                        (Str(_v1), Str(_v2)) => {
                            return Err(vm_error!(
                                self,
                                RuntimeErrorKind::WrongType,
                                "Cannot perform bitwise XOR on strings"
                            ))
                        }
                        (Bool(_v1), Bool(_v2)) => {
                            return Err(vm_error!(
                                self,
                                RuntimeErrorKind::WrongType,
                                "Cannot perform bitwise XOR on booleans"
                            ))
                        }
                        (v1, v2) => {
                            return Err(vm_error!(
                                self,
                                RuntimeErrorKind::MismatchedTypes,
                                "Mismatched types: {} and {}",
                                v1.type_str(),
                                v2.type_str()
                            ))
                        }
                    }
                }
                0x0D => {
                    // BITOR
                    match (self.stack.pop().unwrap(), self.stack.pop().unwrap()) {
                        (Num(v1), Num(v2)) => {
                            if v1.fract() != 0.0 {
                                return Err(vm_error!(
                                    self,
                                    RuntimeErrorKind::WrongType,
                                    "Cannot perform bitwise OR on {}",
                                    v1
                                ));
                            }
                            if v2.fract() != 0.0 {
                                return Err(vm_error!(
                                    self,
                                    RuntimeErrorKind::WrongType,
                                    "Cannot perform bitwise OR on {}",
                                    v2
                                ));
                            }
                            self.stack.push(Num((v1 as u32 | v2 as u32) as f32))
                        }
                        (Str(_v1), Str(_v2)) => {
                            return Err(vm_error!(
                                self,
                                RuntimeErrorKind::WrongType,
                                "Cannot perform bitwise OR on strings"
                            ))
                        }
                        (Bool(_v1), Bool(_v2)) => {
                            return Err(vm_error!(
                                self,
                                RuntimeErrorKind::WrongType,
                                "Cannot perform bitwise OR on booleans"
                            ))
                        }
                        (v1, v2) => {
                            return Err(vm_error!(
                                self,
                                RuntimeErrorKind::MismatchedTypes,
                                "Mismatched types: {} and {}",
                                v1.type_str(),
                                v2.type_str()
                            ))
                        }
                    }
                }
                // EQ
                0x0E => vm_boolean_equality!(self, ==),
                // NE
                0x0F => vm_boolean_equality!(self, !=),
                // GR
                0x10 => vm_boolean_comparison!(self, >),
                // GE
                0x11 => vm_boolean_comparison!(self, >=),
                // LS
                0x12 => vm_boolean_comparison!(self, <),
                // LE
                0x13 => vm_boolean_comparison!(self, <=),
                // OR
                0x14 => match (self.stack.pop().unwrap(), self.stack.pop().unwrap()) {
                    (Num(_v1), Num(_v2)) => {
                        return Err(vm_error!(
                            self,
                            RuntimeErrorKind::WrongType,
                            "Tried to perform \"||\" on non-boolean numbers"
                        ))
                    }
                    (Str(_v1), Str(_v2)) => {
                        return Err(vm_error!(
                            self,
                            RuntimeErrorKind::WrongType,
                            "Tried to perform \"||\" on non-boolean strings"
                        ))
                    }
                    (Bool(v1), Bool(v2)) => self.stack.push(Bool(v1 || v2)),
                    (Null, _) => {
                        return Err(vm_error!(
                            self,
                            RuntimeErrorKind::WrongType,
                            "Tried to perform \"||\" on non-boolean value null"
                        ))
                    }
                    (_, Null) => {
                        return Err(vm_error!(
                            self,
                            RuntimeErrorKind::WrongType,
                            "Tried to perform \"||\" on non-boolean value null"
                        ))
                    }
                    (v1, v2) => {
                        return Err(vm_error!(
                            self,
                            RuntimeErrorKind::MismatchedTypes,
                            "Mismatched types: {} and {}",
                            v1.type_str(),
                            v2.type_str()
                        ))
                    }
                },
                // AND
                0x15 => match (self.stack.pop().unwrap(), self.stack.pop().unwrap()) {
                    (Num(_v1), Num(_v2)) => {
                        return Err(vm_error!(
                            self,
                            RuntimeErrorKind::WrongType,
                            "Tried to perform \"&&\" on non-boolean numbers"
                        ))
                    }
                    (Str(_v1), Str(_v2)) => {
                        return Err(vm_error!(
                            self,
                            RuntimeErrorKind::WrongType,
                            "Tried to perform \"&&\" on non-boolean strings"
                        ))
                    }
                    (Bool(v1), Bool(v2)) => self.stack.push(Bool(v1 && v2)),
                    (Null, _) => {
                        return Err(vm_error!(
                            self,
                            RuntimeErrorKind::WrongType,
                            "Tried to perform \"&&\" on non-boolean value null"
                        ))
                    }
                    (_, Null) => {
                        return Err(vm_error!(
                            self,
                            RuntimeErrorKind::WrongType,
                            "Tried to perform \"&&\" on non-boolean value null"
                        ))
                    }
                    (v1, v2) => {
                        return Err(vm_error!(
                            self,
                            RuntimeErrorKind::MismatchedTypes,
                            "Mismatched types: {} and {}",
                            v1.type_str(),
                            v2.type_str()
                        ))
                    }
                },
                // NOT
                0x16 => match self.stack.pop().unwrap() {
                    Null => {
                        return Err(vm_error!(
                            self,
                            RuntimeErrorKind::WrongType,
                            "Tried to perform \"!\" on non-boolean value null"
                        ))
                    }
                    Num(_v1) => {
                        return Err(vm_error!(
                            self,
                            RuntimeErrorKind::WrongType,
                            "Tried to perform \"!\" on non-boolean number"
                        ))
                    }
                    Str(_v1) => {
                        return Err(vm_error!(
                            self,
                            RuntimeErrorKind::WrongType,
                            "Tried to perform \"!\" on non-boolean string"
                        ))
                    }
                    Bool(v1) => self.stack.push(Bool(!v1)),
                    List(_v1) => {
                        return Err(vm_error!(
                            self,
                            RuntimeErrorKind::WrongType,
                            "Tried to perform \"!\" on non-boolean list"
                        ))
                    }
                    Fun(_v1) => {
                        return Err(vm_error!(
                            self,
                            RuntimeErrorKind::WrongType,
                            "Tried to perform \"!\" on non-boolean function"
                        ))
                    }
                    Ref(_v1) => {
                        return Err(vm_error!(
                            self,
                            RuntimeErrorKind::WrongType,
                            "Tried to perform \"!\" on non-boolean reference"
                        ))
                    }
                },
                // NEG
                0x17 => match self.stack.pop().unwrap() {
                    Null => {
                        return Err(vm_error!(
                            self,
                            RuntimeErrorKind::WrongType,
                            "Tried to perform \"-\" on non-number value null"
                        ))
                    }
                    Num(v1) => self.stack.push(Num(-v1)),
                    Str(_v1) => {
                        return Err(vm_error!(
                            self,
                            RuntimeErrorKind::WrongType,
                            "Tried to perform \"-\" on non-number string"
                        ))
                    }
                    Bool(_v1) => {
                        return Err(vm_error!(
                            self,
                            RuntimeErrorKind::WrongType,
                            "Tried to perform \"-\" on non-number boolean"
                        ))
                    }
                    List(_v1) => {
                        return Err(vm_error!(
                            self,
                            RuntimeErrorKind::WrongType,
                            "Tried to perform \"!\" on non-number list"
                        ))
                    }
                    Fun(_v1) => {
                        return Err(vm_error!(
                            self,
                            RuntimeErrorKind::WrongType,
                            "Tried to perform \"-\" on non-number function"
                        ))
                    }
                    Ref(_v1) => {
                        return Err(vm_error!(
                            self,
                            RuntimeErrorKind::WrongType,
                            "Tried to perform \"-\" on non-number reference"
                        ))
                    }
                },
                // JMP
                0x18 => {
                    let loc = self.read_u16();
                    self.ip += loc as usize;
                }
                // JMP_UP
                0x19 => {
                    let loc = self.read_u16();
                    self.ip -= loc as usize;
                }
                // JNE
                0x1A => {
                    let condition = self.stack.pop().unwrap();
                    if let Value::Bool(condition) = condition {
                        if !condition {
                            let loc = self.read_u16();
                            self.ip += loc as usize;
                        } else {
                            self.read_u16();
                        }
                    } else {
                        return Err(vm_error!(
                            self,
                            RuntimeErrorKind::WrongType,
                            "if must have condition of type boolean"
                        ));
                    }
                }

                // CALL
                0x1B => {
                    let num_args = self.read();
                    let function = self.stack.pop().expect("Stack was empty in call");
                    if let Value::Fun(function) = function {
                        if num_args as usize != function.arity {
                            return Err(vm_error!(
                                self,
                                RuntimeErrorKind::IncorrectArity,
                                "Function has {} arguments, {} provided",
                                function.arity,
                                num_args
                            ));
                        }
                        self.variables_offset = self.stack.len() - num_args as usize;
                        self.call_stack
                            .push((self.unit_ptr, self.ip, self.variables_offset));
                        self.stack
                            .insert(self.stack.len() - num_args as usize, Value::Fun(function));
                        self.ip = 0;
                        self.unit_ptr = function.unit_ptr as usize;
                    } else {
                        return Err(vm_error!(
                            self,
                            RuntimeErrorKind::WrongType,
                            "Tried to call non-function type {}",
                            function.type_str()
                        ));
                    }
                }
                // RET
                0x1C => {
                    let (unit_ptr, ip, variables_offset) =
                        self.call_stack.pop().expect("Call stack empty on RET");
                    let ret = self.stack.pop().expect("Missing return value");
                    self.stack = self.stack[..variables_offset].to_vec();
                    self.variables_offset = self.call_stack.last().expect("call stack empty").2;
                    self.unit_ptr = unit_ptr;
                    self.ip = ip;
                    // returned to code
                    self.stack.push(ret);
                }

                // LIST
                0x1D => {
                    let len = self.read();
                    let list = self
                        .stack
                        .drain(self.stack.len() - len as usize..)
                        .collect();
                    self.stack.push(Value::List(list));
                }
                // SCR
                0x1E => {
                    let index = self.stack.pop().expect("stack empty on subscript index");
                    let list = self.stack.pop().expect("stack empty on subscript list");
                    if let Value::Num(index) = index {
                        if index.fract() != 0.0 {
                            return Err(vm_error!(
                                self,
                                RuntimeErrorKind::WrongType,
                                "Subscript index must be an integer but found {}",
                                index
                            ));
                        }
                        let index = index as usize;
                        if let Value::List(list) = list {
                            if index > list.len() {
                                return Err(vm_error!(
                                    self,
                                    RuntimeErrorKind::ArrayOutOfBounds,
                                    "List length is {} but found index {}",
                                    list.len(),
                                    index
                                ));
                            }
                            self.stack.push(list[index].clone());
                        } else {
                            return Err(vm_error!(
                                self,
                                RuntimeErrorKind::WrongType,
                                "Tried to subscript non-list type {}",
                                list.type_str()
                            ));
                        }
                    } else {
                        return Err(vm_error!(
                            self,
                            RuntimeErrorKind::WrongType,
                            "Tried to use non-integer type {} to subscript list",
                            index.type_str()
                        ));
                    }
                }

                0xFD => {
                    // POP
                    let times = self.read();
                    for _ in 0..times {
                        self.stack
                            .pop()
                            .expect(&format!("{}: Unable to pop stack", self.ip));
                    }
                }
                0xFE => {
                    // PRINT
                    let value = self.stack.pop().unwrap();
                    /*match value {
                        Null => *output += "null",
                        Num(v) => *output += &v.to_string(),
                        Str(v) => *output += &v,
                        Bool(v) => *output += &v.to_string(),
                        List(v) => {
                            *output += "[";
                            for value in v {
                                *output += &format!("", value);
                            }
                            *output += "[";
                        }
                        Fun(v) => *output += &format!("<function {}>", v.unit_ptr),
                    }*/
                    *output += &value.to_string();
                    *output += "\n";
                }
                _ => {}
            }
        }
        Ok(())
    }
    pub fn read(&mut self) -> u8 {
        let byte = self.units[self.unit_ptr].code[self.ip];
        self.ip += 1;
        byte
    }
    pub fn read_u16(&mut self) -> u16 {
        let byte_one = (self.units[self.unit_ptr].code[self.ip] as u16) << 0x08;
        self.ip += 1;
        let byte_two = self.units[self.unit_ptr].code[self.ip] as u16;
        self.ip += 1;
        byte_one | byte_two
    }
    pub fn find_line(&self) -> usize {
        // returns line # at ip
        let mut line_ip = 0;
        for (line, rep) in self.units[self.unit_ptr].lines.clone() {
            if line_ip + rep > self.ip {
                return line;
            }
            line_ip += rep;
        }
        panic!("Something went wrong in finding line for error")
    }
}

#[derive(Debug, Clone)]
pub enum Value {
    Null,
    Num(f32),
    Str(String),
    Bool(bool),
    List(Vec<Value>),
    Fun(Function),
    Ref(usize),
}

impl Value {
    pub fn type_str(&self) -> String {
        match self {
            Value::Null => "null".to_string(),
            Value::Num(_) => "number".to_string(),
            Value::Str(_) => "string".to_string(),
            Value::Bool(_) => "bool".to_string(),
            Value::List(_) => "list".to_string(),
            Value::Fun(_) => "function".to_string(),
            Value::Ref(_) => "reference".to_string(),
        }
    }
}
impl ToString for Value {
    fn to_string(&self) -> String {
        use Value::*;
        match self {
            Null => "null".to_string(),
            Num(v) => v.to_string(),
            Str(v) => v.to_string(),
            Bool(v) => v.to_string(),
            List(v) => {
                let mut output = "".to_string();
                output += "[";
                for value in <Vec<Value>>::clone(&v).into_iter() {
                    output += &value.to_string();
                    output += ",";
                }
                output += "]";
                output
            }
            Fun(v) => format!("<function {}>", v.unit_ptr),
            Ref(v) => format!("<reference {}>", v),
        }
    }
}

#[derive(Debug, Clone, Copy)]
pub struct Function {
    pub unit_ptr: usize,
    pub arity: usize,
}