qanglang-core 0.3.0

Core library for QangLang
Documentation
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
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
use rustc_hash::{FxBuildHasher, FxHashMap};

use crate::{
    GlobalCompilerPipeline, HeapAllocator, NativeFunctionError, QangProgram, QangRuntimeError,
    Value, ValueKind, Vm,
    backend::{
        assembler::STACK_MAX,
        object::{IntrinsicKind, IntrinsicMethod},
        value::{
            ARRAY_TYPE_STRING, BOOLEAN_TYPE_STRING, CLASS_TYPE_STRING, FUNCTION_TYPE_STRING,
            MODULE_TYPE_STRING, NIL_TYPE_STRING, NUMBER_TYPE_STRING, OBJECT_TYPE_STRING,
            STRING_TYPE_STRING,
        },
        vm::RuntimeResult,
    },
    peek_value, pop_value, push_value,
};

pub fn qang_assert(arg_count: usize, vm: &mut Vm) -> Result<Option<Value>, NativeFunctionError> {
    let args = vm.get_function_args(arg_count);
    let assertion = args
        .first()
        .ok_or_else(|| NativeFunctionError::new("No arguments provided."))?;

    if assertion.is_truthy() {
        return Ok(None);
    }
    let message = args
        .get(1)
        .copied()
        .and_then(|v| {
            if v.is_nil() {
                None
            } else {
                Some(v.to_display_string(&vm.alloc))
            }
        })
        .unwrap_or_else(|| "Assertion failed.".to_string());

    Err(NativeFunctionError(message))
}

pub fn qang_assert_eq(arg_count: usize, vm: &mut Vm) -> Result<Option<Value>, NativeFunctionError> {
    let args = vm.get_function_args(arg_count);
    if args.len() < 2 {
        return Err("Must provide two arguments.".into());
    }

    let a = args[0];
    let b = args[1];

    if a != b {
        let message = args
            .get(2)
            .copied()
            .and_then(|v| {
                if v.is_nil() {
                    None
                } else {
                    Some(v.to_display_string(&vm.alloc))
                }
            })
            .unwrap_or_else(|| "Assertion failed.".to_string());
        Err(NativeFunctionError(message))
    } else {
        Ok(None)
    }
}

pub fn qang_assert_throws(
    arg_count: usize,
    vm: &mut Vm,
) -> Result<Option<Value>, NativeFunctionError> {
    let args = vm.get_function_args(arg_count);
    let assertion = args
        .first()
        .ok_or_else(|| NativeFunctionError::new("No arguments provided."))?;
    let message_handle = args.get(1).copied();

    let function_handle = match assertion.as_closure() {
        Some(function_handle) => function_handle,
        _ => return Err("First argument must be a function.".into()),
    };

    let result = vm.call_function(function_handle, &[] as &[Value; 0]);

    match result {
        Ok(_) => {
            let message = message_handle
                .and_then(|v| {
                    if v.is_nil() {
                        None
                    } else {
                        Some(v.to_display_string(&vm.alloc))
                    }
                })
                .unwrap_or_else(|| "Expected function to throw, but did not.".to_string());

            Err(NativeFunctionError::new(&message))
        }
        Err(_) => Ok(None),
    }
}

pub fn qang_print(arg_count: usize, vm: &mut Vm) -> Result<Option<Value>, NativeFunctionError> {
    let args = vm.get_function_args(arg_count);
    let value = args.first().copied().unwrap_or(Value::nil());
    let value = value.to_display_string(&vm.alloc);
    print!("{}", value);
    Ok(None)
}

pub fn qang_println(arg_count: usize, vm: &mut Vm) -> Result<Option<Value>, NativeFunctionError> {
    let args = vm.get_function_args(arg_count);
    let value = args.first().copied().unwrap_or(Value::nil());
    let value = value.to_display_string(&vm.alloc);
    println!("{}", value);
    Ok(None)
}

pub fn qang_typeof(arg_count: usize, vm: &mut Vm) -> Result<Option<Value>, NativeFunctionError> {
    let args = vm.get_function_args(arg_count);
    let value = args.first().copied().unwrap_or(Value::nil());
    let value_string = value.to_type_string();
    let handle = vm.alloc.strings.intern(value_string);

    Ok(Some(Value::string(handle)))
}

pub fn qang_system_time(
    _arg_count: usize,
    _vm: &mut Vm,
) -> Result<Option<Value>, NativeFunctionError> {
    use std::time::{SystemTime, UNIX_EPOCH};

    let start = SystemTime::now();
    let since_the_epoch = start
        .duration_since(UNIX_EPOCH)
        .map_err(|_| NativeFunctionError::new("Unable to get system time."))?;

    let time: f64 = since_the_epoch.as_millis() as f64;

    Ok(Some(time.into()))
}

pub fn qang_to_string(arg_count: usize, vm: &mut Vm) -> Result<Option<Value>, NativeFunctionError> {
    let args = vm.get_function_args(arg_count);
    let value = args.first().copied().unwrap_or(Value::nil());

    let value = value.to_display_string(&vm.alloc);
    let value_handle = vm.alloc.strings.intern(&value);

    Ok(Some(Value::string(value_handle)))
}

pub fn qang_string_to_uppercase(
    receiver: Value,
    _arg_count: usize,
    vm: &mut Vm,
) -> Result<Option<Value>, NativeFunctionError> {
    if let Some(handle) = receiver.as_string() {
        let uppercase_string = &vm.alloc.strings.get_string(handle).to_uppercase();
        let uppercase_handle = vm.alloc.strings.intern(uppercase_string);

        Ok(Some(Value::string(uppercase_handle)))
    } else {
        Err(NativeFunctionError(format!(
            "Expected string but recieved {}.",
            receiver.to_type_string()
        )))
    }
}

pub fn qang_string_to_lowercase(
    receiver: Value,
    _arg_count: usize,
    vm: &mut Vm,
) -> Result<Option<Value>, NativeFunctionError> {
    if let Some(handle) = receiver.as_string() {
        let lowercase_string = &vm.alloc.strings.get_string(handle).to_lowercase();
        let lowercase_handle = vm.alloc.strings.intern(lowercase_string);

        Ok(Some(Value::string(lowercase_handle)))
    } else {
        Err(NativeFunctionError(format!(
            "Expected string but recieved {}.",
            receiver.to_type_string()
        )))
    }
}

pub fn qang_string_split(
    receiver: Value,
    arg_count: usize,
    vm: &mut Vm,
) -> Result<Option<Value>, NativeFunctionError> {
    if let Some(handle) = receiver.as_string() {
        let args = vm.get_function_args(arg_count);
        let delimeter = if let Some(delimeter) = args.first() {
            if let Some(delimeter_handle) = delimeter.as_string() {
                delimeter_handle
            } else {
                return Err(NativeFunctionError::new("Delimeter must be a string."));
            }
        } else {
            vm.alloc.strings.intern("")
        };

        let arr = vm.alloc.arrays.create_array(0);
        let delimeter = vm.alloc.strings.get_string(delimeter).to_owned();
        let string_to_split = vm.alloc.strings.get_string(handle).to_owned();

        if delimeter.is_empty() {
            // Split into individual characters when no delimiter
            for ch in string_to_split.chars() {
                let handle = vm.alloc.strings.intern(&ch.to_string());
                vm.alloc.arrays.push(arr, Value::string(handle));
            }
        } else {
            // Normal split with delimiter
            let strings = string_to_split
                .split(&delimeter)
                .map(|s| s.to_owned())
                .collect::<Vec<_>>();
            for string in strings {
                let handle = vm.alloc.strings.intern(string.as_str());
                vm.alloc.arrays.push(arr, Value::string(handle));
            }
        }

        Ok(Some(Value::array(arr)))
    } else {
        Err(NativeFunctionError(format!(
            "Expected string but recieved {}.",
            receiver.to_type_string()
        )))
    }
}

pub fn qang_string_concat(
    receiver: Value,
    arg_count: usize,
    vm: &mut Vm,
) -> Result<Option<Value>, NativeFunctionError> {
    let args = vm.get_function_args(arg_count);
    match (receiver.kind(), args.first().copied().map(|a| a.kind())) {
        (ValueKind::String(handle1), Some(ValueKind::String(handle2))) => Ok(Some(Value::string(
            vm.alloc.strings.concat_strings(handle1, handle2),
        ))),
        (ValueKind::String(_), _) => Err(NativeFunctionError::new(
            "A string can only be concatenated with another string.",
        )),
        _ => Err(NativeFunctionError(format!(
            "Expected string but recieved {}.",
            receiver.to_type_string()
        ))),
    }
}

pub fn qang_array_length(
    receiver: Value,
    _arg_count: usize,
    vm: &mut Vm,
) -> Result<Option<Value>, NativeFunctionError> {
    if let Some(handle) = receiver.as_array() {
        let length = vm.alloc.arrays.length(handle);
        Ok(Some(length.into()))
    } else {
        Err(NativeFunctionError(format!(
            "Expected array but recieved {}.",
            receiver.to_type_string()
        )))
    }
}

pub fn qang_array_push(
    receiver: Value,
    arg_count: usize,
    vm: &mut Vm,
) -> Result<Option<Value>, NativeFunctionError> {
    let args = vm.get_function_args(arg_count);
    if let Some(handle) = receiver.as_array() {
        let element = args.first().copied().unwrap_or_default();
        vm.with_gc_check(|alloc| alloc.arrays.push(handle, element));
        Ok(None)
    } else {
        Err(NativeFunctionError(format!(
            "Expected array but recieved {}.",
            receiver.to_type_string()
        )))
    }
}

pub fn qang_array_pop(
    receiver: Value,
    _arg_count: usize,
    vm: &mut Vm,
) -> Result<Option<Value>, NativeFunctionError> {
    if let Some(handle) = receiver.as_array() {
        let element = vm.alloc.arrays.pop(handle);
        if element.is_none() {
            return Err(NativeFunctionError::new("Array is empty."));
        }
        Ok(element)
    } else {
        Err(NativeFunctionError(format!(
            "Expected array but recieved {}.",
            receiver.to_type_string()
        )))
    }
}

pub fn qang_array_reverse(
    receiver: Value,
    _arg_count: usize,
    vm: &mut Vm,
) -> Result<Option<Value>, NativeFunctionError> {
    if let Some(handle) = receiver.as_array() {
        vm.alloc.arrays.reverse(handle);
        Ok(None)
    } else {
        Err(NativeFunctionError(format!(
            "Expected array but recieved {}.",
            receiver.to_type_string()
        )))
    }
}

pub fn qang_array_slice(
    receiver: Value,
    arg_count: usize,
    vm: &mut Vm,
) -> Result<Option<Value>, NativeFunctionError> {
    let args = vm.get_function_args(arg_count);
    if let Some(handle) = receiver.as_array() {
        let begin = args.first().copied().unwrap_or(Value::nil());
        let end = args.get(1).copied().unwrap_or(Value::nil());

        match (begin.kind(), end.kind()) {
            (ValueKind::Number(begin), ValueKind::Number(end)) => {
                let slice = vm.with_gc_check(|alloc| {
                    Value::array(
                        alloc
                            .arrays
                            .slice(handle, begin as isize, Some(end as isize)),
                    )
                });
                Ok(Some(slice))
            }
            (ValueKind::Number(begin), ValueKind::Nil) => {
                let slice = vm.with_gc_check(|alloc| {
                    Value::array(alloc.arrays.slice(handle, begin as isize, None))
                });
                Ok(Some(slice))
            }
            (ValueKind::Nil, ValueKind::Nil) => {
                let clone =
                    vm.with_gc_check(|alloc| Value::array(alloc.arrays.shallow_copy(handle)));
                Ok(Some(clone))
            }
            _ => Err(NativeFunctionError::new(
                "Expected both values to be a number.",
            )),
        }
    } else {
        Err(NativeFunctionError(format!(
            "Expected array but recieved {}.",
            receiver.to_type_string()
        )))
    }
}

pub fn qang_array_get(
    receiver: Value,
    arg_count: usize,
    vm: &mut Vm,
) -> Result<Option<Value>, NativeFunctionError> {
    let args = vm.get_function_args(arg_count);
    match (receiver.kind(), args.first().map(|a| a.kind())) {
        (ValueKind::Array(handle), Some(ValueKind::Number(index))) => {
            Ok(Some(vm.alloc.arrays.get(handle, index.trunc() as isize)))
        }
        (ValueKind::Array(_), _) => Err(NativeFunctionError::new(
            "An array can only be indexed by a number.",
        )),
        _ => Err(NativeFunctionError(format!(
            "Expected array but recieved {}.",
            receiver.to_type_string()
        ))),
    }
}

pub fn qang_array_concat(
    receiver: Value,
    arg_count: usize,
    vm: &mut Vm,
) -> Result<Option<Value>, NativeFunctionError> {
    let args = vm.get_function_args(arg_count);
    match (receiver.kind(), args.first().copied().map(|a| a.kind())) {
        (ValueKind::Array(handle1), Some(ValueKind::Array(handle2))) => {
            Ok(Some(Value::array(vm.alloc.arrays.concat(handle1, handle2))))
        }
        (ValueKind::Array(_), _) => Err(NativeFunctionError::new(
            "An array can only be concatenated with another array.",
        )),
        _ => Err(NativeFunctionError(format!(
            "Expected array but recieved {}.",
            receiver.to_type_string()
        ))),
    }
}

pub fn qang_array_remove_at(
    receiver: Value,
    arg_count: usize,
    vm: &mut Vm,
) -> Result<Option<Value>, NativeFunctionError> {
    let args = vm.get_function_args(arg_count);
    match (receiver.kind(), args.first().map(|a| a.kind())) {
        (ValueKind::Array(handle), Some(ValueKind::Number(index))) => {
            let value = vm.alloc.arrays.remove_at(handle, index.trunc() as isize);

            Ok(value)
        }
        (ValueKind::Array(_), _) => Err(NativeFunctionError::new(
            "An array can only be indexed by a number.",
        )),
        _ => Err(NativeFunctionError(format!(
            "Expected array but recieved {}.",
            receiver.to_type_string()
        ))),
    }
}

pub fn qang_array_index_of(
    receiver: Value,
    arg_count: usize,
    vm: &mut Vm,
) -> Result<Option<Value>, NativeFunctionError> {
    if arg_count < 1 {
        return Err(NativeFunctionError::new(
            "An argument must be provided for index_of.",
        ));
    }
    let value = vm
        .get_function_args(arg_count)
        .first()
        .copied()
        .unwrap_or(Value::nil());

    if let Some(handle) = receiver.as_array() {
        for (index, item) in vm.alloc.arrays.iter(handle).enumerate() {
            if item == value {
                return Ok(Some(Value::number(index as f64)));
            }
        }
    }

    return Ok(Some(Value::number(-1.0)));
}

pub fn qang_array_contains(
    receiver: Value,
    arg_count: usize,
    vm: &mut Vm,
) -> Result<Option<Value>, NativeFunctionError> {
    if arg_count < 1 {
        return Err(NativeFunctionError::new(
            "An argument must be provided for contains.",
        ));
    }
    let value = vm
        .get_function_args(arg_count)
        .first()
        .copied()
        .unwrap_or(Value::nil());

    if let Some(handle) = receiver.as_array() {
        for item in vm.alloc.arrays.iter(handle) {
            if item == value {
                return Ok(Some(Value::boolean(true)));
            }
        }
    }

    return Ok(Some(Value::boolean(false)));
}

pub fn qang_array_join(
    receiver: Value,
    arg_count: usize,
    vm: &mut Vm,
) -> Result<Option<Value>, NativeFunctionError> {
    if let Some(handle) = receiver.as_array() {
        let args = vm.get_function_args(arg_count);

        let delimeter = if let Some(delimeter) = args.first() {
            if let Some(delimeter_handle) = delimeter.as_string() {
                delimeter_handle
            } else {
                return Err(NativeFunctionError::new("Delimeter must be a string."));
            }
        } else {
            vm.alloc.strings.intern("")
        };

        let mut combined_string = String::new();
        let delimeter_str = vm.alloc.strings.get_string(delimeter);

        let mut first = true;
        for value in vm.alloc.arrays.iter(handle) {
            if !first {
                combined_string += delimeter_str;
            }
            first = false;

            let string = value.to_display_string(&vm.alloc);
            combined_string += &string;
        }

        let combined_string_handle = vm.alloc.strings.intern(&combined_string);

        Ok(Some(Value::string(combined_string_handle)))
    } else {
        Err(NativeFunctionError(format!(
            "Expected string but recieved {}.",
            receiver.to_type_string()
        )))
    }
}

pub fn qang_array_create(
    arg_count: usize,
    vm: &mut Vm,
) -> Result<Option<Value>, NativeFunctionError> {
    let args = vm.get_function_args(arg_count);
    if let Some(length) = args.first().copied().unwrap_or(Value::nil()).as_number() {
        Ok(Some(Value::array(
            vm.alloc.arrays.create_array(length.trunc() as usize),
        )))
    } else {
        Err(NativeFunctionError::new("Expected length to be a number."))
    }
}

pub fn qang_hash(arg_count: usize, vm: &mut Vm) -> Result<Option<Value>, NativeFunctionError> {
    let args = vm.get_function_args(arg_count);
    let value = args.first().copied();

    match value {
        None => Err("No value provided to hash.".into()),
        Some(value) => Ok(Some(value.hash().into())),
    }
}

pub fn qang_number_ceil(
    receiver: Value,
    _arg_count: usize,
    _vm: &mut Vm,
) -> Result<Option<Value>, NativeFunctionError> {
    if let Some(value) = receiver.as_number() {
        Ok(Some(Value::number(value.ceil())))
    } else {
        Err(NativeFunctionError(format!(
            "Expected number but recieved {}.",
            receiver.to_type_string()
        )))
    }
}

pub fn qang_number_floor(
    receiver: Value,
    _arg_count: usize,
    _vm: &mut Vm,
) -> Result<Option<Value>, NativeFunctionError> {
    if let Some(value) = receiver.as_number() {
        Ok(Some(Value::number(value.floor())))
    } else {
        Err(NativeFunctionError(format!(
            "Expected number but recieved {}.",
            receiver.to_type_string()
        )))
    }
}

pub fn qang_number_trunc(
    receiver: Value,
    _arg_count: usize,
    _vm: &mut Vm,
) -> Result<Option<Value>, NativeFunctionError> {
    if let Some(value) = receiver.as_number() {
        Ok(Some(Value::number(value.trunc())))
    } else {
        Err(NativeFunctionError(format!(
            "Expected number but recieved {}.",
            receiver.to_type_string()
        )))
    }
}

pub fn qang_number_min(
    receiver: Value,
    arg_count: usize,
    vm: &mut Vm,
) -> Result<Option<Value>, NativeFunctionError> {
    let min = vm
        .get_function_args(arg_count)
        .first()
        .and_then(|v| v.as_number())
        .ok_or_else(|| NativeFunctionError::new("Min value must be a number."))?;

    if let Some(value) = receiver.as_number() {
        Ok(Some(Value::number(value.min(min))))
    } else {
        Err(NativeFunctionError(format!(
            "Expected number but recieved {}.",
            receiver.to_type_string()
        )))
    }
}

pub fn qang_number_max(
    receiver: Value,
    arg_count: usize,
    vm: &mut Vm,
) -> Result<Option<Value>, NativeFunctionError> {
    let max = vm
        .get_function_args(arg_count)
        .first()
        .and_then(|v| v.as_number())
        .ok_or_else(|| NativeFunctionError::new("Max value must be a number."))?;

    if let Some(value) = receiver.as_number() {
        Ok(Some(Value::number(value.max(max))))
    } else {
        Err(NativeFunctionError(format!(
            "Expected number but recieved {}.",
            receiver.to_type_string()
        )))
    }
}

impl Vm {
    pub(crate) fn with_stdlib(mut self) -> Self {
        if let Err(err) = self.load_stdlib() {
            panic!("Failed to load standard library: {}", err);
        }
        self
    }

    fn load_stdlib(&mut self) -> Result<(), Box<dyn std::error::Error>> {
        self.load_constants();
        let stdlib_source = include_str!("stdlib.ql");
        let program =
            GlobalCompilerPipeline::compile_source(stdlib_source.to_owned(), &mut self.alloc)
                .map_err(|e| format!("Stdlib compilation failed: {:?}", e))?;

        // Execute stdlib to populate globals
        self.execute_stdlib(program)?;

        Ok(())
    }

    fn execute_stdlib(&mut self, program: QangProgram) -> Result<(), Box<dyn std::error::Error>> {
        // Save current VM state
        let saved_stack_top = self.state.stack_top;
        let saved_frame_count = self.state.frame_count;

        // Execute stdlib program
        self.interpret(program)
            .map_err(|e| format!("Stdlib execution failed: {:?}", e))?;

        // Restore VM state (stdlib execution shouldn't affect main program state)
        self.state.stack_top = saved_stack_top;
        self.state.frame_count = saved_frame_count;

        Ok(())
    }

    fn load_constants(&mut self) {
        self.alloc.strings.intern("NIL");
        self.alloc.strings.intern(NIL_TYPE_STRING);
        self.alloc.strings.intern("BOOLEAN");
        self.alloc.strings.intern(BOOLEAN_TYPE_STRING);
        self.alloc.strings.intern("NUMBER");
        self.alloc.strings.intern(NUMBER_TYPE_STRING);
        self.alloc.strings.intern("STRING");
        self.alloc.strings.intern(STRING_TYPE_STRING);
        self.alloc.strings.intern("FUNCTION");
        self.alloc.strings.intern(FUNCTION_TYPE_STRING);
        self.alloc.strings.intern("CLASS");
        self.alloc.strings.intern(CLASS_TYPE_STRING);
        self.alloc.strings.intern("OBJECT");
        self.alloc.strings.intern(OBJECT_TYPE_STRING);
        self.alloc.strings.intern("ARRAY");
        self.alloc.strings.intern(ARRAY_TYPE_STRING);
        self.alloc.strings.intern("MODULE");
        self.alloc.strings.intern(MODULE_TYPE_STRING);
    }

    pub(crate) fn load_intrinsics(
        alloc: &mut HeapAllocator,
    ) -> FxHashMap<IntrinsicKind, IntrinsicMethod> {
        let mut intrinsics = FxHashMap::with_hasher(FxBuildHasher);
        let to_uppercase_handle = alloc.strings.intern("to_uppercase");
        intrinsics.insert(
            IntrinsicKind::String(to_uppercase_handle),
            IntrinsicMethod::Native {
                function: qang_string_to_uppercase,
                arity: 0,
            },
        );
        let to_lowercase_handle = alloc.strings.intern("to_lowercase");
        intrinsics.insert(
            IntrinsicKind::String(to_lowercase_handle),
            IntrinsicMethod::Native {
                function: qang_string_to_lowercase,
                arity: 0,
            },
        );
        let to_number_handle = alloc.strings.intern("to_number");
        intrinsics.insert(
            IntrinsicKind::String(to_number_handle),
            IntrinsicMethod::ToNumber,
        );
        let concat_handle = alloc.strings.intern("concat");

        intrinsics.insert(
            IntrinsicKind::String(concat_handle),
            IntrinsicMethod::Native {
                function: qang_string_concat,
                arity: 1,
            },
        );
        let split_handle = alloc.strings.intern("split");
        intrinsics.insert(
            IntrinsicKind::String(split_handle),
            IntrinsicMethod::Native {
                function: qang_string_split,
                arity: 1,
            },
        );
        let length_handle = alloc.strings.intern("length");
        intrinsics.insert(
            IntrinsicKind::Array(length_handle),
            IntrinsicMethod::Native {
                function: qang_array_length,
                arity: 0,
            },
        );
        let array_push_handle = alloc.strings.intern("push");
        intrinsics.insert(
            IntrinsicKind::Array(array_push_handle),
            IntrinsicMethod::Native {
                function: qang_array_push,
                arity: 1,
            },
        );
        let array_pop_handle = alloc.strings.intern("pop");
        intrinsics.insert(
            IntrinsicKind::Array(array_pop_handle),
            IntrinsicMethod::Native {
                function: qang_array_pop,
                arity: 0,
            },
        );
        let array_reverse_handle = alloc.strings.intern("reverse");
        intrinsics.insert(
            IntrinsicKind::Array(array_reverse_handle),
            IntrinsicMethod::Native {
                function: qang_array_reverse,
                arity: 0,
            },
        );
        let array_slice_handle = alloc.strings.intern("slice");
        intrinsics.insert(
            IntrinsicKind::Array(array_slice_handle),
            IntrinsicMethod::Native {
                function: qang_array_slice,
                arity: 2,
            },
        );
        let array_get_handle = alloc.strings.intern("get");
        intrinsics.insert(
            IntrinsicKind::Array(array_get_handle),
            IntrinsicMethod::Native {
                function: qang_array_get,
                arity: 1,
            },
        );
        intrinsics.insert(
            IntrinsicKind::Array(concat_handle),
            IntrinsicMethod::Native {
                function: qang_array_concat,
                arity: 1,
            },
        );
        let array_remove_at_handle = alloc.strings.intern("remove_at");
        intrinsics.insert(
            IntrinsicKind::Array(array_remove_at_handle),
            IntrinsicMethod::Native {
                function: qang_array_remove_at,
                arity: 1,
            },
        );
        let array_join_handle = alloc.strings.intern("join");
        intrinsics.insert(
            IntrinsicKind::Array(array_join_handle),
            IntrinsicMethod::Native {
                function: qang_array_join,
                arity: 1,
            },
        );
        let array_index_of_handle = alloc.strings.intern("index_of");
        intrinsics.insert(
            IntrinsicKind::Array(array_index_of_handle),
            IntrinsicMethod::Native {
                function: qang_array_index_of,
                arity: 1,
            },
        );
        let array_contains_handle = alloc.strings.intern("contains");
        intrinsics.insert(
            IntrinsicKind::Array(array_contains_handle),
            IntrinsicMethod::Native {
                function: qang_array_contains,
                arity: 1,
            },
        );
        let array_iter_handle = alloc.strings.intern("iter");
        intrinsics.insert(
            IntrinsicKind::Array(array_iter_handle),
            IntrinsicMethod::Iter,
        );
        let number_ceil_handle = alloc.strings.intern("ceil");
        intrinsics.insert(
            IntrinsicKind::Number(number_ceil_handle),
            IntrinsicMethod::Native {
                function: qang_number_ceil,
                arity: 0,
            },
        );
        let number_floor_handle = alloc.strings.intern("floor");
        intrinsics.insert(
            IntrinsicKind::Number(number_floor_handle),
            IntrinsicMethod::Native {
                function: qang_number_floor,
                arity: 0,
            },
        );
        let number_trunc_handle = alloc.strings.intern("trunc");
        intrinsics.insert(
            IntrinsicKind::Number(number_trunc_handle),
            IntrinsicMethod::Native {
                function: qang_number_trunc,
                arity: 0,
            },
        );
        let number_min_handle = alloc.strings.intern("min");
        intrinsics.insert(
            IntrinsicKind::Number(number_min_handle),
            IntrinsicMethod::Native {
                function: qang_number_min,
                arity: 1,
            },
        );
        let number_max_handle = alloc.strings.intern("max");
        intrinsics.insert(
            IntrinsicKind::Number(number_max_handle),
            IntrinsicMethod::Native {
                function: qang_number_max,
                arity: 1,
            },
        );
        let function_call_handle = alloc.strings.intern("call");
        intrinsics.insert(
            IntrinsicKind::Function(function_call_handle),
            IntrinsicMethod::Call,
        );
        let function_apply_handle = alloc.strings.intern("apply");
        intrinsics.insert(
            IntrinsicKind::Function(function_apply_handle),
            IntrinsicMethod::Apply,
        );

        intrinsics
    }

    pub(crate) fn handle_function_intrinsic_call(
        &mut self,
        receiver: Value,
        arg_count: usize,
    ) -> RuntimeResult<()> {
        match receiver.kind() {
            ValueKind::Closure(_)
            | ValueKind::BoundIntrinsic(_)
            | ValueKind::BoundMethod(_)
            | ValueKind::NativeFunction(_) => {
                self.state.stack[self.state.stack_top - arg_count - 1] = receiver;
                self.call_value(receiver, arg_count)
            }
            _ => Err(QangRuntimeError::new(
                "'call' can only be used on functions.".to_string(),
                self.state.get_previous_loc(),
            )),
        }
    }

    pub(crate) fn handle_function_intrinsic_apply(
        &mut self,
        receiver: Value,
        arg_count: usize,
    ) -> RuntimeResult<()> {
        match receiver.kind() {
            ValueKind::Closure(_)
            | ValueKind::BoundIntrinsic(_)
            | ValueKind::BoundMethod(_)
            | ValueKind::NativeFunction(_) => {
                if arg_count != 1 {
                    return Err(QangRuntimeError::new(
                        "'apply' must be called with one argument and it must be an array."
                            .to_string(),
                        self.state.get_previous_loc(),
                    ));
                }

                let array_arg = peek_value!(self, 0);

                if let Some(array_handle) = array_arg.as_array() {
                    // Pop the array argument
                    pop_value!(self);

                    // Replace the bound intrinsic on the stack with the actual function
                    self.state.stack[self.state.stack_top - 1] = receiver;

                    let array_length = self.alloc.arrays.length(array_handle);
                    for value in self.alloc.arrays.iter(array_handle) {
                        push_value!(self, value)?;
                    }

                    self.call_value(receiver, array_length)
                } else {
                    Err(QangRuntimeError::new(
                        "'apply' must be called with one argument and it must be an array."
                            .to_string(),
                        self.state.get_previous_loc(),
                    ))
                }
            }
            _ => Err(QangRuntimeError::new(
                "'apply' can only be used on functions.".to_string(),
                self.state.get_previous_loc(),
            )),
        }
    }

    pub(crate) fn handle_array_intrinsic_iter(
        &mut self,
        receiver: Value,
        _arg_count: usize,
    ) -> RuntimeResult<()> {
        let array_iterator = *self
            .globals()
            .get(
                self.state
                    .keywords
                    .get(&super::vm::Keyword::ArrayIterator)
                    .expect("Expected ArrayIterator to be interned."),
            )
            .expect("Expected ArrayIterator to be loaded from stdlib.");

        pop_value!(self);

        push_value!(self, array_iterator)?;

        push_value!(self, receiver)?;

        self.call_value(array_iterator, 1)
    }

    pub(crate) fn handle_string_intrinsic_to_number(
        &mut self,
        receiver: Value,
        _arg_count: usize,
    ) -> RuntimeResult<()> {
        pop_value!(self);

        let value = receiver.as_string().ok_or_else(|| {
            QangRuntimeError::new(
                "Expected string.".to_string(),
                self.state.get_previous_loc(),
            )
        })?;
        let value = self.alloc.strings.get_string(value);
        let result = match value.parse::<f64>() {
            Ok(number) => {
                let ok = *self
                    .globals()
                    .get(
                        self.state
                            .keywords
                            .get(&super::vm::Keyword::OkResult)
                            .expect("Expected Ok to be interned."),
                    )
                    .expect("Expected Ok to be loaded from stdlib.");

                push_value!(self, ok)?;
                push_value!(self, Value::number(number))?;
                ok
            }
            Err(_) => {
                let err = *self
                    .globals()
                    .get(
                        self.state
                            .keywords
                            .get(&super::vm::Keyword::ErrResult)
                            .expect("Expected Err to be interned."),
                    )
                    .expect("Expected Err to be loaded from stdlib.");

                push_value!(self, err)?;

                let err_msg = self
                    .alloc
                    .strings
                    .intern(format!("Unable to parse value '{:?}' as number.", value).as_str());
                push_value!(self, Value::string(err_msg))?;
                err
            }
        };

        self.call_value(result, 1)
    }
}