rustleaf 0.1.0

A simple programming language interpreter written in Rust
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
use crate::core::Args;
use crate::core::{RustValue, Value};
use anyhow::{anyhow, Result};

// Helper struct that captures the self value for bound methods
#[derive(Debug, Clone)]
pub struct BoundMethod {
    self_value: Value,
    method_func: fn(&Value, Args) -> Result<Value>,
}

impl BoundMethod {
    pub fn new(self_value: &Value, method_func: fn(&Value, Args) -> Result<Value>) -> Self {
        Self {
            self_value: self_value.clone(),
            method_func,
        }
    }
}

#[crate::rust_value_any]
impl RustValue for BoundMethod {
    fn dyn_clone(&self) -> Box<dyn RustValue> {
        Box::new(self.clone())
    }

    fn call(&self, args: Args) -> Result<Value> {
        (self.method_func)(&self.self_value, args)
    }
}

// Helper struct for bound methods using the new Vec<Value> calling paradigm
#[derive(Debug, Clone)]
pub struct BoundMethodVec {
    self_value: Value,
    method_func: fn(Vec<Value>) -> Result<Value>,
}

impl BoundMethodVec {
    pub fn new(self_value: &Value, method_func: fn(Vec<Value>) -> Result<Value>) -> Self {
        Self {
            self_value: self_value.clone(),
            method_func,
        }
    }
}

#[crate::rust_value_any]
impl RustValue for BoundMethodVec {
    fn dyn_clone(&self) -> Box<dyn RustValue> {
        Box::new(self.clone())
    }

    fn call(&self, mut args: Args) -> Result<Value> {
        // Convert Args to Vec<Value> - first element is self, rest are arguments
        let mut values = vec![self.self_value.clone()];
        values.extend(args.rest());
        (self.method_func)(values)
    }
}

// General operator implementations that work for all value types
pub fn op_add(self_value: &Value, mut args: Args) -> Result<Value> {
    args.set_function_name("op_add");

    // For strings, support multiple arguments for efficient concatenation
    if let Value::String(first_str) = self_value {
        let mut result = first_str.clone();

        // Concatenate all remaining arguments
        let remaining_args = args.rest();
        for arg in remaining_args {
            match arg {
                Value::String(s) => result.push_str(&s),
                _ => {
                    return Err(anyhow!(
                        "String concatenation requires all arguments to be strings, got {:?}",
                        arg
                    ))
                }
            }
        }

        args.complete()?;
        return Ok(Value::String(result));
    }

    // For non-strings, fall back to binary operation
    let other = args.expect("other")?;
    args.complete()?;

    match (self_value, &other) {
        // Integer arithmetic
        (Value::Int(a), Value::Int(b)) => Ok(Value::Int(a + b)),

        // Float arithmetic (includes mixed int/float operations)
        (Value::Int(a), Value::Float(b)) => Ok(Value::Float(*a as f64 + b)),
        (Value::Float(a), Value::Float(b)) => Ok(Value::Float(a + b)),
        (Value::Float(a), Value::Int(b)) => Ok(Value::Float(a + *b as f64)),

        _ => Err(anyhow!("Cannot add {:?} to {:?}", other, self_value)),
    }
}

pub fn op_sub(self_value: &Value, mut args: Args) -> Result<Value> {
    args.set_function_name("op_sub");
    let other = args.expect("other")?;
    args.complete()?;

    match (self_value, &other) {
        // Integer arithmetic
        (Value::Int(a), Value::Int(b)) => Ok(Value::Int(a - b)),

        // Float arithmetic (includes mixed int/float operations)
        (Value::Int(a), Value::Float(b)) => Ok(Value::Float(*a as f64 - b)),
        (Value::Float(a), Value::Float(b)) => Ok(Value::Float(a - b)),
        (Value::Float(a), Value::Int(b)) => Ok(Value::Float(a - *b as f64)),

        _ => Err(anyhow!("Cannot subtract {:?} from {:?}", other, self_value)),
    }
}

pub fn op_mul(self_value: &Value, mut args: Args) -> Result<Value> {
    args.set_function_name("op_mul");
    let other = args.expect("other")?;
    args.complete()?;

    match (self_value, &other) {
        // Integer arithmetic
        (Value::Int(a), Value::Int(b)) => Ok(Value::Int(a * b)),

        // Float arithmetic (includes mixed int/float operations)
        (Value::Int(a), Value::Float(b)) => Ok(Value::Float(*a as f64 * b)),
        (Value::Float(a), Value::Float(b)) => Ok(Value::Float(a * b)),
        (Value::Float(a), Value::Int(b)) => Ok(Value::Float(a * *b as f64)),

        _ => Err(anyhow!("Cannot multiply {:?} by {:?}", self_value, other)),
    }
}

pub fn op_div(self_value: &Value, mut args: Args) -> Result<Value> {
    args.set_function_name("op_div");
    let other = args.expect("other")?;
    args.complete()?;

    match (self_value, &other) {
        // All division returns float (including int/int)
        (Value::Int(a), Value::Int(b)) => {
            if *b == 0 {
                Err(anyhow!("Division by zero"))
            } else {
                Ok(Value::Float(*a as f64 / *b as f64))
            }
        }
        (Value::Int(a), Value::Float(b)) => {
            if *b == 0.0 {
                Err(anyhow!("Division by zero"))
            } else {
                Ok(Value::Float(*a as f64 / b))
            }
        }
        (Value::Float(a), Value::Float(b)) => {
            if *b == 0.0 {
                Err(anyhow!("Division by zero"))
            } else {
                Ok(Value::Float(a / b))
            }
        }
        (Value::Float(a), Value::Int(b)) => {
            if *b == 0 {
                Err(anyhow!("Division by zero"))
            } else {
                Ok(Value::Float(a / *b as f64))
            }
        }

        _ => Err(anyhow!("Cannot divide {:?} by {:?}", self_value, other)),
    }
}

pub fn op_neg(self_value: &Value, mut args: Args) -> Result<Value> {
    args.set_function_name("op_neg");
    args.complete()?;

    match self_value {
        Value::Int(n) => Ok(Value::Int(-n)),
        Value::Float(f) => Ok(Value::Float(-f)),
        _ => Err(anyhow!("Cannot negate {:?}", self_value)),
    }
}

// Comparison operators
pub fn op_eq(self_value: &Value, mut args: Args) -> Result<Value> {
    args.set_function_name("op_eq");
    let other = args.expect("other")?;
    args.complete()?;

    let result = match (self_value, &other) {
        // Same type comparisons
        (Value::Int(a), Value::Int(b)) => a == b,
        (Value::Float(a), Value::Float(b)) => a == b,
        (Value::String(a), Value::String(b)) => a == b,
        (Value::Bool(a), Value::Bool(b)) => a == b,
        (Value::Null, Value::Null) => true,
        (Value::Unit, Value::Unit) => true,

        // Mixed numeric comparisons
        (Value::Int(a), Value::Float(b)) => *a as f64 == *b,
        (Value::Float(a), Value::Int(b)) => *a == *b as f64,

        // List comparisons
        (Value::List(a), Value::List(b)) => {
            let list_a = a.borrow();
            let list_b = b.borrow();

            // Check length first
            if list_a.len() != list_b.len() {
                return Ok(Value::Bool(false));
            }

            // Compare elements recursively
            for (elem_a, elem_b) in list_a.iter().zip(list_b.iter()) {
                // Use op_eq recursively for each element
                let eq_result = op_eq(elem_a, Args::positional(vec![elem_b.clone()]))?;
                match eq_result {
                    Value::Bool(false) => return Ok(Value::Bool(false)),
                    Value::Bool(true) => continue,
                    _ => unreachable!("op_eq should always return Bool"),
                }
            }

            true
        }

        // Dictionary comparisons
        (Value::Dict(a), Value::Dict(b)) => {
            let dict_a = a.borrow();
            let dict_b = b.borrow();

            // Check if they have the same number of keys
            if dict_a.len() != dict_b.len() {
                return Ok(Value::Bool(false));
            }

            // Compare each key-value pair
            for (key, value_a) in dict_a.iter() {
                match dict_b.get(key) {
                    Some(value_b) => {
                        // Use op_eq recursively for each value
                        let eq_result = op_eq(value_a, Args::positional(vec![value_b.clone()]))?;
                        match eq_result {
                            Value::Bool(false) => return Ok(Value::Bool(false)),
                            Value::Bool(true) => continue,
                            _ => unreachable!("op_eq should always return Bool"),
                        }
                    }
                    None => return Ok(Value::Bool(false)), // Key not found in dict_b
                }
            }

            true
        }

        // Everything else is false
        _ => false,
    };

    Ok(Value::Bool(result))
}

pub fn op_ne(self_value: &Value, mut args: Args) -> Result<Value> {
    args.set_function_name("op_ne");
    let other = args.expect("other")?;
    args.complete()?;

    // Use op_eq and negate the result
    let eq_result = op_eq(self_value, Args::positional(vec![other]))?;
    match eq_result {
        Value::Bool(b) => Ok(Value::Bool(!b)),
        _ => unreachable!("op_eq should always return Bool"),
    }
}

pub fn op_lt(self_value: &Value, mut args: Args) -> Result<Value> {
    args.set_function_name("op_lt");
    let other = args.expect("other")?;
    args.complete()?;

    let result = match (self_value, &other) {
        // Integer comparisons
        (Value::Int(a), Value::Int(b)) => a < b,

        // Float comparisons (includes mixed int/float)
        (Value::Int(a), Value::Float(b)) => (*a as f64) < *b,
        (Value::Float(a), Value::Float(b)) => a < b,
        (Value::Float(a), Value::Int(b)) => *a < (*b as f64),

        // String comparisons
        (Value::String(a), Value::String(b)) => a < b,

        _ => return Err(anyhow!("Cannot compare {:?} < {:?}", self_value, other)),
    };

    Ok(Value::Bool(result))
}

pub fn op_le(self_value: &Value, mut args: Args) -> Result<Value> {
    args.set_function_name("op_le");
    let other = args.expect("other")?;
    args.complete()?;

    let result = match (self_value, &other) {
        // Integer comparisons
        (Value::Int(a), Value::Int(b)) => a <= b,

        // Float comparisons (includes mixed int/float)
        (Value::Int(a), Value::Float(b)) => (*a as f64) <= *b,
        (Value::Float(a), Value::Float(b)) => a <= b,
        (Value::Float(a), Value::Int(b)) => *a <= (*b as f64),

        // String comparisons
        (Value::String(a), Value::String(b)) => a <= b,

        _ => return Err(anyhow!("Cannot compare {:?} <= {:?}", self_value, other)),
    };

    Ok(Value::Bool(result))
}

pub fn op_gt(self_value: &Value, mut args: Args) -> Result<Value> {
    args.set_function_name("op_gt");
    let other = args.expect("other")?;
    args.complete()?;

    let result = match (self_value, &other) {
        // Integer comparisons
        (Value::Int(a), Value::Int(b)) => a > b,

        // Float comparisons (includes mixed int/float)
        (Value::Int(a), Value::Float(b)) => (*a as f64) > *b,
        (Value::Float(a), Value::Float(b)) => a > b,
        (Value::Float(a), Value::Int(b)) => *a > (*b as f64),

        // String comparisons
        (Value::String(a), Value::String(b)) => a > b,

        _ => return Err(anyhow!("Cannot compare {:?} > {:?}", self_value, other)),
    };

    Ok(Value::Bool(result))
}

pub fn op_ge(self_value: &Value, mut args: Args) -> Result<Value> {
    args.set_function_name("op_ge");
    let other = args.expect("other")?;
    args.complete()?;

    let result = match (self_value, &other) {
        // Integer comparisons
        (Value::Int(a), Value::Int(b)) => a >= b,

        // Float comparisons (includes mixed int/float)
        (Value::Int(a), Value::Float(b)) => (*a as f64) >= *b,
        (Value::Float(a), Value::Float(b)) => a >= b,
        (Value::Float(a), Value::Int(b)) => *a >= (*b as f64),

        // String comparisons
        (Value::String(a), Value::String(b)) => a >= b,

        _ => return Err(anyhow!("Cannot compare {:?} >= {:?}", self_value, other)),
    };

    Ok(Value::Bool(result))
}

// Additional arithmetic operators
pub fn op_mod(self_value: &Value, mut args: Args) -> Result<Value> {
    args.set_function_name("op_mod");
    let other = args.expect("other")?;
    args.complete()?;

    match (self_value, &other) {
        // Integer modulo
        (Value::Int(a), Value::Int(b)) => {
            if *b == 0 {
                Err(anyhow!("Modulo by zero"))
            } else {
                Ok(Value::Int(a % b))
            }
        }

        // Float modulo (includes mixed int/float operations)
        (Value::Int(a), Value::Float(b)) => {
            if *b == 0.0 {
                Err(anyhow!("Modulo by zero"))
            } else {
                Ok(Value::Float((*a as f64) % b))
            }
        }
        (Value::Float(a), Value::Float(b)) => {
            if *b == 0.0 {
                Err(anyhow!("Modulo by zero"))
            } else {
                Ok(Value::Float(a % b))
            }
        }
        (Value::Float(a), Value::Int(b)) => {
            if *b == 0 {
                Err(anyhow!("Modulo by zero"))
            } else {
                Ok(Value::Float(a % (*b as f64)))
            }
        }

        _ => Err(anyhow!(
            "Cannot compute modulo of {:?} and {:?}",
            self_value,
            other
        )),
    }
}

pub fn op_pow(self_value: &Value, mut args: Args) -> Result<Value> {
    args.set_function_name("op_pow");
    let other = args.expect("other")?;
    args.complete()?;

    match (self_value, &other) {
        // Integer power - return int if exponent is non-negative, float otherwise
        (Value::Int(a), Value::Int(b)) => {
            if *b >= 0 {
                match a.checked_pow(*b as u32) {
                    Some(result) => Ok(Value::Int(result)),
                    None => {
                        // Overflow, fall back to float
                        Ok(Value::Float((*a as f64).powf(*b as f64)))
                    }
                }
            } else {
                // Negative exponent always returns float
                Ok(Value::Float((*a as f64).powf(*b as f64)))
            }
        }

        // Float power (includes mixed int/float operations)
        (Value::Int(a), Value::Float(b)) => Ok(Value::Float((*a as f64).powf(*b))),
        (Value::Float(a), Value::Float(b)) => Ok(Value::Float(a.powf(*b))),
        (Value::Float(a), Value::Int(b)) => Ok(Value::Float(a.powf(*b as f64))),

        _ => Err(anyhow!(
            "Cannot compute power of {:?} and {:?}",
            self_value,
            other
        )),
    }
}

// Bitwise operators (only work on integers)
pub fn op_bitwise_and(self_value: &Value, mut args: Args) -> Result<Value> {
    args.set_function_name("op_bitwise_and");
    let other = args.expect("other")?;
    args.complete()?;

    match (self_value, &other) {
        (Value::Int(a), Value::Int(b)) => Ok(Value::Int(a & b)),
        _ => Err(anyhow!(
            "Bitwise AND requires integers, got {:?} and {:?}",
            self_value,
            other
        )),
    }
}

pub fn op_bitwise_or(self_value: &Value, mut args: Args) -> Result<Value> {
    args.set_function_name("op_bitwise_or");
    let other = args.expect("other")?;
    args.complete()?;

    match (self_value, &other) {
        (Value::Int(a), Value::Int(b)) => Ok(Value::Int(a | b)),
        _ => Err(anyhow!(
            "Bitwise OR requires integers, got {:?} and {:?}",
            self_value,
            other
        )),
    }
}

pub fn op_bitwise_xor(self_value: &Value, mut args: Args) -> Result<Value> {
    args.set_function_name("op_bitwise_xor");
    let other = args.expect("other")?;
    args.complete()?;

    match (self_value, &other) {
        (Value::Int(a), Value::Int(b)) => Ok(Value::Int(a ^ b)),
        _ => Err(anyhow!(
            "Bitwise XOR requires integers, got {:?} and {:?}",
            self_value,
            other
        )),
    }
}

pub fn op_bitwise_not(self_value: &Value, mut args: Args) -> Result<Value> {
    args.set_function_name("op_bitwise_not");
    args.complete()?;

    match self_value {
        Value::Int(n) => Ok(Value::Int(!n)),
        _ => Err(anyhow!(
            "Bitwise NOT requires integer, got {:?}",
            self_value
        )),
    }
}

pub fn op_lshift(self_value: &Value, mut args: Args) -> Result<Value> {
    args.set_function_name("op_lshift");
    let other = args.expect("other")?;
    args.complete()?;

    match (self_value, &other) {
        (Value::Int(a), Value::Int(b)) => {
            if *b < 0 {
                Err(anyhow!("Cannot left shift by negative amount: {}", b))
            } else if *b >= 64 {
                Err(anyhow!("Cannot left shift by more than 63 bits: {}", b))
            } else {
                Ok(Value::Int(a << b))
            }
        }
        _ => Err(anyhow!(
            "Left shift requires integers, got {:?} and {:?}",
            self_value,
            other
        )),
    }
}

pub fn op_rshift(self_value: &Value, mut args: Args) -> Result<Value> {
    args.set_function_name("op_rshift");
    let other = args.expect("other")?;
    args.complete()?;

    match (self_value, &other) {
        (Value::Int(a), Value::Int(b)) => {
            if *b < 0 {
                Err(anyhow!("Cannot right shift by negative amount: {}", b))
            } else if *b >= 64 {
                Err(anyhow!("Cannot right shift by more than 63 bits: {}", b))
            } else {
                Ok(Value::Int(a >> b))
            }
        }
        _ => Err(anyhow!(
            "Right shift requires integers, got {:?} and {:?}",
            self_value,
            other
        )),
    }
}

// Container operations
pub fn op_contains(self_value: &Value, mut args: Args) -> Result<Value> {
    args.set_function_name("op_contains");
    let item = args.expect("item")?;
    args.complete()?;

    match self_value {
        Value::String(s) => {
            // Check if item is a substring
            match &item {
                Value::String(needle) => Ok(Value::Bool(s.contains(needle))),
                _ => Err(anyhow!(
                    "String contains requires string argument, got {:?}",
                    item
                )),
            }
        }
        Value::List(list_ref) => {
            // Check if item is in the list
            let list = list_ref.borrow();
            for list_item in list.iter() {
                if *list_item == item {
                    return Ok(Value::Bool(true));
                }
            }
            Ok(Value::Bool(false))
        }
        Value::Dict(dict_ref) => {
            // Check if key exists in dictionary
            let dict = dict_ref.borrow();
            let key_str = match &item {
                Value::String(s) => s.clone(),
                Value::Int(i) => i.to_string(),
                Value::Float(f) => f.to_string(),
                Value::Bool(b) => b.to_string(),
                _ => {
                    return Err(anyhow!(
                        "Dictionary contains requires string, number, or boolean key, got {:?}",
                        item
                    ))
                }
            };
            Ok(Value::Bool(dict.contains_key(&key_str)))
        }
        Value::Range(range) => {
            // Check if integer is in range
            match &item {
                Value::Int(i) => {
                    let in_range = if range.inclusive {
                        *i >= range.start && *i <= range.end
                    } else {
                        *i >= range.start && *i < range.end
                    };
                    Ok(Value::Bool(in_range))
                }
                _ => Err(anyhow!(
                    "Range contains requires integer argument, got {:?}",
                    item
                )),
            }
        }
        _ => Err(anyhow!(
            "Contains operation not supported for {:?}",
            self_value
        )),
    }
}

// List indexing operations
pub fn op_get_item_list(self_value: &Value, mut args: Args) -> Result<Value> {
    args.set_function_name("op_get_item");
    let index = args.expect("index")?;
    args.complete()?;

    match self_value {
        Value::List(list_ref) => {
            let list = list_ref.borrow();
            match &index {
                Value::Int(i) => {
                    let idx = if *i < 0 {
                        // Negative indexing: -1 is last element
                        (list.len() as i64 + i) as usize
                    } else {
                        *i as usize
                    };

                    if idx < list.len() {
                        Ok(list[idx].clone())
                    } else {
                        Err(anyhow!(
                            "List index {} out of range (length: {})",
                            i,
                            list.len()
                        ))
                    }
                }
                _ => Err(anyhow!("List index must be integer, got {:?}", index)),
            }
        }
        _ => Err(anyhow!(
            "op_get_item_list called on non-list: {:?}",
            self_value
        )),
    }
}

pub fn op_set_item_list(self_value: &Value, mut args: Args) -> Result<Value> {
    args.set_function_name("op_set_item");
    let index = args.expect("index")?;
    let value = args.expect("value")?;
    args.complete()?;

    match self_value {
        Value::List(list_ref) => {
            let mut list = list_ref.borrow_mut();
            match &index {
                Value::Int(i) => {
                    let idx = if *i < 0 {
                        // Negative indexing: -1 is last element
                        (list.len() as i64 + i) as usize
                    } else {
                        *i as usize
                    };

                    if idx < list.len() {
                        list[idx] = value;
                        Ok(Value::Unit)
                    } else {
                        Err(anyhow!(
                            "List index {} out of range (length: {})",
                            i,
                            list.len()
                        ))
                    }
                }
                _ => Err(anyhow!("List index must be integer, got {:?}", index)),
            }
        }
        _ => Err(anyhow!(
            "op_set_item_list called on non-list: {:?}",
            self_value
        )),
    }
}

// Dictionary indexing operations
pub fn op_get_item_dict(self_value: &Value, mut args: Args) -> Result<Value> {
    args.set_function_name("op_get_item");
    let key = args.expect("key")?;
    args.complete()?;

    match self_value {
        Value::Dict(dict_ref) => {
            let dict = dict_ref.borrow();
            let key_str = match &key {
                Value::String(s) => s.clone(),
                Value::Int(i) => i.to_string(),
                Value::Float(f) => f.to_string(),
                Value::Bool(b) => b.to_string(),
                _ => {
                    return Err(anyhow!(
                        "Dictionary key must be string, number, or boolean, got {:?}",
                        key
                    ))
                }
            };

            match dict.get(&key_str) {
                Some(value) => Ok(value.clone()),
                None => Err(anyhow!("Key '{}' not found in dictionary", key_str)),
            }
        }
        _ => Err(anyhow!(
            "op_get_item_dict called on non-dict: {:?}",
            self_value
        )),
    }
}

pub fn op_set_item_dict(self_value: &Value, mut args: Args) -> Result<Value> {
    args.set_function_name("op_set_item");
    let key = args.expect("key")?;
    let value = args.expect("value")?;
    args.complete()?;

    match self_value {
        Value::Dict(dict_ref) => {
            let mut dict = dict_ref.borrow_mut();
            let key_str = match &key {
                Value::String(s) => s.clone(),
                Value::Int(i) => i.to_string(),
                Value::Float(f) => f.to_string(),
                Value::Bool(b) => b.to_string(),
                _ => {
                    return Err(anyhow!(
                        "Dictionary key must be string, number, or boolean, got {:?}",
                        key
                    ))
                }
            };

            dict.insert(key_str, value);
            Ok(Value::Unit)
        }
        _ => Err(anyhow!(
            "op_set_item_dict called on non-dict: {:?}",
            self_value
        )),
    }
}

// Range-specific operations
pub fn range_to_list(self_value: &Value, mut args: Args) -> Result<Value> {
    args.set_function_name("to_list");
    args.complete()?;

    match self_value {
        Value::Range(range) => {
            let mut values = Vec::new();
            let end_value = if range.inclusive {
                range.end + 1
            } else {
                range.end
            };

            for i in range.start..end_value {
                values.push(Value::Int(i));
            }

            Ok(Value::new_list_with_values(values))
        }
        _ => Err(anyhow!("to_list called on non-range: {:?}", self_value)),
    }
}