#[allow(unused_imports)]
use crate::aver_generated::domain::value::*;
#[allow(unused_imports)]
use crate::*;

/// Create slot env: Vector<Val> of slotCount, args at 0..n-1.
#[inline(always)]
pub fn buildSlotEnv(args: &aver_rt::AverList<Val>, slotCount: i64) -> aver_rt::AverVector<Val> {
    crate::cancel_checkpoint();
    crate::aver_generated::domain::eval::slots::buildSlotEnvLoop(
        args.clone(),
        aver_rt::AverVector::new(
            slotCount as usize,
            crate::aver_generated::domain::value::Val::ValUnit,
        ),
        0i64,
    )
}

/// Fill slot env from arg list.
#[inline(always)]
pub fn buildSlotEnvLoop(
    mut args: aver_rt::AverList<Val>,
    mut acc: aver_rt::AverVector<Val>,
    mut idx: i64,
) -> aver_rt::AverVector<Val> {
    loop {
        crate::cancel_checkpoint();
        aver_list_match!(args, [] => { return acc; }, [a, rest] => { {
            let __tco0 = rest;
            let __tco1 = { let __vec = acc.clone(); let __idx = idx as usize; if __idx < __vec.len() { __vec.set_unchecked(__idx, a) } else { __vec } };
            let __tco2 = (idx + 1i64);
            args = __tco0;
            acc = __tco1;
            idx = __tco2;
            continue;
        } })
    }
}

/// Look up a variable by slot index. O(1).
#[inline(always)]
pub fn lookupSlot(env: &aver_rt::AverVector<Val>, slot: i64) -> Result<Val, AverStr> {
    crate::cancel_checkpoint();
    match env.get(slot as usize).cloned() {
        Some(v) => Ok(v),
        None => Err(aver_rt::AverStr::from({
            let mut __b = {
                let mut __b = aver_rt::Buffer::with_capacity((36i64) as usize);
                __b.push_str(&AverStr::from("slot out of bounds: "));
                __b
            };
            __b.push_str(&aver_rt::AverStr::from(aver_rt::aver_display(
                &((slot.to_string()).into_aver()),
            )));
            __b
        })),
    }
}

/// Set slot value. O(1).
#[inline(always)]
pub fn setSlot(env: &aver_rt::AverVector<Val>, slot: i64, v: &Val) -> aver_rt::AverVector<Val> {
    crate::cancel_checkpoint();
    {
        let __vec = env.clone();
        let __idx = slot as usize;
        if __idx < __vec.len() {
            __vec.set_unchecked(__idx, v.clone())
        } else {
            __vec
        }
    }
}
