nilang 0.4.1

A scripting language interpreter for Advent of Code
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
use sandpit::{Gc, Mutator};

use crate::symbol_map::SymID;

use super::error::RuntimeErrorKind;
use super::hash_map::GcHashMap;
use super::list::List;
use super::string::VMString;
use super::type_objects::TypeObjects;
use super::value::Value;
use super::RuntimeError;

pub fn add<'gc>(lhs: Value<'gc>, rhs: Value<'gc>) -> Result<Value<'gc>, RuntimeError> {
    match (lhs, rhs) {
        (Value::Int(lhs), Value::Int(rhs)) => Ok(match lhs.checked_add(rhs) {
            Some(val) => Value::Int(val),
            None => Value::Float(lhs as f64 + rhs as f64),
        }),
        (Value::Float(lhs), Value::Float(rhs)) => Ok(Value::Float(lhs + rhs)),
        (Value::Float(f), Value::Int(i)) | (Value::Int(i), Value::Float(f)) => {
            Ok(Value::Float(f + i as f64))
        }
        (lhs, rhs) => Err(RuntimeError::new(
            RuntimeErrorKind::TypeError,
            Some(format!(
                "Attempted to add {} with {}",
                lhs.type_str(),
                rhs.type_str()
            )),
            None
        ))
    }
}

pub fn sub<'gc>(lhs: Value<'gc>, rhs: Value<'gc>) -> Result<Value<'gc>, RuntimeError> {
    match (lhs, rhs) {
        (Value::Int(lhs), Value::Int(rhs)) => Ok(match lhs.checked_sub(rhs) {
            Some(val) => Value::Int(val),
            None => Value::Float(lhs as f64 - rhs as f64),
        }),
        (Value::Float(lhs), Value::Float(rhs)) => Ok(Value::Float(lhs - rhs)),
        (Value::Float(lhs), Value::Int(rhs)) => Ok(Value::Float(lhs - rhs as f64)),
        (Value::Int(lhs), Value::Float(rhs)) => Ok(Value::Float(lhs as f64 - rhs)),
        (lhs, rhs) => Err(RuntimeError::new(
            RuntimeErrorKind::TypeError,
            Some(format!(
                "Attempted to subtract {} with {}",
                lhs.type_str(),
                rhs.type_str()
            )),
            None
        ))
    }
}

pub fn multiply<'gc>(lhs: Value<'gc>, rhs: Value<'gc>) -> Result<Value<'gc>, RuntimeError> {
    match (lhs, rhs) {
        (Value::Int(lhs), Value::Int(rhs)) => Ok(match lhs.checked_mul(rhs) {
            Some(val) => Value::Int(val),
            None => Value::Float(lhs as f64 * rhs as f64),
        }),
        (Value::Float(lhs), Value::Float(rhs)) => Ok(Value::Float(lhs * rhs)),
        (Value::Float(f), Value::Int(i)) | (Value::Int(i), Value::Float(f)) => {
            Ok(Value::Float(f * i as f64))
        }
        (lhs, rhs) => Err(RuntimeError::new(
            RuntimeErrorKind::TypeError,
            Some(format!(
                "Attempted to multiply {} with {}",
                lhs.type_str(),
                rhs.type_str()
            )),
            None
        ))
    }
}

pub fn divide<'gc>(lhs: Value<'gc>, rhs: Value<'gc>) -> Result<Value<'gc>, RuntimeError> {
    match (lhs, rhs) {
        (_, Value::Int(0)) | (_, Value::Float(0.0))=> Err(RuntimeError::new(
            RuntimeErrorKind::DivideByZero,
            Some("Attempted to divide by zero".to_string()),
            None
        )),
        (Value::Int(lhs), Value::Int(rhs)) => Ok(match lhs.checked_div(rhs) {
            Some(val) => Value::Int(val),
            None => Value::Float(lhs as f64 / rhs as f64),
        }),
        (Value::Float(lhs), Value::Float(rhs)) => Ok(Value::Float(lhs / rhs)),
        (Value::Float(lhs), Value::Int(rhs)) => Ok(Value::Float(lhs / rhs as f64)),
        (Value::Int(lhs), Value::Float(rhs)) => Ok(Value::Float(lhs as f64 / rhs)),
        (lhs, rhs) => Err(RuntimeError::new(
            RuntimeErrorKind::TypeError,
            Some(format!(
                "Attempted to divide {} with {}",
                lhs.type_str(),
                rhs.type_str()
            )),
            None
        ))
    }
}

pub fn modulo<'gc>(lhs: Value<'gc>, rhs: Value<'gc>) -> Result<Value<'gc>, RuntimeError> {
    match (lhs, rhs) {
        (_, Value::Int(0)) | (_, Value::Float(0.0))=> Err(RuntimeError::new(
            RuntimeErrorKind::DivideByZero,
            Some("Attempted to modulo by zero".to_string()),
            None
        )),
        (Value::Float(lhs), Value::Float(rhs)) => Ok(Value::Float(lhs % rhs)),
        (Value::Int(lhs), Value::Int(rhs)) => Ok(Value::Int(lhs % rhs)),
        (Value::Float(lhs), Value::Int(rhs)) => Ok(Value::Float(lhs % rhs as f64)),
        (Value::Int(lhs), Value::Float(rhs)) => Ok(Value::Float(lhs as f64 % rhs)),
        (lhs, rhs) => Err(RuntimeError::new(
            RuntimeErrorKind::TypeError,
            Some(format!(
                "Attempted to modulo {} with {}",
                lhs.type_str(),
                rhs.type_str()
            )),
            None
        ))
    }
}

pub fn less_than<'gc>(lhs: Value<'gc>, rhs: Value<'gc>) -> Result<Value<'gc>, RuntimeError> {
    match (lhs, rhs) {
        (Value::Float(lhs), Value::Float(rhs)) => Ok(Value::Bool(lhs < rhs)),
        (Value::Int(lhs), Value::Int(rhs)) => Ok(Value::Bool(lhs < rhs)),
        (Value::Float(lhs), Value::Int(rhs)) => Ok(Value::Bool(lhs < rhs as f64)),
        (Value::Int(lhs), Value::Float(rhs)) => Ok(Value::Bool((lhs as f64) < rhs)),
        (lhs, rhs) => Err(RuntimeError::new(
            RuntimeErrorKind::TypeError,
            Some(format!(
                "Attempted to perform comparison between {} and {}",
                lhs.type_str(),
                rhs.type_str()
            )),
            None
        ))
    }
}

pub fn less_than_or_equal<'gc>(lhs: Value<'gc>, rhs: Value<'gc>) -> Result<Value<'gc>, RuntimeError> {
    match (lhs, rhs) {
        (Value::Float(lhs), Value::Float(rhs)) => Ok(Value::Bool(lhs <= rhs)),
        (Value::Int(lhs), Value::Int(rhs)) => Ok(Value::Bool(lhs <= rhs)),
        (Value::Float(lhs), Value::Int(rhs)) => Ok(Value::Bool(lhs <= rhs as f64)),
        (Value::Int(lhs), Value::Float(rhs)) => Ok(Value::Bool((lhs as f64) <= rhs)),
        (lhs, rhs) => Err(RuntimeError::new(
            RuntimeErrorKind::TypeError,
            Some(format!(
                "Attempted to perform comparison between {} and {}",
                lhs.type_str(),
                rhs.type_str()
            )),
            None
        ))
    }
}

pub fn greater_than<'gc>(lhs: Value<'gc>, rhs: Value<'gc>) -> Result<Value<'gc>, RuntimeError> {
    match (lhs, rhs) {
        (Value::Float(lhs), Value::Float(rhs)) => Ok(Value::Bool(lhs > rhs)),
        (Value::Int(lhs), Value::Int(rhs)) => Ok(Value::Bool(lhs > rhs)),
        (Value::Float(lhs), Value::Int(rhs)) => Ok(Value::Bool(lhs > rhs as f64)),
        (Value::Int(lhs), Value::Float(rhs)) => Ok(Value::Bool((lhs as f64) > rhs)),
        (lhs, rhs) => Err(RuntimeError::new(
            RuntimeErrorKind::TypeError,
            Some(format!(
                "Attempted to perform comparison between {} and {}",
                lhs.type_str(),
                rhs.type_str()
            )),
            None
        ))
    }
}

pub fn greater_than_or_equal<'gc>(lhs: Value<'gc>, rhs: Value<'gc>) -> Result<Value<'gc>, RuntimeError> {
    match (lhs, rhs) {
        (Value::Float(lhs), Value::Float(rhs)) => Ok(Value::Bool(lhs >= rhs)),
        (Value::Int(lhs), Value::Int(rhs)) => Ok(Value::Bool(lhs >= rhs)),
        (Value::Float(lhs), Value::Int(rhs)) => Ok(Value::Bool(lhs >= rhs as f64)),
        (Value::Int(lhs), Value::Float(rhs)) => Ok(Value::Bool((lhs as f64) >= rhs)),
        (lhs, rhs) => Err(RuntimeError::new(
            RuntimeErrorKind::TypeError,
            Some(format!(
                "Attempted to perform comparison between {} and {}",
                lhs.type_str(),
                rhs.type_str()
            )),
            None
        ))
    }
}

pub fn bit_shift<'gc>(lhs: Value<'gc>, rhs: Value<'gc>) -> Result<Value<'gc>, RuntimeError> {
    match (lhs, rhs) {
        (Value::Int(lhs), Value::Int(rhs)) => {
            if rhs > 0 {
                Ok(Value::Int(lhs << rhs))
            } else {
                Ok(Value::Int(lhs >> rhs.abs()))
            }
        }
        (lhs, rhs) => Err(RuntimeError::new(
            RuntimeErrorKind::TypeError,
            Some(format!(
                "Attempted to perform bit shift between {} and {}",
                lhs.type_str(),
                rhs.type_str()
            )),
            None
        ))
    }
}

pub fn bit_xor<'gc>(lhs: Value<'gc>, rhs: Value<'gc>) -> Result<Value<'gc>, RuntimeError> {
    match (lhs, rhs) {
        (Value::Int(lhs), Value::Int(rhs)) => {
            Ok(Value::Int(lhs ^ rhs))
        }
        (lhs, rhs) => Err(RuntimeError::new(
            RuntimeErrorKind::TypeError,
            Some(format!(
                "Attempted to perform bitwise 'xor' between {} and {}",
                lhs.type_str(),
                rhs.type_str()
            )),
            None
        ))
    }
}

pub fn bit_or<'gc>(lhs: Value<'gc>, rhs: Value<'gc>) -> Result<Value<'gc>, RuntimeError> {
    match (lhs, rhs) {
        (Value::Int(lhs), Value::Int(rhs)) => {
            Ok(Value::Int(lhs | rhs))
        }
        (lhs, rhs) => Err(RuntimeError::new(
            RuntimeErrorKind::TypeError,
            Some(format!(
                "Attempted to perform bitwise 'or' between {} and {}",
                lhs.type_str(),
                rhs.type_str()
            )),
            None
        ))
    }
}

pub fn bit_and<'gc>(lhs: Value<'gc>, rhs: Value<'gc>) -> Result<Value<'gc>, RuntimeError> {
    match (lhs, rhs) {
        (Value::Int(lhs), Value::Int(rhs)) => {
            Ok(Value::Int(lhs & rhs))
        }
        (lhs, rhs) => Err(RuntimeError::new(
            RuntimeErrorKind::TypeError,
            Some(format!(
                "Attempted to perform bitwise 'and' between {} and {}",
                lhs.type_str(),
                rhs.type_str()
            )),
            None
        ))
    }
}
pub fn bit_flip<'gc>(src: Value<'gc>) -> Result<Value<'gc>, RuntimeError> {
    match src {
        Value::Int(src) => {
            Ok(Value::Int(!src))
        }
        src => Err(RuntimeError::new(
            RuntimeErrorKind::TypeError,
            Some(format!(
                "Attempted to perform bit flip on {}",
                src.type_str(),
            )),
            None
        ))
    }
}

pub fn equal<'gc>(lhs: Value<'gc>, rhs: Value<'gc>) -> Value<'gc>{
    Value::Bool(lhs.is_equal_to(&rhs))
}

pub fn not_equal<'gc>(lhs: Value<'gc>, rhs: Value<'gc>) -> Value<'gc> {
    Value::Bool(!lhs.is_equal_to(&rhs))
}

pub fn mem_load<'gc>(
    store: Value<'gc>,
    key: Value<'gc>,
    type_objects: &TypeObjects<'gc>,
    mu: &'gc Mutator,
) -> Result<Value<'gc>, RuntimeError> {
    match (store, key) {
        (Value::List(list), Value::Int(idx)) => {
            let out_of_bounds = if idx >= 0  {
                list.len() <= idx as usize
            } else if idx == i64::MIN {
                // Handle edge case: i64::MIN has no valid positive representation
                true
            } else {
                list.len() < idx.unsigned_abs() as usize
            };

            if out_of_bounds {
                return Err(RuntimeError::new(
                        RuntimeErrorKind::OutOfBoundsAccess,
                        Some(format!("Attempted to access list of len {} at index {}", list.len(), idx)),
                        None
                    ));
            }

            let adjusted_idx = if idx >= 0  {
                idx as usize
            } else {
                list.len() - idx.unsigned_abs() as usize
            };

            Ok(list.at(adjusted_idx))
        }
        (Value::String(s), Value::Int(idx)) => {
            let out_of_bounds = if idx >= 0  {
                s.len() <= idx as usize
            } else if idx == i64::MIN {
                // Handle edge case: i64::MIN has no valid positive representation
                true
            } else {
                s.len() < idx.unsigned_abs() as usize
            };

            if out_of_bounds {
                return Err(RuntimeError::new(
                        RuntimeErrorKind::OutOfBoundsAccess,
                        Some(format!("Attempted to access string of len {} at index {}", s.len(), idx)),
                        None
                    ));
            }

            let adjusted_idx = if idx >= 0  {
                idx as usize
            } else {
                s.len() - idx.unsigned_abs() as usize
            };

            if let Some(c) = s.at(adjusted_idx) {
                let text: [char; 1] = [c];
                let vm_str = VMString::alloc(text.into_iter(), mu);

                Ok(Value::String(Gc::new(mu, vm_str)))
            } else {
                // This should be unreachable due to bounds checking above
                Ok(Value::Null)
            }
        }
        (Value::Map(map), key) => {
            let tagged_key = key.as_tagged(mu);
            if let Some(val) = map.get(&tagged_key.clone()) {
                match Value::from(&val) {
                    Value::Func(func) => {
                        if func.auto_binds() {
                            bind(Value::Func(func), Value::Map(map.clone()), mu)
                        } else {
                            Ok(Value::Func(func))
                        }
                    }
                    value => Ok(value)
                }
            } else if let Value::SymId(sym_id) = Value::from(&tagged_key) {
                access_type_object(Value::Map(map), sym_id, type_objects, mu)
            } else {
                Ok(Value::Null)
            }
        }
        (store, Value::SymId(sym_id)) => access_type_object(store, sym_id, type_objects, mu),
        (lhs, rhs) => Err(RuntimeError::new(
            RuntimeErrorKind::TypeError,
            Some(format!(
                "Invalid memory access of {} via a {}",
                lhs.type_str(),
                rhs.type_str()
            )),
            None
        ))
    }
}

fn access_type_object<'gc>(
    store_value: Value<'gc>,
    key: SymID,
    type_objects: &TypeObjects<'gc>,
    mu: &'gc Mutator,
) -> Result<Value<'gc>, RuntimeError> {
    let type_obj = type_objects.get_type_obj(store_value.get_type_id()).unwrap();
    if let Some(val) = type_obj.get(&Value::SymId(key).as_tagged(mu)) {
        match Value::from(&val) {
            Value::Func(func) => {
                if func.auto_binds() {
                    bind(Value::Func(func), store_value, mu)
                } else {
                    Ok(Value::Func(func))
                }
            }
            value => Ok(value)
        }
    } else {
        Ok(Value::Null)
    }
}

pub fn mem_store<'gc>(
    store: Value<'gc>,
    key: Value<'gc>,
    src: Value<'gc>,
    mu: &'gc Mutator,
) -> Result<(), RuntimeError> {
    match (store, key) {
        (Value::List(list), Value::Int(idx)) => {
            let out_of_bounds = if idx >= 0  {
                list.len() <= idx as usize
            } else {
                list.len() < idx.unsigned_abs() as usize
            };

            if out_of_bounds {
                return Err(RuntimeError::new(
                        RuntimeErrorKind::OutOfBoundsAccess,
                        Some(format!("Attempted to store to list of len {} at index {}", list.len(), idx)),
                        None
                    ));
            }

            let adjusted_idx = if idx >= 0  {
                idx as usize
            } else {
                list.len() - idx.unsigned_abs() as usize
            };

            list.set(
                adjusted_idx,
                src.as_tagged(mu),
                mu,
            );

            Ok(())
        }
        (Value::Map(map), key) => {
            GcHashMap::insert(map, key.as_tagged(mu), src.as_tagged(mu), mu);

            Ok(())
        }
        (lhs, rhs) => Err(RuntimeError::new(
            RuntimeErrorKind::TypeError,
            Some(format!(
                "Invalid memory access of {} via a {}",
                lhs.type_str(),
                rhs.type_str()
            )),
            None
        ))
    }
}

pub fn push<'gc>(lhs: Value<'gc>, rhs: Value<'gc>, mu: &'gc Mutator) -> Result<(), RuntimeError> {
    match (lhs, rhs) {
        (Value::String(a), Value::String(b)) => {
            for i in 0..b.len() {
                a.push_char(b.at(i).unwrap(), mu);
            }
        }
        (Value::List(list), any) => {
            list.push(any.as_tagged(mu), mu);
        }
        (lhs, rhs) => return Err(RuntimeError::new(
            RuntimeErrorKind::TypeError,
            Some(format!(
                "Attempted to push {} into a {}",
                rhs.type_str(),
                lhs.type_str(),
            )),
            None
        ))
    };

    Ok(())
}

pub fn pop<'gc>(store: Value<'gc>, mu: &'gc Mutator) -> Result<Value<'gc>, RuntimeError> {
    match store {
        Value::String(s) => match s.pop_char() {
            None => Ok(Value::Null),
            Some(c) => {
                let new_string = VMString::alloc_empty(mu);
                new_string.push_char(c, mu);

                Ok(Value::String(Gc::new(mu, new_string)))
            }
        },
        Value::List(list) => Ok(Value::from(&list.pop())),
        _ => Err(RuntimeError::new(
            RuntimeErrorKind::TypeError,
            Some(format!(
                "Attempted to call pop on a {} type",
                store.type_str(),
            )),
            None
        ))
    }
}

pub fn len<'gc>(val: Value<'gc>) -> Result<Value<'gc>, RuntimeError> {
    match val {
        // TODO: remove 'as' casts
        // should be fine for now as no list should ever get close to i64::MAX length
        Value::String(s) => Ok(Value::Int(s.len() as i64)),
        Value::List(list) => Ok(Value::Int(list.len() as i64)),
        Value::Func(f) => { 
            Ok(Value::Int(f.arity() as i64))
        }
        _ => Err(RuntimeError::new(
            RuntimeErrorKind::TypeError,
            Some(format!(
                "Attempted to call len on a {} type",
                val.type_str(),
            )),
            None
        ))
    }
}

pub fn clone<'gc>(
    arg: Value<'gc>,
    mu: &'gc Mutator<'gc>,
) -> Value<'gc> {
    match arg {
        Value::String(old) => {
            let new = Gc::new(mu, VMString::alloc_empty(mu));

            for x in 0..old.len() {
                let c = old.at(usize::try_from(x).unwrap()).unwrap();

                new.push_char(c, mu);
            }

            Value::String(new)
        }
        Value::Map(old_map) => {
            let new_map = GcHashMap::alloc(mu);
            old_map.copy_entries_to(new_map.clone(), mu);
            Value::Map(new_map)
        }
        Value::List(old) => {
            let new_list = Gc::new(mu, List::alloc(mu));

            for x in 0..old.len() {
                let item = old.at(x);

                new_list.push(item.as_tagged(mu), mu);
            }

            Value::List(new_list)
        }
        _ => arg,
    }
}

pub fn ttype<'gc>(arg: &Value<'gc>) -> Value<'gc> {
    Value::SymId(arg.get_type_id())
}

pub fn delete<'gc>(
    store: Value<'gc>,
    key: Value<'gc>,
    mu: &'gc Mutator,
) -> Result<Value<'gc>, RuntimeError> {
    match store {
        Value::Map(map) => {
            if let Some(k) = map.delete(key.as_tagged(mu)) {
                Ok(Value::from(&k))
            } else {
                Ok(Value::Null)
            }
        }
        _ => Err(RuntimeError::new(
            RuntimeErrorKind::TypeError,
            Some(format!(
                "Attempted to call delete on a {} type",
                store.type_str(),
            )),
            None
        ))
    }
}

pub fn bind<'gc>(func: Value<'gc>, arg: Value<'gc>, mu: &'gc Mutator<'gc>) -> Result<Value<'gc>, RuntimeError> {
    match func {
        Value::Func(f) => {
            let partial = f.bind(mu, arg.as_tagged(mu))?;
            Ok(Value::Func(partial))
        }
        _ => Err(RuntimeError::new(
            RuntimeErrorKind::TypeError,
            Some(format!(
                "Attempted to call bind on a {} type",
                func.type_str(),
            )),
            None
        ))
    }
}