feat(tvix/eval): Support builtins.elemAt

(Attempt to) index into a list.

Change-Id: I3592e60a79e64d265e34100d4062041b0b410e00
Reviewed-on: https://cl.tvl.fyi/c/depot/+/6551
Reviewed-by: wpcarro <wpcarro@gmail.com>
Reviewed-by: tazjin <tazjin@tvl.su>
Autosubmit: wpcarro <wpcarro@gmail.com>
Tested-by: BuildkiteCI
This commit is contained in:
William Carroll 2022-09-06 11:58:28 -07:00 committed by clbot
parent 53fbc75df9
commit 3a67a14009
4 changed files with 22 additions and 2 deletions

View file

@ -140,6 +140,20 @@ fn pure_builtins() -> Vec<Builtin> {
let a = args.pop().unwrap();
arithmetic_op!(a, b, /)
}),
Builtin::new("elemAt", 2, |args, vm| {
force!(vm, &args[0], value, {
let xs = value.to_list()?;
let i = args[1].as_int()?;
if i < 0 {
Err(ErrorKind::IndexOutOfBounds { index: i })
} else {
match xs.get(i as usize) {
Some(x) => Ok(x.clone()),
None => Err(ErrorKind::IndexOutOfBounds { index: i }),
}
}
})
}),
Builtin::new("length", 1, |args, vm| {
if let Value::Thunk(t) = &args[0] {
t.force(vm)?;

View file

@ -26,9 +26,9 @@ pub enum ErrorKind {
name: String,
},
// Attempted to index into a list beyond its boundaries.
/// Attempted to index into a list beyond its boundaries.
IndexOutOfBounds {
index: usize,
index: i64,
},
TypeError {

View file

@ -0,0 +1 @@
[ "foo" "bar" "baz" ]

View file

@ -0,0 +1,5 @@
[
(builtins.elemAt [ "foo" "bar" "baz" ] 0)
(builtins.elemAt [ "foo" "bar" "baz" ] 1)
(builtins.elemAt [ "foo" "bar" "baz" ] 2)
]