Skip to main content

rl_lang/interpreter/stdlib/array/
arr_insert.rs

1use crate::{
2    ast::statements::TypeAnnotation,
3    interpreter::{evaluator::Evaluator, values::Value},
4    utils::{errors::Error, span::Span},
5};
6
7pub fn std_arr_insert(
8    eval: &mut Evaluator,
9    array: Value,
10    value: Value,
11    index: i64,
12    span: Span,
13) -> Result<Value, Error> {
14    match array {
15        Value::Values { items_type, items } => {
16            if index as usize >= items.len() {
17                return Err(eval.err(format!("index out of bounds: {}", index), span));
18            }
19
20            let val_type = Evaluator::infer_type(&value, false);
21            if val_type != items_type && val_type != TypeAnnotation::Null {
22                return Err(eval.err(
23                    format!(
24                        "type mismatch: array expects {:?}, cannot push {:?}",
25                        items_type, val_type
26                    ),
27                    span,
28                ));
29            }
30            let mut v = items;
31            v.insert(index as usize, value);
32            Ok(Value::Values {
33                items_type,
34                items: v,
35            })
36        }
37        _ => Err(eval.err(
38            "arr_insert() accepts only arrays and values".to_string(),
39            span,
40        )),
41    }
42}