hexput-runtime 0.1.3

WebSocket runtime server for Hexput AST processing
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
use crate::error::RuntimeError;
use hexput_ast_api::ast_structs::SourceLocation;
use serde_json::{Map, Value};
use std::future::Future;
use std::pin::Pin;

const FORBIDDEN_KEY: &str = "secret_data";
const CALLBACK_REFERENCE_HASH: &str = "__callback_ref_constant";

pub type CallbackExecutor = Box<dyn Fn(String, Vec<Value>) -> Pin<Box<dyn Future<Output = Result<Value, RuntimeError>> + Send>> + Send + Sync>;

pub fn execute_builtin_method(
    object: &Value,
    method_name: &str,
    args: &[Value],
    location: &SourceLocation,
    callback_executor: Option<&CallbackExecutor>,
) -> Result<Option<Value>, RuntimeError> {
    // Check if object contains forbidden value - if so, deny all method calls
    if contains_forbidden_value(object) {
        return Err(RuntimeError::with_location(
            "Cannot call methods on object containing restricted data. Use as reference only.".to_string(),
            location.clone(),
        ));
    }

    match object {
        Value::String(s) => execute_string_method(s, method_name, args, location),
        Value::Array(arr) => execute_array_method(arr, method_name, args, location, callback_executor),
        Value::Object(obj) => execute_object_method(obj, method_name, args, location),
        Value::Number(num) => execute_number_method(num, method_name, args, location),
        Value::Bool(b) => execute_boolean_method(b, method_name, args, location),
        Value::Null => execute_null_method(method_name, args, location),
    }
}

fn execute_string_method(
    string: &str,
    method_name: &str,
    args: &[Value],
    location: &SourceLocation,
) -> Result<Option<Value>, RuntimeError> {
    match method_name {
        "len" | "length" => {
            if !args.is_empty() {
                return Err(RuntimeError::with_location(
                    format!("String.{} expects 0 arguments, got {}", method_name, args.len()),
                    location.clone(),
                ));
            }
            Ok(Some(Value::Number(string.len().into())))
        }
        "isEmpty" => {
            if !args.is_empty() {
                return Err(RuntimeError::with_location(
                    format!("String.isEmpty expects 0 arguments, got {}", args.len()),
                    location.clone(),
                ));
            }
            Ok(Some(Value::Bool(string.is_empty())))
        }
        "substring" => {
            if args.len() < 1 || args.len() > 2 {
                return Err(RuntimeError::with_location(
                    format!("String.substring expects 1-2 arguments, got {}", args.len()),
                    location.clone(),
                ));
            }

            
            let start = get_index_arg(&args[0], 0, string.len(), "substring", location)?;
            
            
            let end = if args.len() > 1 {
                get_index_arg(&args[1], start, string.len(), "substring", location)?
            } else {
                string.len()
            };

            
            let chars: Vec<char> = string.chars().collect();
            if start <= end && end <= chars.len() {
                let result: String = chars[start..end].iter().collect();
                Ok(Some(Value::String(result)))
            } else {
                Ok(Some(Value::String(String::new())))
            }
        }
        "toLowerCase" => {
            if !args.is_empty() {
                return Err(RuntimeError::with_location(
                    format!("String.toLowerCase expects 0 arguments, got {}", args.len()),
                    location.clone(),
                ));
            }
            Ok(Some(Value::String(string.to_lowercase())))
        }
        "toUpperCase" => {
            if !args.is_empty() {
                return Err(RuntimeError::with_location(
                    format!("String.toUpperCase expects 0 arguments, got {}", args.len()),
                    location.clone(),
                ));
            }
            Ok(Some(Value::String(string.to_uppercase())))
        }
        "trim" => {
            if !args.is_empty() {
                return Err(RuntimeError::with_location(
                    format!("String.trim expects 0 arguments, got {}", args.len()),
                    location.clone(),
                ));
            }
            Ok(Some(Value::String(string.trim().to_string())))
        }
        "contains" | "includes" => {
            if args.len() != 1 {
                return Err(RuntimeError::with_location(
                    format!("String.{} expects 1 argument, got {}", method_name, args.len()),
                    location.clone(),
                ));
            }
            
            match &args[0] {
                Value::String(substring) => Ok(Some(Value::Bool(string.contains(substring)))),
                _ => Err(RuntimeError::with_location(
                    format!("String.{} expects a string argument", method_name),
                    location.clone(),
                )),
            }
        }
        "startsWith" => {
            if args.len() != 1 {
                return Err(RuntimeError::with_location(
                    format!("String.startsWith expects 1 argument, got {}", args.len()),
                    location.clone(),
                ));
            }
            
            match &args[0] {
                Value::String(prefix) => Ok(Some(Value::Bool(string.starts_with(prefix)))),
                _ => Err(RuntimeError::with_location(
                    "String.startsWith expects a string argument".to_string(),
                    location.clone(),
                )),
            }
        }
        "endsWith" => {
            if args.len() != 1 {
                return Err(RuntimeError::with_location(
                    format!("String.endsWith expects 1 argument, got {}", args.len()),
                    location.clone(),
                ));
            }
            
            match &args[0] {
                Value::String(suffix) => Ok(Some(Value::Bool(string.ends_with(suffix)))),
                _ => Err(RuntimeError::with_location(
                    "String.endsWith expects a string argument".to_string(),
                    location.clone(),
                )),
            }
        }
        "indexOf" => {
            if args.len() != 1 {
                return Err(RuntimeError::with_location(
                    format!("String.indexOf expects 1 argument, got {}", args.len()),
                    location.clone(),
                ));
            }
            
            match &args[0] {
                Value::String(substring) => {
                    let index = string.find(substring).map_or(-1, |i| i as i64);
                    Ok(Some(Value::Number(index.into())))
                },
                _ => Err(RuntimeError::with_location(
                    "String.indexOf expects a string argument".to_string(),
                    location.clone(),
                )),
            }
        }
        "split" => {
            if args.len() != 1 {
                return Err(RuntimeError::with_location(
                    format!("String.split expects 1 argument, got {}", args.len()),
                    location.clone(),
                ));
            }
            
            match &args[0] {
                Value::String(delimiter) => {
                    let parts: Vec<Value> = string.split(delimiter)
                        .map(|s| Value::String(s.to_string()))
                        .collect();
                    Ok(Some(Value::Array(parts)))
                },
                _ => Err(RuntimeError::with_location(
                    "String.split expects a string argument".to_string(),
                    location.clone(),
                )),
            }
        }
        "replace" => {
            if args.len() != 2 {
                return Err(RuntimeError::with_location(
                    format!("String.replace expects 2 arguments, got {}", args.len()),
                    location.clone(),
                ));
            }
            
            let old = match &args[0] {
                Value::String(s) => s,
                _ => return Err(RuntimeError::with_location(
                    "String.replace expects a string argument".to_string(),
                    location.clone(),
                )),
            };
            
            let new = match &args[1] {
                Value::String(s) => s,
                _ => return Err(RuntimeError::with_location(
                    "String.replace expects a string argument".to_string(),
                    location.clone(),
                )),
            };
            
            let result = string.replace(old, new);
            Ok(Some(Value::String(result)))
        }
        _ => Ok(None), 
    }
}


fn execute_array_method(
    array: &[Value],
    method_name: &str,
    args: &[Value],
    location: &SourceLocation,
    callback_executor: Option<&CallbackExecutor>,
) -> Result<Option<Value>, RuntimeError> {
    match method_name {
        "length" | "len" => {
            if !args.is_empty() {
                return Err(RuntimeError::with_location(
                    format!("Array.{} expects 0 arguments, got {}", method_name, args.len()),
                    location.clone(),
                ));
            }
            Ok(Some(Value::Number(array.len().into())))
        }
        "isEmpty" => {
            if !args.is_empty() {
                return Err(RuntimeError::with_location(
                    format!("Array.isEmpty expects 0 arguments, got {}", args.len()),
                    location.clone(),
                ));
            }
            Ok(Some(Value::Bool(array.is_empty())))
        }
        "join" => {
            if args.len() != 1 {
                return Err(RuntimeError::with_location(
                    format!("Array.join expects 1 argument, got {}", args.len()),
                    location.clone(),
                ));
            }
            
            let separator = match &args[0] {
                Value::String(s) => s,
                _ => return Err(RuntimeError::with_location(
                    "Array.join expects a string argument".to_string(),
                    location.clone(),
                )),
            };
            
            
            let items: Vec<String> = array.iter()
                .map(|v| match v {
                    Value::String(s) => s.clone(),
                    Value::Number(n) => n.to_string(),
                    Value::Bool(b) => b.to_string(),
                    Value::Null => "null".to_string(),
                    Value::Array(_) => "[array]".to_string(),
                    Value::Object(_) => "[object]".to_string(),
                })
                .collect();
            
            Ok(Some(Value::String(items.join(separator))))
        }
        "first" => {
            if !args.is_empty() {
                return Err(RuntimeError::with_location(
                    format!("Array.first expects 0 arguments, got {}", args.len()),
                    location.clone(),
                ));
            }
            
            if array.is_empty() {
                Ok(Some(Value::Null))
            } else {
                Ok(Some(array[0].clone()))
            }
        }
        "last" => {
            if !args.is_empty() {
                return Err(RuntimeError::with_location(
                    format!("Array.last expects 0 arguments, got {}", args.len()),
                    location.clone(),
                ));
            }
            
            if array.is_empty() {
                Ok(Some(Value::Null))
            } else {
                Ok(Some(array[array.len() - 1].clone()))
            }
        }
        "includes" | "contains" => {
            if args.len() != 1 {
                return Err(RuntimeError::with_location(
                    format!("Array.{} expects 1 argument, got {}", method_name, args.len()),
                    location.clone(),
                ));
            }
            
            let target = &args[0];
            let contains = array.iter().any(|item| value_equals(item, target));
            Ok(Some(Value::Bool(contains)))
        }
        "slice" => {
            if args.len() < 1 || args.len() > 2 {
                return Err(RuntimeError::with_location(
                    format!("Array.slice expects 1-2 arguments, got {}", args.len()),
                    location.clone(),
                ));
            }
            
            
            let start = get_index_arg(&args[0], 0, array.len(), "slice", location)?;
            
            
            let end = if args.len() > 1 {
                get_index_arg(&args[1], start, array.len(), "slice", location)?
            } else {
                array.len()
            };
            
            if start <= end && end <= array.len() {
                let result = array[start..end].to_vec();
                Ok(Some(Value::Array(result)))
            } else {
                Ok(Some(Value::Array(vec![])))
            }
        }
        "map" => {
            if args.len() != 1 {
                return Err(RuntimeError::with_location(
                    format!("Array.map expects 1 argument (callback), got {}", args.len()),
                    location.clone(),
                ));
            }
            
            // Check if the argument is a callback reference
            if let Some(callback_name) = extract_callback_name(&args[0]) {
                if callback_executor.is_some() {
                    // This will need to be handled asynchronously in the caller
                    return Ok(Some(Value::Object({
                        let mut map = Map::new();
                        map.insert("__builtin_async_op".to_string(), Value::String("map".to_string()));
                        map.insert("callback_name".to_string(), Value::String(callback_name));
                        map.insert("array".to_string(), Value::Array(array.to_vec()));
                        map
                    })));
                } else {
                    return Err(RuntimeError::with_location(
                        "Callback executor not available for Array.map".to_string(),
                        location.clone(),
                    ));
                }
            } else {
                return Err(RuntimeError::with_location(
                    "Array.map expects a callback function reference".to_string(),
                    location.clone(),
                ));
            }
        }
        "filter" => {
            if args.len() != 1 {
                return Err(RuntimeError::with_location(
                    format!("Array.filter expects 1 argument (callback), got {}", args.len()),
                    location.clone(),
                ));
            }
            
            if let Some(callback_name) = extract_callback_name(&args[0]) {
                if callback_executor.is_some() {
                    return Ok(Some(Value::Object({
                        let mut map = Map::new();
                        map.insert("__builtin_async_op".to_string(), Value::String("filter".to_string()));
                        map.insert("callback_name".to_string(), Value::String(callback_name));
                        map.insert("array".to_string(), Value::Array(array.to_vec()));
                        map
                    })));
                } else {
                    return Err(RuntimeError::with_location(
                        "Callback executor not available for Array.filter".to_string(),
                        location.clone(),
                    ));
                }
            } else {
                return Err(RuntimeError::with_location(
                    "Array.filter expects a callback function reference".to_string(),
                    location.clone(),
                ));
            }
        }
        "forEach" => {
            if args.len() != 1 {
                return Err(RuntimeError::with_location(
                    format!("Array.forEach expects 1 argument (callback), got {}", args.len()),
                    location.clone(),
                ));
            }
            
            if let Some(callback_name) = extract_callback_name(&args[0]) {
                if callback_executor.is_some() {
                    return Ok(Some(Value::Object({
                        let mut map = Map::new();
                        map.insert("__builtin_async_op".to_string(), Value::String("forEach".to_string()));
                        map.insert("callback_name".to_string(), Value::String(callback_name));
                        map.insert("array".to_string(), Value::Array(array.to_vec()));
                        map
                    })));
                } else {
                    return Err(RuntimeError::with_location(
                        "Callback executor not available for Array.forEach".to_string(),
                        location.clone(),
                    ));
                }
            } else {
                return Err(RuntimeError::with_location(
                    "Array.forEach expects a callback function reference".to_string(),
                    location.clone(),
                ));
            }
        }
        "reduce" => {
            if args.len() < 1 || args.len() > 2 {
                return Err(RuntimeError::with_location(
                    format!("Array.reduce expects 1-2 arguments (callback, initial), got {}", args.len()),
                    location.clone(),
                ));
            }
            
            if let Some(callback_name) = extract_callback_name(&args[0]) {
                if callback_executor.is_some() {
                    let initial_value = if args.len() > 1 {
                        args[1].clone()
                    } else {
                        Value::Null
                    };
                    
                    return Ok(Some(Value::Object({
                        let mut map = Map::new();
                        map.insert("__builtin_async_op".to_string(), Value::String("reduce".to_string()));
                        map.insert("callback_name".to_string(), Value::String(callback_name));
                        map.insert("array".to_string(), Value::Array(array.to_vec()));
                        map.insert("initial_value".to_string(), initial_value);
                        map.insert("has_initial".to_string(), Value::Bool(args.len() > 1));
                        map
                    })));
                } else {
                    return Err(RuntimeError::with_location(
                        "Callback executor not available for Array.reduce".to_string(),
                        location.clone(),
                    ));
                }
            } else {
                return Err(RuntimeError::with_location(
                    "Array.reduce expects a callback function reference".to_string(),
                    location.clone(),
                ));
            }
        }
        "find" => {
            if args.len() != 1 {
                return Err(RuntimeError::with_location(
                    format!("Array.find expects 1 argument (callback), got {}", args.len()),
                    location.clone(),
                ));
            }
            
            if let Some(callback_name) = extract_callback_name(&args[0]) {
                if callback_executor.is_some() {
                    return Ok(Some(Value::Object({
                        let mut map = Map::new();
                        map.insert("__builtin_async_op".to_string(), Value::String("find".to_string()));
                        map.insert("callback_name".to_string(), Value::String(callback_name));
                        map.insert("array".to_string(), Value::Array(array.to_vec()));
                        map
                    })));
                } else {
                    return Err(RuntimeError::with_location(
                        "Callback executor not available for Array.find".to_string(),
                        location.clone(),
                    ));
                }
            } else {
                return Err(RuntimeError::with_location(
                    "Array.find expects a callback function reference".to_string(),
                    location.clone(),
                ));
            }
        }
        "findIndex" => {
            if args.len() != 1 {
                return Err(RuntimeError::with_location(
                    format!("Array.findIndex expects 1 argument (callback), got {}", args.len()),
                    location.clone(),
                ));
            }
            
            if let Some(callback_name) = extract_callback_name(&args[0]) {
                if callback_executor.is_some() {
                    return Ok(Some(Value::Object({
                        let mut map = Map::new();
                        map.insert("__builtin_async_op".to_string(), Value::String("findIndex".to_string()));
                        map.insert("callback_name".to_string(), Value::String(callback_name));
                        map.insert("array".to_string(), Value::Array(array.to_vec()));
                        map
                    })));
                } else {
                    return Err(RuntimeError::with_location(
                        "Callback executor not available for Array.findIndex".to_string(),
                        location.clone(),
                    ));
                }
            } else {
                return Err(RuntimeError::with_location(
                    "Array.findIndex expects a callback function reference".to_string(),
                    location.clone(),
                ));
            }
        }
        "some" => {
            if args.len() != 1 {
                return Err(RuntimeError::with_location(
                    format!("Array.some expects 1 argument (callback), got {}", args.len()),
                    location.clone(),
                ));
            }
            
            if let Some(callback_name) = extract_callback_name(&args[0]) {
                if callback_executor.is_some() {
                    return Ok(Some(Value::Object({
                        let mut map = Map::new();
                        map.insert("__builtin_async_op".to_string(), Value::String("some".to_string()));
                        map.insert("callback_name".to_string(), Value::String(callback_name));
                        map.insert("array".to_string(), Value::Array(array.to_vec()));
                        map
                    })));
                } else {
                    return Err(RuntimeError::with_location(
                        "Callback executor not available for Array.some".to_string(),
                        location.clone(),
                    ));
                }
            } else {
                return Err(RuntimeError::with_location(
                    "Array.some expects a callback function reference".to_string(),
                    location.clone(),
                ));
            }
        }
        "every" => {
            if args.len() != 1 {
                return Err(RuntimeError::with_location(
                    format!("Array.every expects 1 argument (callback), got {}", args.len()),
                    location.clone(),
                ));
            }
            
            if let Some(callback_name) = extract_callback_name(&args[0]) {
                if callback_executor.is_some() {
                    return Ok(Some(Value::Object({
                        let mut map = Map::new();
                        map.insert("__builtin_async_op".to_string(), Value::String("every".to_string()));
                        map.insert("callback_name".to_string(), Value::String(callback_name));
                        map.insert("array".to_string(), Value::Array(array.to_vec()));
                        map
                    })));
                } else {
                    return Err(RuntimeError::with_location(
                        "Callback executor not available for Array.every".to_string(),
                        location.clone(),
                    ));
                }
            } else {
                return Err(RuntimeError::with_location(
                    "Array.every expects a callback function reference".to_string(),
                    location.clone(),
                ));
            }
        }
        _ => Ok(None), 
    }
}

fn extract_callback_name(value: &Value) -> Option<String> {
    if let Value::Object(map) = value {
        if let (Some(Value::String(type_val)), Some(Value::String(name_val))) = 
            (map.get("type"), map.get("name")) {
            if type_val == "callback_reference" {
                // Check for constant hash first
                if let Some(Value::String(hash_val)) = map.get("hash") {
                    if hash_val == CALLBACK_REFERENCE_HASH {
                        return Some(name_val.clone());
                    }
                }
                // If hash doesn't match, it might be an old format or invalid
                // Still return the name for backward compatibility but this should be validated
                return Some(name_val.clone());
            }
        }
    }
    None
}

fn contains_forbidden_value(value: &Value) -> bool {
    match value {
        Value::Object(map) => {
            map.contains_key(FORBIDDEN_KEY) || map.values().any(contains_forbidden_value)
        }
        Value::Array(arr) => {
            arr.iter().any(contains_forbidden_value)
        }
        _ => false,
    }
}

fn execute_object_method(
    object: &Map<String, Value>,
    method_name: &str,
    args: &[Value],
    location: &SourceLocation,
) -> Result<Option<Value>, RuntimeError> {
    match method_name {
        "keys" => {
            if !args.is_empty() {
                return Err(RuntimeError::with_location(
                    format!("Object.keys expects 0 arguments, got {}", args.len()),
                    location.clone(),
                ));
            }

            let keys: Vec<Value> = object.keys()
                .filter(|&k| k != FORBIDDEN_KEY) // Filter out the forbidden key
                .map(|k| Value::String(k.clone()))
                .collect();

            Ok(Some(Value::Array(keys)))
        }
        "values" => {
            if !args.is_empty() {
                return Err(RuntimeError::with_location(
                    format!("Object.values expects 0 arguments, got {}", args.len()),
                    location.clone(),
                ));
            }

            let values: Vec<Value> = object.iter()
                .filter(|(k, _)| *k != FORBIDDEN_KEY) // Filter out the forbidden key's value
                .map(|(_, v)| v.clone())
                .collect();
            Ok(Some(Value::Array(values)))
        }
        "isEmpty" => {
            if !args.is_empty() {
                return Err(RuntimeError::with_location(
                    format!("Object.isEmpty expects 0 arguments, got {}", args.len()),
                    location.clone(),
                ));
            }
            // Consider the object empty if it only contains the forbidden key
            let is_effectively_empty = object.iter().all(|(k, _)| k == FORBIDDEN_KEY);
            Ok(Some(Value::Bool(is_effectively_empty)))
        }
        "has" => {
            if args.len() != 1 {
                return Err(RuntimeError::with_location(
                    format!("Object.{} expects 1 argument, got {}", method_name, args.len()),
                    location.clone(),
                ));
            }

            match &args[0] {
                Value::String(key) => {
                    if key == FORBIDDEN_KEY {
                        Ok(Some(Value::Bool(false))) // Never report forbidden key as present
                    } else {
                        Ok(Some(Value::Bool(object.contains_key(key))))
                    }
                },
                _ => Err(RuntimeError::with_location(
                    format!("Object.{} expects a string argument", method_name),
                    location.clone(),
                )),
            }
        }
        "entries" => {
            if !args.is_empty() {
                return Err(RuntimeError::with_location(
                    format!("Object.entries expects 0 arguments, got {}", args.len()),
                    location.clone(),
                ));
            }

            let entries: Vec<Value> = object.iter()
                .filter(|(k, _)| *k != FORBIDDEN_KEY) // Filter out the forbidden entry
                .map(|(k, v)| {
                    Value::Array(vec![
                        Value::String(k.clone()),
                        v.clone()
                    ])
                })
                .collect();

            Ok(Some(Value::Array(entries)))
        }
        _ => Ok(None), 
    }
}

fn execute_number_method(
    number: &serde_json::Number,
    method_name: &str,
    args: &[Value],
    location: &SourceLocation,
) -> Result<Option<Value>, RuntimeError> {
    match method_name {
        "toString" => {
            if !args.is_empty() {
                return Err(RuntimeError::with_location(
                    format!("Number.toString expects 0 arguments, got {}", args.len()),
                    location.clone(),
                ));
            }
            
            Ok(Some(Value::String(number.to_string())))
        }
        "toFixed" => {
            if args.len() != 1 {
                return Err(RuntimeError::with_location(
                    format!("Number.toFixed expects 1 argument, got {}", args.len()),
                    location.clone(),
                ));
            }
            
            let digits = match &args[0] {
                Value::Number(n) => {
                    if let Some(d) = n.as_u64() {
                        d as usize
                    } else {
                        return Err(RuntimeError::with_location(
                            "Number.toFixed expects a non-negative integer argument".to_string(),
                            location.clone(),
                        ));
                    }
                },
                _ => return Err(RuntimeError::with_location(
                    "Number.toFixed expects a number argument".to_string(),
                    location.clone(),
                )),
            };
            
            if let Some(n) = number.as_f64() {
                let formatted = format!("{:.*}", digits, n);
                Ok(Some(Value::String(formatted)))
            } else {
                Ok(Some(Value::String(number.to_string())))
            }
        }
        "isInteger" => {
            if !args.is_empty() {
                return Err(RuntimeError::with_location(
                    format!("Number.isInteger expects 0 arguments, got {}", args.len()),
                    location.clone(),
                ));
            }
            
            Ok(Some(Value::Bool(number.is_i64() || number.is_u64())))
        }
        "abs" => {
            if !args.is_empty() {
                return Err(RuntimeError::with_location(
                    format!("Number.abs expects 0 arguments, got {}", args.len()),
                    location.clone(),
                ));
            }
            
            if let Some(n) = number.as_f64() {
                Ok(Some(Value::Number(serde_json::Number::from_f64(n.abs()).unwrap_or_else(|| serde_json::Number::from(0)))))
            } else if let Some(n) = number.as_i64() {
                Ok(Some(Value::Number(n.abs().into())))
            } else {
                
                Ok(Some(Value::Number(number.clone())))
            }
        }
        _ => Ok(None), 
    }
}


fn execute_boolean_method(
    boolean: &bool,
    method_name: &str,
    args: &[Value],
    location: &SourceLocation,
) -> Result<Option<Value>, RuntimeError> {
    match method_name {
        "toString" => {
            if !args.is_empty() {
                return Err(RuntimeError::with_location(
                    format!("Boolean.toString expects 0 arguments, got {}", args.len()),
                    location.clone(),
                ));
            }
            
            Ok(Some(Value::String(boolean.to_string())))
        }
        _ => Ok(None), 
    }
}


fn execute_null_method(
    method_name: &str,
    args: &[Value],
    location: &SourceLocation,
) -> Result<Option<Value>, RuntimeError> {
    match method_name {
        "toString" => {
            if !args.is_empty() {
                return Err(RuntimeError::with_location(
                    format!("null.toString expects 0 arguments, got {}", args.len()),
                    location.clone(),
                ));
            }
            
            Ok(Some(Value::String("null".to_string())))
        }
        _ => Ok(None), 
    }
}

fn value_equals(a: &Value, b: &Value) -> bool {
    match (a, b) {
        (Value::Null, Value::Null) => true,
        (Value::Bool(a_val), Value::Bool(b_val)) => a_val == b_val,
        (Value::Number(a_val), Value::Number(b_val)) => {
            
            if let (Some(a_f64), Some(b_f64)) = (a_val.as_f64(), b_val.as_f64()) {
                (a_f64 - b_f64).abs() < f64::EPSILON
            } else {
                a_val.to_string() == b_val.to_string()
            }
        },
        (Value::String(a_val), Value::String(b_val)) => a_val == b_val,
        _ => false, 
    }
}

fn get_index_arg(
    arg: &Value, 
    min: usize, 
    max: usize, 
    method_name: &str, 
    location: &SourceLocation
) -> Result<usize, RuntimeError> {
    match arg {
        Value::Number(n) => {
            if let Some(idx) = n.as_u64() {
                let idx = idx as usize;
                if idx >= min && idx <= max {
                    Ok(idx)
                } else {
                    Err(RuntimeError::with_location(
                        format!("Index out of bounds in {} method", method_name),
                        location.clone(),
                    ))
                }
            } else if let Some(idx) = n.as_i64() {
                if idx < 0 {
                    Err(RuntimeError::with_location(
                        format!("Negative index not allowed in {} method", method_name),
                        location.clone(),
                    ))
                } else {
                    let idx = idx as usize;
                    if idx >= min && idx <= max {
                        Ok(idx)
                    } else {
                        Err(RuntimeError::with_location(
                            format!("Index out of bounds in {} method", method_name),
                            location.clone(),
                        ))
                    }
                }
            } else {
                Err(RuntimeError::with_location(
                    format!("{} expects integer arguments", method_name),
                    location.clone(),
                ))
            }
        },
        _ => Err(RuntimeError::with_location(
            format!("{} expects number arguments", method_name),
            location.clone(),
        )),
    }
}