git.delta.rocks / jrsonnet / refs/commits / 62ffdd8c4879

difftreelog

refactor more array specializations

Yaroslav Bolyukin2022-12-03parent: #aab1050.patch.diff
in: master

16 files changed

modifiedbindings/jsonnet/src/val_make.rsdiffbeforeafterboth
--- a/bindings/jsonnet/src/val_make.rs
+++ b/bindings/jsonnet/src/val_make.rs
@@ -46,7 +46,7 @@
 /// Assign elements with [`jsonnet_json_array_append`].
 #[no_mangle]
 pub extern "C" fn jsonnet_json_make_array(_vm: &VM) -> *mut Val {
-	Box::into_raw(Box::new(Val::Arr(ArrValue::Eager(Cc::new(Vec::new())))))
+	Box::into_raw(Box::new(Val::Arr(ArrValue::eager(Cc::new(Vec::new())))))
 }
 
 /// Make a `JsonnetJsonValue` representing an object.
modifiedbindings/jsonnet/src/val_modify.rsdiffbeforeafterboth
--- a/bindings/jsonnet/src/val_modify.rs
+++ b/bindings/jsonnet/src/val_modify.rs
@@ -25,7 +25,7 @@
 			}
 
 			new.push(Thunk::evaluated(val.clone()));
-			*arr = Val::Arr(ArrValue::Lazy(Cc::new(new)));
+			*arr = Val::Arr(ArrValue::lazy(Cc::new(new)));
 		}
 		_ => panic!("should receive array"),
 	}
modifiedcrates/jrsonnet-cli/src/manifest.rsdiffbeforeafterboth
--- a/crates/jrsonnet-cli/src/manifest.rs
+++ b/crates/jrsonnet-cli/src/manifest.rs
@@ -50,7 +50,7 @@
 	/// Preserve order in object manifestification
 	#[cfg(feature = "exp-preserve-order")]
 	#[clap(long)]
-	preserve_order: bool,
+	pub preserve_order: bool,
 }
 impl ConfigureState for ManifestOpts {
 	type Guards = Box<dyn ManifestFormat>;
addedcrates/jrsonnet-evaluator/src/arr/mod.rsdiffbeforeafterboth
--- /dev/null
+++ b/crates/jrsonnet-evaluator/src/arr/mod.rs
@@ -0,0 +1,222 @@
+use jrsonnet_gcmodule::{Cc, Trace};
+use jrsonnet_interner::IBytes;
+use jrsonnet_parser::LocExpr;
+
+use crate::{function::FuncVal, Context, Result, Thunk, Val};
+
+mod spec;
+use spec::*;
+
+/// Represents a Jsonnet array value.
+#[derive(Debug, Clone, Trace)]
+// may contrain other ArrValue
+#[trace(tracking(force))]
+pub enum ArrValue {
+	/// Layout optimized byte array.
+	Bytes(BytesArray),
+	/// Every element is lazy evaluated.
+	Lazy(LazyArray),
+	/// Every element is defined somewhere in source code
+	Expr(ExprArray),
+	/// Every field is already evaluated.
+	Eager(EagerArray),
+	/// Concatenation of two arrays of any kind.
+	Extended(Cc<ExtendedArray>),
+	/// Represents a integer array in form `[start, start + 1, ... end - 1, end]`.
+	/// This kind of arrays is generated by `std.range(start, end)` call, and used for loops.
+	Range(RangeArray),
+	/// Sliced array view.
+	Slice(Box<SliceArray>),
+	/// Reversed array view.
+	/// Returned by `std.reverse(other)` call
+	Reverse(Box<ReverseArray>),
+	/// Returned by `std.map` call
+	Mapped(MappedArray),
+}
+
+impl ArrValue {
+	pub fn empty() -> Self {
+		Self::Range(RangeArray::empty())
+	}
+
+	pub fn expr(ctx: Context, exprs: impl IntoIterator<Item = LocExpr>) -> Self {
+		Self::Expr(ExprArray::new(ctx, exprs))
+	}
+
+	pub fn lazy(thunks: Cc<Vec<Thunk<Val>>>) -> Self {
+		Self::Lazy(LazyArray(thunks))
+	}
+
+	pub fn eager(values: Cc<Vec<Val>>) -> Self {
+		Self::Eager(EagerArray(values))
+	}
+
+	pub fn bytes(bytes: IBytes) -> Self {
+		Self::Bytes(BytesArray(bytes))
+	}
+
+	#[must_use]
+	pub fn map(self, mapper: FuncVal) -> Self {
+		Self::Mapped(MappedArray::new(self, mapper))
+	}
+
+	pub fn filter(self, filter: impl Fn(&Val) -> Result<bool>) -> Result<Self> {
+		// TODO: ArrValue::Picked(inner, indexes) for large arrays
+		let mut out = Vec::new();
+		for i in self.iter() {
+			let i = i?;
+			if filter(&i)? {
+				out.push(i);
+			};
+		}
+		Ok(Self::eager(Cc::new(out)))
+	}
+
+	pub fn extended(a: ArrValue, b: ArrValue) -> Self {
+		// TODO: benchmark for an optimal value, currently just a arbitrary choice
+		const ARR_EXTEND_THRESHOLD: usize = 100;
+
+		if a.len() + b.len() > ARR_EXTEND_THRESHOLD {
+			Self::Extended(Cc::new(ExtendedArray::new(a, b)))
+		} else if let (Some(a), Some(b)) = (a.iter_cheap(), b.iter_cheap()) {
+			let mut out = Vec::with_capacity(a.len() + b.len());
+			out.extend(a);
+			out.extend(b);
+			Self::eager(Cc::new(out))
+		} else {
+			let mut out = Vec::with_capacity(a.len() + b.len());
+			out.extend(a.iter_lazy());
+			out.extend(b.iter_lazy());
+			Self::lazy(Cc::new(out))
+		}
+	}
+
+	pub fn range_exclusive(a: i32, b: i32) -> Self {
+		Self::Range(RangeArray::new_exclusive(a, b))
+	}
+	pub fn range_inclusive(a: i32, b: i32) -> Self {
+		Self::Range(RangeArray::new_inclusive(a, b))
+	}
+
+	#[must_use]
+	pub fn slice(
+		self,
+		from: Option<usize>,
+		to: Option<usize>,
+		step: Option<usize>,
+	) -> Option<Self> {
+		let len = self.len();
+		let from = from.unwrap_or(0);
+		let to = to.unwrap_or(len).min(len);
+		let step = step.unwrap_or(1);
+		if from >= to || step == 0 {
+			return None;
+		}
+
+		Some(Self::Slice(Box::new(SliceArray {
+			inner: self,
+			from: from as u32,
+			to: to as u32,
+			step: step as u32,
+		})))
+	}
+
+	/// Array length.
+	pub fn len(&self) -> usize {
+		pass!(self.len())
+	}
+
+	/// Is array contains no elements?
+	pub fn is_empty(&self) -> bool {
+		pass!(self.is_empty())
+	}
+
+	/// Get array element by index, evaluating it, if it is lazy.
+	///
+	/// Returns `None` on out-of-bounds condition.
+	pub fn get(&self, index: usize) -> Result<Option<Val>> {
+		pass!(self.get(index))
+	}
+
+	/// Returns None if get is either non cheap, or out of bounds
+	fn get_cheap(&self, index: usize) -> Option<Val> {
+		pass!(self.get_cheap(index))
+	}
+
+	/// Get array element by index, without evaluation.
+	///
+	/// Returns `None` on out-of-bounds condition.
+	pub fn get_lazy(&self, index: usize) -> Option<Thunk<Val>> {
+		pass!(self.get_lazy(index))
+	}
+
+	/// Evaluate all array elements, returning new array.
+	pub fn evaluatedcc(&self) -> Result<Cc<Vec<Val>>> {
+		self.evaluated().map(Cc::new)
+	}
+	pub fn evaluated(&self) -> Result<Vec<Val>> {
+		pass!(self.evaluated())
+	}
+
+	/// Iterate over elements, evaluating them.
+	pub fn iter(&self) -> UnknownArrayIter<'_> {
+		pass_iter_call!(self.iter => UnknownArrayIter)
+	}
+
+	/// Iterate over elements, returning lazy values.
+	pub fn iter_lazy(&self) -> UnknownArrayIterLazy<'_> {
+		pass_iter_call!(self.iter_lazy => UnknownArrayIterLazy)
+	}
+
+	pub fn iter_cheap(&self) -> Option<UnknownArrayIterCheap<'_>> {
+		macro_rules! question {
+			($v:expr) => {
+				$v?
+			};
+		}
+		Some(pass_iter_call!(self.iter_cheap in question => UnknownArrayIterCheap))
+	}
+
+	/// Return a reversed view on current array.
+	#[must_use]
+	pub fn reversed(self) -> Self {
+		Self::Reverse(Box::new(ReverseArray(self)))
+	}
+
+	pub fn ptr_eq(a: &Self, b: &Self) -> bool {
+		match (a, b) {
+			(ArrValue::Bytes(a), ArrValue::Bytes(b)) => a.0 == b.0,
+			(ArrValue::Lazy(a), ArrValue::Lazy(b)) => Cc::ptr_eq(&a.0, &b.0),
+			(ArrValue::Expr(a), ArrValue::Expr(b)) => Cc::ptr_eq(&a.0, &b.0),
+			(ArrValue::Eager(a), ArrValue::Eager(b)) => Cc::ptr_eq(&a.0, &b.0),
+			(ArrValue::Extended(a), ArrValue::Extended(b)) => Cc::ptr_eq(&a, &b),
+			(ArrValue::Range(a), ArrValue::Range(b)) => a == b,
+			(ArrValue::Slice(_), ArrValue::Slice(_)) => false,
+			(ArrValue::Reverse(_), ArrValue::Reverse(_)) => false,
+			_ => false,
+		}
+	}
+
+	pub fn is_cheap(&self) -> bool {
+		match self {
+			ArrValue::Eager(_) | ArrValue::Range(..) | ArrValue::Bytes(_) => true,
+			ArrValue::Extended(v) => v.a.is_cheap() && v.b.is_cheap(),
+			ArrValue::Slice(r) => r.inner.is_cheap(),
+			ArrValue::Reverse(i) => i.0.is_cheap(),
+			ArrValue::Expr(_) | ArrValue::Lazy(_) | ArrValue::Mapped(_) => false,
+		}
+	}
+}
+impl From<Vec<Val>> for ArrValue {
+	fn from(value: Vec<Val>) -> Self {
+		Self::eager(Cc::new(value))
+	}
+}
+impl From<Vec<Thunk<Val>>> for ArrValue {
+	fn from(value: Vec<Thunk<Val>>) -> Self {
+		Self::lazy(Cc::new(value))
+	}
+}
+
+#[cfg(target_pointer_width = "64")]
+static_assertions::assert_eq_size!(ArrValue, [u8; 16]);
addedcrates/jrsonnet-evaluator/src/arr/spec.rsdiffbeforeafterboth
--- /dev/null
+++ b/crates/jrsonnet-evaluator/src/arr/spec.rs
@@ -0,0 +1,841 @@
+use std::{
+	cell::RefCell,
+	iter::{self, Rev},
+	mem::replace,
+};
+
+use jrsonnet_gcmodule::{Cc, Trace};
+use jrsonnet_interner::IBytes;
+use jrsonnet_parser::LocExpr;
+
+use super::ArrValue;
+use crate::{
+	error::ErrorKind::InfiniteRecursionDetected, evaluate, function::FuncVal, tb, typed::Any,
+	val::ThunkValue, Context, Error, Result, Thunk, Val,
+};
+
+pub trait ArrayLike {
+	type Iter<'t>
+	where
+		Self: 't;
+	type IterLazy<'t>
+	where
+		Self: 't;
+	type IterCheap<'t>
+	where
+		Self: 't;
+
+	fn len(&self) -> usize;
+	fn is_empty(&self) -> bool {
+		self.len() == 0
+	}
+	fn get(&self, index: usize) -> Result<Option<Val>>;
+	fn get_lazy(&self, index: usize) -> Option<Thunk<Val>>;
+	fn get_cheap(&self, index: usize) -> Option<Val>;
+	fn evaluated(&self) -> Result<Vec<Val>>;
+	#[allow(clippy::iter_not_returning_iterator)]
+	fn iter(&self) -> Self::Iter<'_>;
+	fn iter_lazy(&self) -> Self::IterLazy<'_>;
+	fn iter_cheap(&self) -> Option<Self::IterCheap<'_>>;
+}
+
+#[derive(Debug, Clone, Trace)]
+pub struct SliceArray {
+	pub(crate) inner: ArrValue,
+	pub(crate) from: u32,
+	pub(crate) to: u32,
+	pub(crate) step: u32,
+}
+type SliceArrayIter<'t> = impl DoubleEndedIterator<Item = Result<Val>> + ExactSizeIterator + 't;
+type SliceArrayLazyIter<'t> = impl DoubleEndedIterator<Item = Thunk<Val>> + ExactSizeIterator + 't;
+type SliceArrayCheapIter<'t> = impl DoubleEndedIterator<Item = Val> + ExactSizeIterator + 't;
+impl ArrayLike for SliceArray {
+	type Iter<'t> = SliceArrayIter<'t>;
+
+	type IterLazy<'t> = SliceArrayLazyIter<'t>;
+
+	type IterCheap<'t> = SliceArrayCheapIter<'t>;
+
+	fn len(&self) -> usize {
+		iter::repeat(())
+			.take((self.to - self.from) as usize)
+			.step_by(self.step as usize)
+			.count()
+	}
+
+	fn get(&self, index: usize) -> Result<Option<Val>> {
+		self.iter().nth(index).transpose()
+	}
+
+	fn get_lazy(&self, index: usize) -> Option<Thunk<Val>> {
+		self.iter_lazy().nth(index)
+	}
+
+	fn get_cheap(&self, index: usize) -> Option<Val> {
+		self.iter_cheap()?.nth(index)
+	}
+
+	fn evaluated(&self) -> Result<Vec<Val>> {
+		self.iter().collect()
+	}
+
+	fn iter(&self) -> SliceArrayIter<'_> {
+		self.inner
+			.iter()
+			.skip(self.from as usize)
+			.take((self.to - self.from) as usize)
+			.step_by(self.step as usize)
+	}
+
+	fn iter_lazy(&self) -> SliceArrayLazyIter<'_> {
+		self.inner
+			.iter_lazy()
+			.skip(self.from as usize)
+			.take((self.to - self.from) as usize)
+			.step_by(self.step as usize)
+	}
+
+	fn iter_cheap(&self) -> Option<SliceArrayCheapIter<'_>> {
+		Some(
+			self.inner
+				.iter_cheap()?
+				.skip(self.from as usize)
+				.take((self.to - self.from) as usize)
+				.step_by(self.step as usize),
+		)
+	}
+}
+
+#[derive(Trace, Debug, Clone)]
+pub struct BytesArray(pub IBytes);
+type BytesArrayIter<'t> = impl DoubleEndedIterator<Item = Result<Val>> + ExactSizeIterator + 't;
+type BytesArrayLazyIter<'t> = impl DoubleEndedIterator<Item = Thunk<Val>> + ExactSizeIterator + 't;
+type BytesArrayCheapIter<'t> = impl DoubleEndedIterator<Item = Val> + ExactSizeIterator + 't;
+impl ArrayLike for BytesArray {
+	type Iter<'t> = BytesArrayIter<'t>;
+
+	type IterLazy<'t> = BytesArrayLazyIter<'t>;
+
+	type IterCheap<'t> = BytesArrayCheapIter<'t>;
+
+	fn len(&self) -> usize {
+		self.0.len()
+	}
+
+	fn get(&self, index: usize) -> Result<Option<Val>> {
+		Ok(self.get_cheap(index))
+	}
+
+	fn get_lazy(&self, index: usize) -> Option<Thunk<Val>> {
+		self.get_cheap(index).map(Thunk::evaluated)
+	}
+
+	fn get_cheap(&self, index: usize) -> Option<Val> {
+		self.0.get(index).map(|v| Val::Num(f64::from(*v)))
+	}
+
+	fn evaluated(&self) -> Result<Vec<Val>> {
+		self.iter().collect()
+	}
+
+	fn iter(&self) -> BytesArrayIter<'_> {
+		self.0.iter().map(|v| Ok(Val::Num(f64::from(*v))))
+	}
+
+	fn iter_lazy(&self) -> BytesArrayLazyIter<'_> {
+		self.0
+			.iter()
+			.map(|v| Thunk::evaluated(Val::Num(f64::from(*v))))
+	}
+
+	fn iter_cheap(&self) -> Option<BytesArrayCheapIter<'_>> {
+		Some(self.0.iter().map(|v| Val::Num(f64::from(*v))))
+	}
+}
+
+#[derive(Debug, Trace, Clone)]
+enum ArrayThunk<T: 'static + Trace> {
+	Computed(Val),
+	Errored(Error),
+	Waiting(T),
+	Pending,
+}
+
+#[derive(Debug, Trace)]
+pub struct ExprArrayInner {
+	ctx: Context,
+	cached: RefCell<Vec<ArrayThunk<LocExpr>>>,
+}
+#[derive(Debug, Trace, Clone)]
+pub struct ExprArray(pub Cc<ExprArrayInner>);
+type ExprArrayIter<'t> = impl DoubleEndedIterator<Item = Result<Val>> + ExactSizeIterator + 't;
+type ExprArrayLazyIter<'t> = impl DoubleEndedIterator<Item = Thunk<Val>> + ExactSizeIterator + 't;
+type ExprArrayCheapIter<'t> = iter::Empty<Val>;
+impl ExprArray {
+	pub fn new(ctx: Context, items: impl IntoIterator<Item = LocExpr>) -> Self {
+		Self(Cc::new(ExprArrayInner {
+			ctx,
+			cached: RefCell::new(items.into_iter().map(ArrayThunk::Waiting).collect()),
+		}))
+	}
+}
+impl ArrayLike for ExprArray {
+	type Iter<'t> = ExprArrayIter<'t>;
+
+	type IterLazy<'t> = ExprArrayLazyIter<'t>;
+
+	type IterCheap<'t> = ExprArrayCheapIter<'t>;
+
+	fn len(&self) -> usize {
+		self.0.cached.borrow().len()
+	}
+	fn get(&self, index: usize) -> Result<Option<Val>> {
+		if index >= self.len() {
+			return Ok(None);
+		}
+		match &self.0.cached.borrow()[index] {
+			ArrayThunk::Computed(c) => return Ok(Some(c.clone())),
+			ArrayThunk::Errored(e) => return Err(e.clone()),
+			ArrayThunk::Pending => return Err(InfiniteRecursionDetected.into()),
+			ArrayThunk::Waiting(..) => {}
+		};
+
+		let ArrayThunk::Waiting(expr) = replace(&mut self.0.cached.borrow_mut()[index], ArrayThunk::Pending) else {
+			unreachable!()
+		};
+
+		let new_value = match evaluate(self.0.ctx.clone(), &expr) {
+			Ok(v) => v,
+			Err(e) => {
+				self.0.cached.borrow_mut()[index] = ArrayThunk::Errored(e.clone());
+				return Err(e);
+			}
+		};
+		self.0.cached.borrow_mut()[index] = ArrayThunk::Computed(new_value.clone());
+		Ok(Some(new_value))
+	}
+	fn get_lazy(&self, index: usize) -> Option<Thunk<Val>> {
+		#[derive(Trace)]
+		struct ArrayElement {
+			arr_thunk: ExprArray,
+			index: usize,
+		}
+
+		impl ThunkValue for ArrayElement {
+			type Output = Val;
+
+			fn get(self: Box<Self>) -> Result<Self::Output> {
+				self.arr_thunk
+					.get(self.index)
+					.transpose()
+					.expect("index checked")
+			}
+		}
+
+		if index >= self.len() {
+			return None;
+		}
+		match &self.0.cached.borrow()[index] {
+			ArrayThunk::Computed(c) => return Some(Thunk::evaluated(c.clone())),
+			ArrayThunk::Errored(e) => return Some(Thunk::errored(e.clone())),
+			ArrayThunk::Waiting(_) | ArrayThunk::Pending => {}
+		};
+
+		Some(Thunk::new(tb!(ArrayElement {
+			arr_thunk: self.clone(),
+			index,
+		})))
+	}
+	fn get_cheap(&self, _index: usize) -> Option<Val> {
+		None
+	}
+
+	fn iter(&self) -> ExprArrayIter<'_> {
+		(0..self.len()).map(|i| self.get(i).transpose().expect("index checked"))
+	}
+	fn iter_lazy(&self) -> ExprArrayLazyIter<'_> {
+		(0..self.len()).map(|i| self.get_lazy(i).expect("index checked"))
+	}
+	fn iter_cheap(&self) -> Option<ExprArrayCheapIter<'_>> {
+		None
+	}
+
+	fn evaluated(&self) -> Result<Vec<Val>> {
+		self.iter().collect()
+	}
+}
+
+#[derive(Trace, Debug, Clone)]
+pub struct ExtendedArray {
+	pub a: ArrValue,
+	pub b: ArrValue,
+	split: usize,
+	len: usize,
+}
+type ExtendedArrayIter<'t> = impl DoubleEndedIterator<Item = Result<Val>> + 't;
+type ExtendedArrayLazyIter<'t> = impl DoubleEndedIterator<Item = Thunk<Val>> + 't;
+type ExtendedArrayCheapIter<'t> = impl DoubleEndedIterator<Item = Val> + 't;
+impl ExtendedArray {
+	pub fn new(a: ArrValue, b: ArrValue) -> Self {
+		let a_len = a.len();
+		let b_len = b.len();
+		Self {
+			a,
+			b,
+			split: a_len,
+			len: a_len.checked_add(b_len).expect("too large array value"),
+		}
+	}
+}
+impl ArrayLike for ExtendedArray {
+	type Iter<'t> = ExtendedArrayIter<'t>;
+
+	type IterLazy<'t> = ExtendedArrayLazyIter<'t>;
+
+	type IterCheap<'t> = ExtendedArrayCheapIter<'t>;
+
+	fn get(&self, index: usize) -> Result<Option<Val>> {
+		if self.split > index {
+			self.a.get(index)
+		} else {
+			self.b.get(index - self.split)
+		}
+	}
+	fn get_lazy(&self, index: usize) -> Option<Thunk<Val>> {
+		if self.split > index {
+			self.a.get_lazy(index)
+		} else {
+			self.b.get_lazy(index - self.split)
+		}
+	}
+
+	fn len(&self) -> usize {
+		self.len
+	}
+
+	fn get_cheap(&self, index: usize) -> Option<Val> {
+		if self.split > index {
+			self.a.get_cheap(index)
+		} else {
+			self.b.get_cheap(index - self.split)
+		}
+	}
+
+	fn evaluated(&self) -> Result<Vec<Val>> {
+		let mut out = self.a.evaluated()?;
+		out.extend(self.b.evaluated()?.into_iter());
+		Ok(out)
+	}
+
+	fn iter(&self) -> ExtendedArrayIter<'_> {
+		self.a.iter().chain(self.b.iter())
+	}
+	fn iter_lazy(&self) -> ExtendedArrayLazyIter<'_> {
+		self.a.iter_lazy().chain(self.b.iter_lazy())
+	}
+	fn iter_cheap(&self) -> Option<ExtendedArrayCheapIter<'_>> {
+		let a = self.a.iter_cheap()?;
+		let b = self.b.iter_cheap()?;
+		Some(a.chain(b))
+	}
+}
+
+#[derive(Trace, Debug, Clone)]
+pub struct LazyArray(pub Cc<Vec<Thunk<Val>>>);
+type LazyArrayIter<'t> = impl DoubleEndedIterator<Item = Result<Val>> + ExactSizeIterator + 't;
+type LazyArrayLazyIter<'t> = impl DoubleEndedIterator<Item = Thunk<Val>> + ExactSizeIterator + 't;
+type LazyArrayCheapIter<'t> = iter::Empty<Val>;
+impl ArrayLike for LazyArray {
+	type Iter<'t> = LazyArrayIter<'t>;
+
+	type IterLazy<'t> = LazyArrayLazyIter<'t>;
+
+	type IterCheap<'t> = LazyArrayCheapIter<'t>;
+
+	fn len(&self) -> usize {
+		self.0.len()
+	}
+	fn get(&self, index: usize) -> Result<Option<Val>> {
+		let Some(v) = self.0.get(index) else {
+			return Ok(None);
+		};
+		v.evaluate().map(Some)
+	}
+	fn get_cheap(&self, _index: usize) -> Option<Val> {
+		None
+	}
+	fn get_lazy(&self, index: usize) -> Option<Thunk<Val>> {
+		self.0.get(index).cloned()
+	}
+	fn evaluated(&self) -> Result<Vec<Val>> {
+		let mut out = Vec::with_capacity(self.len());
+		for i in self.0.iter() {
+			out.push(i.evaluate()?);
+		}
+		Ok(out)
+	}
+	fn iter(&self) -> LazyArrayIter<'_> {
+		self.0.iter().map(Thunk::evaluate)
+	}
+	fn iter_lazy(&self) -> LazyArrayLazyIter<'_> {
+		self.0.iter().cloned()
+	}
+	fn iter_cheap(&self) -> Option<LazyArrayCheapIter<'_>> {
+		None
+	}
+}
+
+#[derive(Trace, Debug, Clone)]
+pub struct EagerArray(pub Cc<Vec<Val>>);
+type EagerArrayIter<'t> = impl DoubleEndedIterator<Item = Result<Val>> + ExactSizeIterator + 't;
+type EagerArrayLazyIter<'t> = impl DoubleEndedIterator<Item = Thunk<Val>> + ExactSizeIterator + 't;
+type EagerArrayCheapIter<'t> = impl DoubleEndedIterator<Item = Val> + ExactSizeIterator + 't;
+impl ArrayLike for EagerArray {
+	type Iter<'t> = EagerArrayIter<'t>;
+
+	type IterLazy<'t> = EagerArrayLazyIter<'t>;
+
+	type IterCheap<'t> = EagerArrayCheapIter<'t>;
+
+	fn len(&self) -> usize {
+		self.0.len()
+	}
+
+	fn get(&self, index: usize) -> Result<Option<Val>> {
+		Ok(self.0.get(index).cloned())
+	}
+
+	fn get_lazy(&self, index: usize) -> Option<Thunk<Val>> {
+		self.0.get(index).cloned().map(Thunk::evaluated)
+	}
+
+	fn get_cheap(&self, index: usize) -> Option<Val> {
+		self.0.get(index).cloned()
+	}
+
+	fn evaluated(&self) -> Result<Vec<Val>> {
+		Ok((*self.0).clone())
+	}
+
+	fn iter(&self) -> EagerArrayIter<'_> {
+		self.0.iter().cloned().map(Ok)
+	}
+
+	fn iter_lazy(&self) -> EagerArrayLazyIter<'_> {
+		self.0.iter().cloned().map(Thunk::evaluated)
+	}
+
+	fn iter_cheap(&self) -> Option<EagerArrayCheapIter<'_>> {
+		Some(self.0.iter().cloned())
+	}
+}
+
+/// Inclusive range type
+#[derive(Debug, Trace, Clone, PartialEq, Eq)]
+pub struct RangeArray {
+	start: i32,
+	end: i32,
+}
+struct RangeIter {
+	start: i32,
+	end: i32,
+}
+impl RangeIter {
+	fn finished(&self) -> bool {
+		self.end < self.start
+	}
+	fn finish(&mut self) {
+		self.start = 0;
+		self.end = -1;
+	}
+}
+impl Iterator for RangeIter {
+	type Item = i32;
+
+	fn next(&mut self) -> Option<Self::Item> {
+		if self.finished() {
+			return None;
+		}
+		let v = self.start;
+		if v == self.end {
+			self.finish();
+		} else {
+			self.start = v + 1;
+		}
+		Some(v)
+	}
+	fn nth(&mut self, n: usize) -> Option<Self::Item> {
+		let v = (self.start as usize) + n;
+		if v > self.end as usize {
+			self.finish();
+			None
+		} else {
+			self.start = v as i32;
+			self.next()
+		}
+	}
+	fn size_hint(&self) -> (usize, Option<usize>) {
+		let len = self.len();
+		(len, Some(len))
+	}
+}
+impl DoubleEndedIterator for RangeIter {
+	fn next_back(&mut self) -> Option<Self::Item> {
+		if self.finished() {
+			return None;
+		}
+		let v = self.end;
+		if v == self.start {
+			self.finish();
+		} else {
+			self.end = v - 1;
+		}
+		Some(v)
+	}
+	fn nth_back(&mut self, n: usize) -> Option<Self::Item> {
+		let v = (self.end as usize) - n;
+		if v < self.start as usize {
+			self.finish();
+			None
+		} else {
+			self.end = v as i32;
+			self.next_back()
+		}
+	}
+}
+impl ExactSizeIterator for RangeIter {
+	fn len(&self) -> usize {
+		if self.finished() {
+			0
+		} else {
+			(self.end as isize - self.start as isize + 1) as usize
+		}
+	}
+}
+impl RangeArray {
+	pub fn empty() -> Self {
+		Self::new_exclusive(0, 0)
+	}
+	pub fn new_exclusive(start: i32, end: i32) -> Self {
+		end.checked_sub(1)
+			.map_or_else(Self::empty, |end| Self { start, end })
+	}
+	pub fn new_inclusive(start: i32, end: i32) -> Self {
+		Self { start, end }
+	}
+	fn range(&self) -> RangeIter {
+		RangeIter {
+			start: self.start,
+			end: self.end,
+		}
+	}
+}
+
+type RangeArrayIter<'t> = impl DoubleEndedIterator<Item = Result<Val>> + ExactSizeIterator + 't;
+type RangeArrayLazyIter<'t> = impl DoubleEndedIterator<Item = Thunk<Val>> + ExactSizeIterator + 't;
+type RangeArrayCheapIter<'t> = impl DoubleEndedIterator<Item = Val> + ExactSizeIterator + 't;
+impl ArrayLike for RangeArray {
+	type Iter<'t> = RangeArrayIter<'t>;
+
+	type IterLazy<'t> = RangeArrayLazyIter<'t>;
+
+	type IterCheap<'t> = RangeArrayCheapIter<'t>;
+
+	fn len(&self) -> usize {
+		self.range().len()
+	}
+	fn is_empty(&self) -> bool {
+		self.range().finished()
+	}
+
+	fn get(&self, index: usize) -> Result<Option<Val>> {
+		Ok(self.get_cheap(index))
+	}
+
+	fn get_lazy(&self, index: usize) -> Option<Thunk<Val>> {
+		self.get_cheap(index).map(Thunk::evaluated)
+	}
+
+	fn get_cheap(&self, index: usize) -> Option<Val> {
+		self.range().nth(index).map(|i| Val::Num(f64::from(i)))
+	}
+
+	fn evaluated(&self) -> Result<Vec<Val>> {
+		Ok(self.range().map(|i| Val::Num(f64::from(i))).collect())
+	}
+
+	fn iter(&self) -> RangeArrayIter<'_> {
+		self.range().map(|i| Ok(Val::Num(f64::from(i))))
+	}
+
+	fn iter_lazy(&self) -> RangeArrayLazyIter<'_> {
+		self.range()
+			.map(|i| Thunk::evaluated(Val::Num(f64::from(i))))
+	}
+
+	fn iter_cheap(&self) -> Option<RangeArrayCheapIter<'_>> {
+		Some(self.range().map(|i| Val::Num(f64::from(i))))
+	}
+}
+
+#[derive(Debug, Trace, Clone)]
+pub struct ReverseArray(pub ArrValue);
+impl ArrayLike for ReverseArray {
+	type Iter<'t> = Rev<UnknownArrayIter<'t>>;
+
+	type IterLazy<'t> = Rev<UnknownArrayIterLazy<'t>>;
+
+	type IterCheap<'t> = Rev<UnknownArrayIterCheap<'t>>;
+
+	fn len(&self) -> usize {
+		self.0.len()
+	}
+
+	fn get(&self, index: usize) -> Result<Option<Val>> {
+		self.0.get(self.0.len() - index - 1)
+	}
+
+	fn get_lazy(&self, index: usize) -> Option<Thunk<Val>> {
+		self.0.get_lazy(self.0.len() - index - 1)
+	}
+
+	fn get_cheap(&self, index: usize) -> Option<Val> {
+		self.0.get_cheap(self.0.len() - index - 1)
+	}
+
+	fn evaluated(&self) -> Result<Vec<Val>> {
+		let mut v = self.0.evaluated()?;
+		v.reverse();
+		Ok(v)
+	}
+
+	fn iter(&self) -> Rev<UnknownArrayIter<'_>> {
+		self.0.iter().rev()
+	}
+
+	fn iter_lazy(&self) -> Rev<UnknownArrayIterLazy<'_>> {
+		self.0.iter_lazy().rev()
+	}
+
+	fn iter_cheap(&self) -> Option<Rev<UnknownArrayIterCheap<'_>>> {
+		Some(self.0.iter_cheap()?.rev())
+	}
+}
+
+#[derive(Trace, Debug)]
+pub struct MappedArrayInner {
+	inner: ArrValue,
+	cached: RefCell<Vec<ArrayThunk<()>>>,
+	mapper: FuncVal,
+}
+#[derive(Trace, Debug, Clone)]
+pub struct MappedArray(Cc<MappedArrayInner>);
+impl MappedArray {
+	pub fn new(inner: ArrValue, mapper: FuncVal) -> Self {
+		let len = inner.len();
+		Self(Cc::new(MappedArrayInner {
+			inner,
+			cached: RefCell::new(vec![ArrayThunk::Waiting(()); len]),
+			mapper,
+		}))
+	}
+}
+type MappedArrayIter<'t> = impl DoubleEndedIterator<Item = Result<Val>> + ExactSizeIterator + 't;
+type MappedArrayLazyIter<'t> = impl DoubleEndedIterator<Item = Thunk<Val>> + ExactSizeIterator + 't;
+type MappedArrayCheapIter<'t> = iter::Empty<Val>;
+impl ArrayLike for MappedArray {
+	type Iter<'t> = MappedArrayIter<'t>;
+	type IterLazy<'t> = MappedArrayLazyIter<'t>;
+	type IterCheap<'t> = MappedArrayCheapIter<'t>;
+
+	fn len(&self) -> usize {
+		self.0.cached.borrow().len()
+	}
+
+	fn get(&self, index: usize) -> Result<Option<Val>> {
+		if index >= self.len() {
+			return Ok(None);
+		}
+		match &self.0.cached.borrow()[index] {
+			ArrayThunk::Computed(c) => return Ok(Some(c.clone())),
+			ArrayThunk::Errored(e) => return Err(e.clone()),
+			ArrayThunk::Pending => return Err(InfiniteRecursionDetected.into()),
+			ArrayThunk::Waiting(..) => {}
+		};
+
+		let ArrayThunk::Waiting(_) = replace(&mut self.0.cached.borrow_mut()[index], ArrayThunk::Pending) else {
+			unreachable!()
+		};
+
+		let val = self
+			.0
+			.inner
+			.get(index)
+			.transpose()
+			.expect("index checked")
+			.and_then(|r| self.0.mapper.evaluate_simple(&(Any(r),)));
+
+		let new_value = match val {
+			Ok(v) => v,
+			Err(e) => {
+				self.0.cached.borrow_mut()[index] = ArrayThunk::Errored(e.clone());
+				return Err(e);
+			}
+		};
+		self.0.cached.borrow_mut()[index] = ArrayThunk::Computed(new_value.clone());
+		Ok(Some(new_value))
+	}
+	fn get_lazy(&self, index: usize) -> Option<Thunk<Val>> {
+		#[derive(Trace)]
+		struct ArrayElement {
+			arr_thunk: MappedArray,
+			index: usize,
+		}
+
+		impl ThunkValue for ArrayElement {
+			type Output = Val;
+
+			fn get(self: Box<Self>) -> Result<Self::Output> {
+				self.arr_thunk
+					.get(self.index)
+					.transpose()
+					.expect("index checked")
+			}
+		}
+
+		if index >= self.len() {
+			return None;
+		}
+		match &self.0.cached.borrow()[index] {
+			ArrayThunk::Computed(c) => return Some(Thunk::evaluated(c.clone())),
+			ArrayThunk::Errored(e) => return Some(Thunk::errored(e.clone())),
+			ArrayThunk::Waiting(_) | ArrayThunk::Pending => {}
+		};
+
+		Some(Thunk::new(tb!(ArrayElement {
+			arr_thunk: self.clone(),
+			index,
+		})))
+	}
+
+	fn get_cheap(&self, _index: usize) -> Option<Val> {
+		None
+	}
+
+	fn evaluated(&self) -> Result<Vec<Val>> {
+		self.iter().collect()
+	}
+
+	fn iter(&self) -> MappedArrayIter<'_> {
+		(0..self.len()).map(|i| self.get(i).transpose().expect("length checked"))
+	}
+
+	fn iter_lazy(&self) -> MappedArrayLazyIter<'_> {
+		(0..self.len()).map(|i| self.get_lazy(i).expect("length checked"))
+	}
+
+	fn iter_cheap(&self) -> Option<Self::IterCheap<'_>> {
+		None
+	}
+}
+// impl MappedArray
+
+macro_rules! impl_iter_enum {
+	($n:ident => $v:ident) => {
+		pub enum $n<'t> {
+			Bytes(<BytesArray as ArrayLike>::$v<'t>),
+			Expr(<ExprArray as ArrayLike>::$v<'t>),
+			Lazy(<LazyArray as ArrayLike>::$v<'t>),
+			Eager(<EagerArray as ArrayLike>::$v<'t>),
+			Range(<RangeArray as ArrayLike>::$v<'t>),
+			Slice(Box<<SliceArray as ArrayLike>::$v<'t>>),
+			Extended(Box<<ExtendedArray as ArrayLike>::$v<'t>>),
+			Reverse(Box<<ReverseArray as ArrayLike>::$v<'t>>),
+			Mapped(Box<<MappedArray as ArrayLike>::$v<'t>>),
+		}
+	};
+}
+
+macro_rules! pass {
+	($t:ident.$m:ident($($ident:ident),*)) => {
+		match $t {
+			Self::Bytes(e) => e.$m($($ident)*),
+			Self::Expr(e) => e.$m($($ident)*),
+			Self::Lazy(e) => e.$m($($ident)*),
+			Self::Eager(e) => e.$m($($ident)*),
+			Self::Range(e) => e.$m($($ident)*),
+			Self::Slice(e) => e.$m($($ident)*),
+			Self::Extended(e) => e.$m($($ident)*),
+			Self::Reverse(e) => e.$m($($ident)*),
+			Self::Mapped(e) => e.$m($($ident)*),
+		}
+	};
+}
+pub(super) use pass;
+
+macro_rules! pass_iter_call {
+	($t:ident.$c:ident $(in $wrap:ident)? => $e:ident) => {
+		match $t {
+			ArrValue::Bytes(e) => $e::Bytes($($wrap!)?(e.$c())),
+			ArrValue::Lazy(e) => $e::Lazy($($wrap!)?(e.$c())),
+			ArrValue::Expr(e) => $e::Expr($($wrap!)?(e.$c())),
+			ArrValue::Eager(e) => $e::Eager($($wrap!)?(e.$c())),
+			ArrValue::Range(e) => $e::Range($($wrap!)?(e.$c())),
+			ArrValue::Slice(e) => $e::Slice(Box::new($($wrap!)?(e.$c()))),
+			ArrValue::Extended(e) => $e::Extended(Box::new($($wrap!)?(e.$c()))),
+			ArrValue::Reverse(e) => $e::Reverse(Box::new($($wrap!)?(e.$c()))),
+			ArrValue::Mapped(e) => $e::Mapped(Box::new($($wrap!)?(e.$c()))),
+		}
+	};
+}
+pub(super) use pass_iter_call;
+
+macro_rules! impl_iter {
+	($t:ident => $out:ty) => {
+		impl Iterator for $t<'_> {
+			type Item = $out;
+
+			fn next(&mut self) -> Option<Self::Item> {
+				pass!(self.next())
+			}
+			fn nth(&mut self, count: usize) -> Option<Self::Item> {
+				pass!(self.nth(count))
+			}
+			fn size_hint(&self) -> (usize, Option<usize>) {
+				pass!(self.size_hint())
+			}
+		}
+		impl DoubleEndedIterator for $t<'_> {
+			fn next_back(&mut self) -> Option<Self::Item> {
+				pass!(self.next_back())
+			}
+			fn nth_back(&mut self, count: usize) -> Option<Self::Item> {
+				pass!(self.nth_back(count))
+			}
+		}
+		impl ExactSizeIterator for $t<'_> {
+			fn len(&self) -> usize {
+				match self {
+					Self::Bytes(e) => e.len(),
+					Self::Expr(e) => e.len(),
+					Self::Lazy(e) => e.len(),
+					Self::Eager(e) => e.len(),
+					Self::Range(e) => e.len(),
+					Self::Slice(e) => e.len(),
+					Self::Extended(e) => {
+						e.size_hint().1.expect("overflow is checked in constructor")
+					}
+					Self::Reverse(e) => e.len(),
+					Self::Mapped(e) => e.len(),
+				}
+			}
+		}
+	};
+}
+
+impl_iter_enum!(UnknownArrayIter => Iter);
+impl_iter_enum!(UnknownArrayIterLazy => IterLazy);
+impl_iter_enum!(UnknownArrayIterCheap => IterCheap);
+impl_iter!(UnknownArrayIter => Result<Val>);
+impl_iter!(UnknownArrayIterLazy => Thunk<Val>);
+impl_iter!(UnknownArrayIterCheap => Val);
modifiedcrates/jrsonnet-evaluator/src/evaluate/destructure.rsdiffbeforeafterboth
--- a/crates/jrsonnet-evaluator/src/evaluate/destructure.rs
+++ b/crates/jrsonnet-evaluator/src/evaluate/destructure.rs
@@ -32,7 +32,7 @@
 		Destruct::Array { start, rest, end } => {
 			use jrsonnet_parser::DestructRest;
 
-			use crate::val::ArrValue;
+			use crate::arr::ArrValue;
 
 			#[derive(Trace)]
 			struct DataThunk {
@@ -110,7 +110,10 @@
 						fn get(self: Box<Self>) -> Result<Self::Output> {
 							let full = self.full.evaluate()?;
 							let to = full.len() - self.end;
-							Ok(Val::Arr(full.slice(Some(self.start), Some(to), None)))
+							Ok(Val::Arr(
+								full.slice(Some(self.start), Some(to), None)
+									.expect("arguments checked"),
+							))
 						}
 					}
 
modifiedcrates/jrsonnet-evaluator/src/evaluate/mod.rsdiffbeforeafterboth
before · crates/jrsonnet-evaluator/src/evaluate/mod.rs
1use std::{cmp::Ordering, rc::Rc};23use jrsonnet_gcmodule::{Cc, Trace};4use jrsonnet_interner::IStr;5use jrsonnet_parser::{6	ArgsDesc, AssertStmt, BindSpec, CompSpec, Expr, FieldMember, FieldName, ForSpecData,7	IfSpecData, LiteralType, LocExpr, Member, ObjBody, ParamsDesc,8};9use jrsonnet_types::ValType;1011use self::destructure::destruct;12use crate::{13	destructure::evaluate_dest,14	error::ErrorKind::*,15	evaluate::operator::{evaluate_add_op, evaluate_binary_op_special, evaluate_unary_op},16	function::{CallLocation, FuncDesc, FuncVal},17	tb, throw,18	typed::Typed,19	val::{ArrValue, CachedUnbound, IndexableVal, Thunk, ThunkValue},20	Context, GcHashMap, ObjValue, ObjValueBuilder, ObjectAssertion, Pending, Result, State,21	Unbound, Val,22};23pub mod destructure;24pub mod operator;2526pub fn evaluate_method(ctx: Context, name: IStr, params: ParamsDesc, body: LocExpr) -> Val {27	Val::Func(FuncVal::Normal(Cc::new(FuncDesc {28		name,29		ctx,30		params,31		body,32	})))33}3435pub fn evaluate_field_name(ctx: Context, field_name: &FieldName) -> Result<Option<IStr>> {36	Ok(match field_name {37		FieldName::Fixed(n) => Some(n.clone()),38		FieldName::Dyn(expr) => State::push(39			CallLocation::new(&expr.1),40			|| "evaluating field name".to_string(),41			|| {42				let value = evaluate(ctx, expr)?;43				if matches!(value, Val::Null) {44					Ok(None)45				} else {46					Ok(Some(IStr::from_untyped(value)?))47				}48			},49		)?,50	})51}5253pub fn evaluate_comp(54	ctx: Context,55	specs: &[CompSpec],56	callback: &mut impl FnMut(Context) -> Result<()>,57) -> Result<()> {58	match specs.get(0) {59		None => callback(ctx)?,60		Some(CompSpec::IfSpec(IfSpecData(cond))) => {61			if bool::from_untyped(evaluate(ctx.clone(), cond)?)? {62				evaluate_comp(ctx, &specs[1..], callback)?;63			}64		}65		Some(CompSpec::ForSpec(ForSpecData(var, expr))) => match evaluate(ctx.clone(), expr)? {66			Val::Arr(list) => {67				for item in list.iter_lazy() {68					let fctx = Pending::new();69					let mut new_bindings = GcHashMap::with_capacity(var.capacity_hint());70					destruct(var, item, fctx.clone(), &mut new_bindings)?;71					let ctx = ctx72						.clone()73						.extend(new_bindings, None, None, None)74						.into_future(fctx);7576					evaluate_comp(ctx, &specs[1..], callback)?;77				}78			}79			#[cfg(feature = "exp-object-iteration")]80			Val::Obj(obj) => {81				for field in obj.fields(82					// TODO: Should there be ability to preserve iteration order?83					#[cfg(feature = "exp-preserve-order")]84					false,85				) {86					#[derive(Trace)]87					struct ObjectFieldThunk {88						obj: ObjValue,89						field: IStr,90					}91					impl ThunkValue for ObjectFieldThunk {92						type Output = Val;9394						fn get(self: Box<Self>) -> Result<Self::Output> {95							self.obj.get(self.field).transpose().expect(96								"field exists, as field name was obtained from object.fields()",97							)98						}99					}100101					let fctx = Pending::new();102					let mut new_bindings = GcHashMap::with_capacity(var.capacity_hint());103					let value = Thunk::evaluated(Val::Arr(ArrValue::Lazy(Cc::new(vec![104						Thunk::evaluated(Val::Str(field.clone())),105						Thunk::new(tb!(ObjectFieldThunk {106							field: field.clone(),107							obj: obj.clone(),108						})),109					]))));110					destruct(var, value, fctx.clone(), &mut new_bindings)?;111					let ctx = ctx112						.clone()113						.extend(new_bindings, None, None, None)114						.into_future(fctx);115116					evaluate_comp(ctx, &specs[1..], callback)?;117				}118			}119			_ => throw!(InComprehensionCanOnlyIterateOverArray),120		},121	}122	Ok(())123}124125trait CloneableUnbound<T>: Unbound<Bound = T> + Clone {}126impl<V, T> CloneableUnbound<T> for V where V: Unbound<Bound = T> + Clone {}127128fn evaluate_object_locals(129	fctx: Pending<Context>,130	locals: Rc<Vec<BindSpec>>,131) -> impl CloneableUnbound<Context> {132	#[derive(Trace, Clone)]133	struct UnboundLocals {134		fctx: Pending<Context>,135		locals: Rc<Vec<BindSpec>>,136	}137	impl Unbound for UnboundLocals {138		type Bound = Context;139140		fn bind(&self, sup: Option<ObjValue>, this: Option<ObjValue>) -> Result<Context> {141			let fctx = Context::new_future();142			let mut new_bindings =143				GcHashMap::with_capacity(self.locals.iter().map(BindSpec::capacity_hint).sum());144			for b in self.locals.iter() {145				evaluate_dest(b, fctx.clone(), &mut new_bindings)?;146			}147148			let ctx = self.fctx.unwrap();149			let new_dollar = ctx.dollar().clone().or_else(|| this.clone());150151			let ctx = ctx152				.extend(new_bindings, new_dollar, sup, this)153				.into_future(fctx);154155			Ok(ctx)156		}157	}158159	UnboundLocals { fctx, locals }160}161162pub fn evaluate_field_member<B: Unbound<Bound = Context> + Clone>(163	builder: &mut ObjValueBuilder,164	ctx: Context,165	uctx: B,166	field: &FieldMember,167) -> Result<()> {168	let name = evaluate_field_name(ctx, &field.name)?;169	let Some(name) = name else {170		return Ok(());171	};172173	match field {174		FieldMember {175			plus,176			params: None,177			visibility,178			value,179			..180		} => {181			#[derive(Trace)]182			struct UnboundValue<B: Trace> {183				uctx: B,184				value: LocExpr,185				name: IStr,186			}187			impl<B: Unbound<Bound = Context>> Unbound for UnboundValue<B> {188				type Bound = Val;189				fn bind(&self, sup: Option<ObjValue>, this: Option<ObjValue>) -> Result<Val> {190					evaluate_named(self.uctx.bind(sup, this)?, &self.value, self.name.clone())191				}192			}193194			builder195				.member(name.clone())196				.with_add(*plus)197				.with_visibility(*visibility)198				.with_location(value.1.clone())199				.bindable(tb!(UnboundValue {200					uctx,201					value: value.clone(),202					name,203				}))?;204		}205		FieldMember {206			params: Some(params),207			visibility,208			value,209			..210		} => {211			#[derive(Trace)]212			struct UnboundMethod<B: Trace> {213				uctx: B,214				value: LocExpr,215				params: ParamsDesc,216				name: IStr,217			}218			impl<B: Unbound<Bound = Context>> Unbound for UnboundMethod<B> {219				type Bound = Val;220				fn bind(&self, sup: Option<ObjValue>, this: Option<ObjValue>) -> Result<Val> {221					Ok(evaluate_method(222						self.uctx.bind(sup, this)?,223						self.name.clone(),224						self.params.clone(),225						self.value.clone(),226					))227				}228			}229230			builder231				.member(name.clone())232				.with_visibility(*visibility)233				.with_location(value.1.clone())234				.bindable(tb!(UnboundMethod {235					uctx,236					value: value.clone(),237					params: params.clone(),238					name,239				}))?;240		}241	}242	Ok(())243}244245#[allow(clippy::too_many_lines)]246pub fn evaluate_member_list_object(ctx: Context, members: &[Member]) -> Result<ObjValue> {247	let mut builder = ObjValueBuilder::new();248	let locals = Rc::new(249		members250			.iter()251			.filter_map(|m| match m {252				Member::BindStmt(bind) => Some(bind.clone()),253				_ => None,254			})255			.collect::<Vec<_>>(),256	);257258	let fctx = Context::new_future();259260	// We have single context for all fields, so we can cache binds261	let uctx = CachedUnbound::new(evaluate_object_locals(fctx.clone(), locals));262263	for member in members.iter() {264		match member {265			Member::Field(field) => {266				evaluate_field_member(&mut builder, ctx.clone(), uctx.clone(), field)?;267			}268			Member::AssertStmt(stmt) => {269				#[derive(Trace)]270				struct ObjectAssert<B: Trace> {271					uctx: B,272					assert: AssertStmt,273				}274				impl<B: Unbound<Bound = Context>> ObjectAssertion for ObjectAssert<B> {275					fn run(&self, sup: Option<ObjValue>, this: Option<ObjValue>) -> Result<()> {276						let ctx = self.uctx.bind(sup, this)?;277						evaluate_assert(ctx, &self.assert)278					}279				}280				builder.assert(tb!(ObjectAssert {281					uctx: uctx.clone(),282					assert: stmt.clone(),283				}));284			}285			Member::BindStmt(_) => {286				// Already handled287			}288		}289	}290	let this = builder.build();291	fctx.fill(ctx.extend(GcHashMap::new(), None, None, Some(this.clone())));292	Ok(this)293}294295pub fn evaluate_object(ctx: Context, object: &ObjBody) -> Result<ObjValue> {296	Ok(match object {297		ObjBody::MemberList(members) => evaluate_member_list_object(ctx, members)?,298		ObjBody::ObjComp(obj) => {299			let mut builder = ObjValueBuilder::new();300			let locals = Rc::new(301				obj.pre_locals302					.iter()303					.chain(obj.post_locals.iter())304					.cloned()305					.collect::<Vec<_>>(),306			);307			let mut ctxs = vec![];308			evaluate_comp(ctx, &obj.compspecs, &mut |ctx| {309				let fctx = Context::new_future();310				ctxs.push((ctx.clone(), fctx.clone()));311				let uctx = evaluate_object_locals(fctx, locals.clone());312313				evaluate_field_member(&mut builder, ctx, uctx, &obj.field)314			})?;315316			let this = builder.build();317			for (ctx, fctx) in ctxs {318				let _ctx = ctx319					.extend(GcHashMap::new(), None, None, Some(this.clone()))320					.into_future(fctx);321			}322			this323		}324	})325}326327pub fn evaluate_apply(328	ctx: Context,329	value: &LocExpr,330	args: &ArgsDesc,331	loc: CallLocation<'_>,332	tailstrict: bool,333) -> Result<Val> {334	let value = evaluate(ctx.clone(), value)?;335	Ok(match value {336		Val::Func(f) => {337			let body = || f.evaluate(ctx, loc, args, tailstrict);338			if tailstrict {339				body()?340			} else {341				State::push(loc, || format!("function <{}> call", f.name()), body)?342			}343		}344		v => throw!(OnlyFunctionsCanBeCalledGot(v.value_type())),345	})346}347348pub fn evaluate_assert(ctx: Context, assertion: &AssertStmt) -> Result<()> {349	let value = &assertion.0;350	let msg = &assertion.1;351	let assertion_result = State::push(352		CallLocation::new(&value.1),353		|| "assertion condition".to_owned(),354		|| bool::from_untyped(evaluate(ctx.clone(), value)?),355	)?;356	if !assertion_result {357		State::push(358			CallLocation::new(&value.1),359			|| "assertion failure".to_owned(),360			|| {361				if let Some(msg) = msg {362					throw!(AssertionFailed(evaluate(ctx, msg)?.to_string()?));363				}364				throw!(AssertionFailed(Val::Null.to_string()?));365			},366		)?;367	}368	Ok(())369}370371pub fn evaluate_named(ctx: Context, expr: &LocExpr, name: IStr) -> Result<Val> {372	use Expr::*;373	let LocExpr(raw_expr, _loc) = expr;374	Ok(match &**raw_expr {375		Function(params, body) => evaluate_method(ctx, name, params.clone(), body.clone()),376		_ => evaluate(ctx, expr)?,377	})378}379380#[allow(clippy::too_many_lines)]381pub fn evaluate(ctx: Context, expr: &LocExpr) -> Result<Val> {382	use Expr::*;383	let LocExpr(expr, loc) = expr;384	Ok(match &**expr {385		Literal(LiteralType::This) => {386			Val::Obj(ctx.this().clone().ok_or(CantUseSelfOutsideOfObject)?)387		}388		Literal(LiteralType::Super) => Val::Obj(389			ctx.super_obj().clone().ok_or(NoSuperFound)?.with_this(390				ctx.this()391					.clone()392					.expect("if super exists - then this should too"),393			),394		),395		Literal(LiteralType::Dollar) => {396			Val::Obj(ctx.dollar().clone().ok_or(NoTopLevelObjectFound)?)397		}398		Literal(LiteralType::True) => Val::Bool(true),399		Literal(LiteralType::False) => Val::Bool(false),400		Literal(LiteralType::Null) => Val::Null,401		Parened(e) => evaluate(ctx, e)?,402		Str(v) => Val::Str(v.clone()),403		Num(v) => Val::new_checked_num(*v)?,404		BinaryOp(v1, o, v2) => evaluate_binary_op_special(ctx, v1, *o, v2)?,405		UnaryOp(o, v) => evaluate_unary_op(*o, &evaluate(ctx, v)?)?,406		Var(name) => State::push(407			CallLocation::new(loc),408			|| format!("variable <{name}> access"),409			|| ctx.binding(name.clone())?.evaluate(),410		)?,411		Index(LocExpr(v, _), index) if matches!(&**v, Expr::Literal(LiteralType::Super)) => {412			let name = evaluate(ctx.clone(), index)?;413			let Val::Str(name) = name else {414				throw!(ValueIndexMustBeTypeGot(415					ValType::Obj,416					ValType::Str,417					name.value_type(),418				))419			};420			ctx.super_obj()421				.clone()422				.expect("no super found")423				.get_for(name, ctx.this().clone().expect("no this found"))?424				.expect("value not found")425		}426		Index(value, index) => match (evaluate(ctx.clone(), value)?, evaluate(ctx, index)?) {427			(Val::Obj(v), Val::Str(key)) => State::push(428				CallLocation::new(loc),429				|| format!("field <{key}> access"),430				|| match v.get(key.clone()) {431					Ok(Some(v)) => Ok(v),432					#[cfg(not(feature = "friendly-errors"))]433					Ok(None) => throw!(NoSuchField(key.clone(), vec![])),434					#[cfg(feature = "friendly-errors")]435					Ok(None) => {436						let mut heap = Vec::new();437						for field in v.fields_ex(438							true,439							#[cfg(feature = "exp-preserve-order")]440							false,441						) {442							let conf = strsim::jaro_winkler(&field as &str, &key as &str);443							if conf < 0.8 {444								continue;445							}446							heap.push((conf, field));447						}448						heap.sort_by(|a, b| b.0.partial_cmp(&a.0).unwrap_or(Ordering::Equal));449450						throw!(NoSuchField(451							key.clone(),452							heap.into_iter().map(|(_, v)| v).collect()453						))454					}455					Err(e) => Err(e),456				},457			)?,458			(Val::Obj(_), n) => throw!(ValueIndexMustBeTypeGot(459				ValType::Obj,460				ValType::Str,461				n.value_type(),462			)),463464			(Val::Arr(v), Val::Num(n)) => {465				if n.fract() > f64::EPSILON {466					throw!(FractionalIndex)467				}468				v.get(n as usize)?469					.ok_or_else(|| ArrayBoundsError(n as usize, v.len()))?470			}471			(Val::Arr(_), Val::Str(n)) => throw!(AttemptedIndexAnArrayWithString(n)),472			(Val::Arr(_), n) => throw!(ValueIndexMustBeTypeGot(473				ValType::Arr,474				ValType::Num,475				n.value_type(),476			)),477478			(Val::Str(s), Val::Num(n)) => Val::Str({479				let v: IStr = s480					.chars()481					.skip(n as usize)482					.take(1)483					.collect::<String>()484					.into();485				if v.is_empty() {486					let size = s.chars().count();487					throw!(StringBoundsError(n as usize, size))488				}489				v490			}),491			(Val::Str(_), n) => throw!(ValueIndexMustBeTypeGot(492				ValType::Str,493				ValType::Num,494				n.value_type(),495			)),496497			(v, _) => throw!(CantIndexInto(v.value_type())),498		},499		LocalExpr(bindings, returned) => {500			let mut new_bindings: GcHashMap<IStr, Thunk<Val>> =501				GcHashMap::with_capacity(bindings.iter().map(BindSpec::capacity_hint).sum());502			let fctx = Context::new_future();503			for b in bindings {504				evaluate_dest(b, fctx.clone(), &mut new_bindings)?;505			}506			let ctx = ctx.extend(new_bindings, None, None, None).into_future(fctx);507			evaluate(ctx, &returned.clone())?508		}509		Arr(items) => {510			let mut out = Vec::with_capacity(items.len());511			for item in items {512				// TODO: Implement ArrValue::Lazy with same context for every element?513				#[derive(Trace)]514				struct ArrayElement {515					ctx: Context,516					item: LocExpr,517				}518				impl ThunkValue for ArrayElement {519					type Output = Val;520					fn get(self: Box<Self>) -> Result<Val> {521						evaluate(self.ctx, &self.item)522					}523				}524				out.push(Thunk::new(tb!(ArrayElement {525					ctx: ctx.clone(),526					item: item.clone(),527				})));528			}529			Val::Arr(out.into())530		}531		ArrComp(expr, comp_specs) => {532			let mut out = Vec::new();533			evaluate_comp(ctx, comp_specs, &mut |ctx| {534				out.push(evaluate(ctx, expr)?);535				Ok(())536			})?;537			Val::Arr(ArrValue::Eager(Cc::new(out)))538		}539		Obj(body) => Val::Obj(evaluate_object(ctx, body)?),540		ObjExtend(a, b) => evaluate_add_op(541			&evaluate(ctx.clone(), a)?,542			&Val::Obj(evaluate_object(ctx, b)?),543		)?,544		Apply(value, args, tailstrict) => {545			evaluate_apply(ctx, value, args, CallLocation::new(loc), *tailstrict)?546		}547		Function(params, body) => {548			evaluate_method(ctx, "anonymous".into(), params.clone(), body.clone())549		}550		AssertExpr(assert, returned) => {551			evaluate_assert(ctx.clone(), assert)?;552			evaluate(ctx, returned)?553		}554		ErrorStmt(e) => State::push(555			CallLocation::new(loc),556			|| "error statement".to_owned(),557			|| throw!(RuntimeError(evaluate(ctx, e)?.to_string()?,)),558		)?,559		IfElse {560			cond,561			cond_then,562			cond_else,563		} => {564			if State::push(565				CallLocation::new(loc),566				|| "if condition".to_owned(),567				|| bool::from_untyped(evaluate(ctx.clone(), &cond.0)?),568			)? {569				evaluate(ctx, cond_then)?570			} else {571				match cond_else {572					Some(v) => evaluate(ctx, v)?,573					None => Val::Null,574				}575			}576		}577		Slice(value, desc) => {578			fn parse_idx<T: Typed>(579				loc: CallLocation<'_>,580				ctx: &Context,581				expr: &Option<LocExpr>,582				desc: &'static str,583			) -> Result<Option<T>> {584				if let Some(value) = expr {585					Ok(Some(State::push(586						loc,587						|| format!("slice {desc}"),588						|| T::from_untyped(evaluate(ctx.clone(), value)?),589					)?))590				} else {591					Ok(None)592				}593			}594595			let indexable = evaluate(ctx.clone(), value)?;596			let loc = CallLocation::new(loc);597598			let start = parse_idx(loc, &ctx, &desc.start, "start")?;599			let end = parse_idx(loc, &ctx, &desc.end, "end")?;600			let step = parse_idx(loc, &ctx, &desc.step, "step")?;601602			IndexableVal::into_untyped(indexable.into_indexable()?.slice(start, end, step)?)?603		}604		i @ (Import(path) | ImportStr(path) | ImportBin(path)) => {605			let Expr::Str(path) = &*path.0 else {606				throw!("computed imports are not supported")607			};608			let tmp = loc.clone().0;609			let s = ctx.state();610			let resolved_path = s.resolve_from(tmp.source_path(), path as &str)?;611			match i {612				Import(_) => State::push(613					CallLocation::new(loc),614					|| format!("import {:?}", path.clone()),615					|| s.import_resolved(resolved_path),616				)?,617				ImportStr(_) => Val::Str(s.import_resolved_str(resolved_path)?),618				ImportBin(_) => Val::Arr(ArrValue::Bytes(s.import_resolved_bin(resolved_path)?)),619				_ => unreachable!(),620			}621		}622	})623}
modifiedcrates/jrsonnet-evaluator/src/evaluate/operator.rsdiffbeforeafterboth
--- a/crates/jrsonnet-evaluator/src/evaluate/operator.rs
+++ b/crates/jrsonnet-evaluator/src/evaluate/operator.rs
@@ -3,8 +3,8 @@
 use jrsonnet_parser::{BinaryOpType, LocExpr, UnaryOpType};
 
 use crate::{
-	error::ErrorKind::*, evaluate, stdlib::std_format, throw, typed::Typed, val::equals, Context,
-	Result, Val,
+	arr::ArrValue, error::ErrorKind::*, evaluate, stdlib::std_format, throw, typed::Typed,
+	val::equals, Context, Result, Val,
 };
 
 pub fn evaluate_unary_op(op: UnaryOpType, b: &Val) -> Result<Val> {
@@ -18,6 +18,8 @@
 	})
 }
 
+/// Arbitrary threshold
+
 pub fn evaluate_add_op(a: &Val, b: &Val) -> Result<Val> {
 	use Val::*;
 	Ok(match (a, b) {
@@ -34,12 +36,8 @@
 		(o, Str(a)) => Str(format!("{}{a}", o.clone().to_string()?).into()),
 
 		(Obj(v1), Obj(v2)) => Obj(v2.extend_from(v1.clone())),
-		(Arr(a), Arr(b)) => {
-			let mut out = Vec::with_capacity(a.len() + b.len());
-			out.extend(a.iter_lazy());
-			out.extend(b.iter_lazy());
-			Arr(out.into())
-		}
+		(Arr(a), Arr(b)) => Val::Arr(ArrValue::extended(a.clone(), b.clone())),
+
 		(Num(v1), Num(v2)) => Val::new_checked_num(v1 + v2)?,
 		_ => throw!(BinaryOperatorDoesNotOperateOnValues(
 			BinaryOpType::Add,
@@ -82,7 +80,7 @@
 	})
 }
 
-pub fn evaluate_compare_op(a: &Val, op: BinaryOpType, b: &Val) -> Result<Ordering> {
+pub fn evaluate_compare_op(a: &Val, b: &Val, op: BinaryOpType) -> Result<Ordering> {
 	use Val::*;
 	Ok(match (a, b) {
 		(Str(a), Str(b)) => a.cmp(b),
@@ -92,7 +90,7 @@
 			let bi = b.iter();
 
 			for (a, b) in ai.zip(bi) {
-				let ord = evaluate_compare_op(&a?, op, &b?)?;
+				let ord = evaluate_compare_op(&a?, &b?, op)?;
 				if !ord.is_eq() {
 					return Ok(ord);
 				}
@@ -117,10 +115,10 @@
 		(a, Eq, b) => Bool(equals(a, b)?),
 		(a, Neq, b) => Bool(!equals(a, b)?),
 
-		(a, Lt, b) => Bool(evaluate_compare_op(a, Lt, b)?.is_lt()),
-		(a, Gt, b) => Bool(evaluate_compare_op(a, Gt, b)?.is_gt()),
-		(a, Lte, b) => Bool(evaluate_compare_op(a, Lte, b)?.is_le()),
-		(a, Gte, b) => Bool(evaluate_compare_op(a, Gte, b)?.is_ge()),
+		(a, Lt, b) => Bool(evaluate_compare_op(a, b, Lt)?.is_lt()),
+		(a, Gt, b) => Bool(evaluate_compare_op(a, b, Gt)?.is_gt()),
+		(a, Lte, b) => Bool(evaluate_compare_op(a, b, Lte)?.is_le()),
+		(a, Gte, b) => Bool(evaluate_compare_op(a, b, Gte)?.is_ge()),
 
 		(Str(a), In, Obj(obj)) => Bool(obj.has_field_ex(a.clone(), true)),
 		(a, Mod, b) => evaluate_mod_op(a, b)?,
modifiedcrates/jrsonnet-evaluator/src/integrations/serde.rsdiffbeforeafterboth
--- a/crates/jrsonnet-evaluator/src/integrations/serde.rs
+++ b/crates/jrsonnet-evaluator/src/integrations/serde.rs
@@ -7,7 +7,7 @@
 	Deserialize, Serialize,
 };
 
-use crate::{error::Result, val::ArrValue, ObjValueBuilder, State, Val};
+use crate::{arr::ArrValue, error::Result, ObjValueBuilder, State, Val};
 
 impl<'de> Deserialize<'de> for Val {
 	fn deserialize<D>(deserializer: D) -> Result<Val, D::Error>
@@ -77,7 +77,7 @@
 			where
 				E: serde::de::Error,
 			{
-				Ok(Val::Arr(ArrValue::Bytes(v.into())))
+				Ok(Val::Arr(ArrValue::bytes(v.into())))
 			}
 
 			fn visit_none<E>(self) -> Result<Self::Value, E>
@@ -117,7 +117,7 @@
 					out.push(val);
 				}
 
-				Ok(Val::Arr(ArrValue::Eager(Cc::new(out))))
+				Ok(Val::Arr(ArrValue::eager(Cc::new(out))))
 			}
 
 			fn visit_map<A>(self, mut map: A) -> Result<Self::Value, A::Error>
modifiedcrates/jrsonnet-evaluator/src/lib.rsdiffbeforeafterboth
--- a/crates/jrsonnet-evaluator/src/lib.rs
+++ b/crates/jrsonnet-evaluator/src/lib.rs
@@ -1,5 +1,6 @@
 //! jsonnet interpreter implementation
 #![cfg_attr(feature = "nightly", feature(thread_local))]
+#![feature(type_alias_impl_trait)]
 #![deny(unsafe_op_in_unsafe_fn)]
 #![warn(
 	clippy::all,
@@ -43,6 +44,7 @@
 // For jrsonnet-macros
 extern crate self as jrsonnet_evaluator;
 
+mod arr;
 mod ctx;
 mod dynamic;
 pub mod error;
modifiedcrates/jrsonnet-evaluator/src/stdlib/mod.rsdiffbeforeafterboth
--- a/crates/jrsonnet-evaluator/src/stdlib/mod.rs
+++ b/crates/jrsonnet-evaluator/src/stdlib/mod.rs
@@ -14,7 +14,7 @@
 		|| format!("std.format of {str}"),
 		|| {
 			Ok(match vals {
-				Val::Arr(vals) => format_arr(&str, &vals.evaluated()?)?,
+				Val::Arr(vals) => format_arr(&str, &vals.evaluatedcc()?)?,
 				Val::Obj(obj) => format_obj(&str, &obj)?,
 				o => format_arr(&str, &[o])?,
 			})
modifiedcrates/jrsonnet-evaluator/src/typed/conversions.rsdiffbeforeafterboth
--- a/crates/jrsonnet-evaluator/src/typed/conversions.rs
+++ b/crates/jrsonnet-evaluator/src/typed/conversions.rs
@@ -6,11 +6,12 @@
 use jrsonnet_types::{ComplexValType, ValType};
 
 use crate::{
+	arr::ArrValue,
 	error::Result,
 	function::{native::NativeDesc, FuncDesc, FuncVal},
 	throw,
 	typed::CheckType,
-	val::{ArrValue, IndexableVal},
+	val::IndexableVal,
 	ObjValue, ObjValueBuilder, Val,
 };
 
@@ -30,6 +31,8 @@
 	fn from_untyped(untyped: Val) -> Result<Self>;
 }
 
+const MAX_SAFE_INTEGER: f64 = ((1u64 << (f64::MANTISSA_DIGITS + 1)) - 1) as f64;
+
 macro_rules! impl_int {
 	($($ty:ty)*) => {$(
 		impl Typed for $ty {
@@ -155,12 +158,11 @@
 	}
 }
 impl Typed for usize {
-	// It is possible to store 54 bits of precision in f64, but leaving u32::MAX here for compatibility
 	const TYPE: &'static ComplexValType =
-		&ComplexValType::BoundedNumber(Some(0.0), Some(u32::MAX as f64));
+		&ComplexValType::BoundedNumber(Some(0.0), Some(MAX_SAFE_INTEGER));
 
 	fn into_untyped(value: Self) -> Result<Val> {
-		if value > u32::MAX as Self {
+		if value > MAX_SAFE_INTEGER as Self {
 			throw!("number is too large")
 		}
 		Ok(Val::Num(value as f64))
@@ -282,13 +284,13 @@
 	const TYPE: &'static ComplexValType = &ComplexValType::Simple(ValType::Arr);
 
 	fn into_untyped(value: Self) -> Result<Val> {
-		Ok(Val::Arr(ArrValue::Eager(value.0)))
+		Ok(Val::Arr(ArrValue::eager(value.0)))
 	}
 
 	fn from_untyped(value: Val) -> Result<Self> {
 		<Self as Typed>::TYPE.check(&value)?;
 		match value {
-			Val::Arr(a) => Ok(Self(a.evaluated()?)),
+			Val::Arr(a) => Ok(Self(a.evaluatedcc()?)),
 			_ => unreachable!(),
 		}
 	}
@@ -300,12 +302,12 @@
 		&ComplexValType::ArrayRef(&ComplexValType::BoundedNumber(Some(0.0), Some(255.0)));
 
 	fn into_untyped(value: Self) -> Result<Val> {
-		Ok(Val::Arr(ArrValue::Bytes(value)))
+		Ok(Val::Arr(ArrValue::bytes(value)))
 	}
 
 	fn from_untyped(value: Val) -> Result<Self> {
 		if let Val::Arr(ArrValue::Bytes(bytes)) = value {
-			return Ok(bytes);
+			return Ok(bytes.0);
 		}
 		<Self as Typed>::TYPE.check(&value)?;
 		match value {
modifiedcrates/jrsonnet-evaluator/src/val.rsdiffbeforeafterboth
--- a/crates/jrsonnet-evaluator/src/val.rs
+++ b/crates/jrsonnet-evaluator/src/val.rs
@@ -1,9 +1,10 @@
-use std::{cell::RefCell, fmt::Debug};
+use std::{cell::RefCell, fmt::Debug, mem::replace};
 
 use jrsonnet_gcmodule::{Cc, Trace};
-use jrsonnet_interner::{IBytes, IStr};
+use jrsonnet_interner::IStr;
 use jrsonnet_types::ValType;
 
+pub use crate::arr::ArrValue;
 use crate::{
 	error::{Error, ErrorKind::*},
 	function::FuncVal,
@@ -31,16 +32,22 @@
 #[derive(Clone, Trace)]
 pub struct Thunk<T: Trace>(Cc<RefCell<ThunkInner<T>>>);
 
+impl<T: Trace> Thunk<T> {
+	pub fn evaluated(val: T) -> Self {
+		Self(Cc::new(RefCell::new(ThunkInner::Computed(val))))
+	}
+	pub fn new(f: TraceBox<dyn ThunkValue<Output = T>>) -> Self {
+		Self(Cc::new(RefCell::new(ThunkInner::Waiting(f))))
+	}
+	pub fn errored(e: Error) -> Self {
+		Self(Cc::new(RefCell::new(ThunkInner::Errored(e))))
+	}
+}
+
 impl<T> Thunk<T>
 where
 	T: Clone + Trace,
 {
-	pub fn new(f: TraceBox<dyn ThunkValue<Output = T>>) -> Self {
-		Self(Cc::new(RefCell::new(ThunkInner::Waiting(f))))
-	}
-	pub fn evaluated(val: T) -> Self {
-		Self(Cc::new(RefCell::new(ThunkInner::Computed(val))))
-	}
 	pub fn force(&self) -> Result<()> {
 		self.evaluate()?;
 		Ok(())
@@ -52,7 +59,7 @@
 			ThunkInner::Pending => return Err(InfiniteRecursionDetected.into()),
 			ThunkInner::Waiting(..) => (),
 		};
-		let ThunkInner::Waiting(value) = std::mem::replace(&mut *self.0.borrow_mut(), ThunkInner::Pending) else {
+		let ThunkInner::Waiting(value) = replace(&mut *self.0.borrow_mut(), ThunkInner::Pending) else {
 			unreachable!();
 		};
 		let new_value = match value.0.get() {
@@ -118,337 +125,8 @@
 	fn eq(&self, other: &Self) -> bool {
 		Cc::ptr_eq(&self.0, &other.0)
 	}
-}
-
-#[derive(Debug, Clone, Trace)]
-pub struct Slice {
-	pub(crate) inner: ArrValue,
-	pub(crate) from: u32,
-	pub(crate) to: u32,
-	pub(crate) step: u32,
 }
-impl Slice {
-	const fn from(&self) -> usize {
-		self.from as usize
-	}
-	const fn to(&self) -> usize {
-		self.to as usize
-	}
-	const fn step(&self) -> usize {
-		self.step as usize
-	}
-	const fn len(&self) -> usize {
-		// TODO: use div_ceil
-		let diff = self.to() - self.from();
-		let rem = diff % self.step();
-		let div = diff / self.step();
-
-		if rem == 0 {
-			div
-		} else {
-			div + 1
-		}
-	}
-}
-
-/// Represents a Jsonnet array value.
-#[derive(Debug, Clone, Trace)]
-// may contrain other ArrValue
-#[trace(tracking(force))]
-pub enum ArrValue {
-	/// Layout optimized byte array.
-	Bytes(#[trace(skip)] IBytes),
-	/// Every element is lazy evaluated.
-	Lazy(Cc<Vec<Thunk<Val>>>),
-	/// Every field is already evaluated.
-	Eager(Cc<Vec<Val>>),
-	/// Concatenation of two arrays of any kind.
-	Extended(Box<(Self, Self)>),
-	/// Represents a integer array in form `[start, start + 1, ... end - 1, end]`.
-	/// This kind of arrays is generated by `std.range(start, end)` call, and used for loops.
-	Range(i32, i32),
-	/// Sliced array view.
-	Slice(Box<Slice>),
-	/// Reversed array view.
-	/// Returned by `std.reverse(other)` call
-	Reversed(Box<Self>),
-}
-
-#[cfg(target_pointer_width = "64")]
-static_assertions::assert_eq_size!(ArrValue, [u8; 16]);
-
-impl ArrValue {
-	pub fn new_eager() -> Self {
-		Self::Eager(Cc::new(Vec::new()))
-	}
-	pub fn empty() -> Self {
-		Self::new_range(0, 0)
-	}
-
-	/// # Panics
-	/// If a > b
-	#[inline]
-	pub fn new_range(a: i32, b: i32) -> Self {
-		assert!(a <= b);
-		Self::Range(a, b)
-	}
-
-	/// # Panics
-	/// If passed numbers are incorrect
-	#[must_use]
-	pub fn slice(self, from: Option<usize>, to: Option<usize>, step: Option<usize>) -> Self {
-		let len = self.len();
-		let from = from.unwrap_or(0);
-		let to = to.unwrap_or(len).min(len);
-		let step = step.unwrap_or(1);
-		assert!(from < to);
-		assert!(step > 0);
-
-		Self::Slice(Box::new(Slice {
-			inner: self,
-			from: from as u32,
-			to: to as u32,
-			step: step as u32,
-		}))
-	}
 
-	/// Array length.
-	pub fn len(&self) -> usize {
-		match self {
-			Self::Bytes(i) => i.len(),
-			Self::Lazy(l) => l.len(),
-			Self::Eager(e) => e.len(),
-			Self::Extended(v) => v.0.len() + v.1.len(),
-			Self::Range(a, b) => a.abs_diff(*b) as usize + 1,
-			Self::Reversed(i) => i.len(),
-			Self::Slice(s) => s.len(),
-		}
-	}
-
-	/// Is array contains no elements?
-	pub fn is_empty(&self) -> bool {
-		self.len() == 0
-	}
-
-	/// Get array element by index, evaluating it, if it is lazy.
-	///
-	/// Returns `None` on out-of-bounds condition.
-	pub fn get(&self, index: usize) -> Result<Option<Val>> {
-		match self {
-			Self::Bytes(i) => i
-				.get(index)
-				.map_or(Ok(None), |v| Ok(Some(Val::Num(f64::from(*v))))),
-			Self::Lazy(vec) => {
-				if let Some(v) = vec.get(index) {
-					Ok(Some(v.evaluate()?))
-				} else {
-					Ok(None)
-				}
-			}
-			Self::Eager(vec) => Ok(vec.get(index).cloned()),
-			Self::Extended(v) => {
-				let a_len = v.0.len();
-				if a_len > index {
-					v.0.get(index)
-				} else {
-					v.1.get(index - a_len)
-				}
-			}
-			Self::Range(a, _) => {
-				if index >= self.len() {
-					return Ok(None);
-				}
-				Ok(Some(Val::Num(((*a as isize) + index as isize) as f64)))
-			}
-			Self::Reversed(v) => {
-				let len = v.len();
-				if index >= len {
-					return Ok(None);
-				}
-				v.get(len - index - 1)
-			}
-			Self::Slice(v) => {
-				let index = v.from() + index * v.step();
-				if index >= v.to() {
-					return Ok(None);
-				}
-				v.inner.get(index)
-			}
-		}
-	}
-
-	/// Get array element by index, without evaluation.
-	///
-	/// Returns `None` on out-of-bounds condition.
-	pub fn get_lazy(&self, index: usize) -> Option<Thunk<Val>> {
-		match self {
-			Self::Bytes(i) => i
-				.get(index)
-				.map(|b| Thunk::evaluated(Val::Num(f64::from(*b)))),
-			Self::Lazy(vec) => vec.get(index).cloned(),
-			Self::Eager(vec) => vec.get(index).cloned().map(Thunk::evaluated),
-			Self::Extended(v) => {
-				let a_len = v.0.len();
-				if a_len > index {
-					v.0.get_lazy(index)
-				} else {
-					v.1.get_lazy(index - a_len)
-				}
-			}
-			Self::Range(a, _) => {
-				if index >= self.len() {
-					return None;
-				}
-				Some(Thunk::evaluated(Val::Num(
-					((*a as isize) + index as isize) as f64,
-				)))
-			}
-			Self::Reversed(v) => {
-				let len = v.len();
-				if index >= len {
-					return None;
-				}
-				v.get_lazy(len - index - 1)
-			}
-			Self::Slice(s) => {
-				let index = s.from() + index * s.step();
-				if index >= s.to() {
-					return None;
-				}
-				s.inner.get_lazy(index)
-			}
-		}
-	}
-
-	/// Evaluate all array elements, returning new array.
-	pub fn evaluated(&self) -> Result<Cc<Vec<Val>>> {
-		Ok(match self {
-			Self::Bytes(i) => {
-				let mut out = Vec::with_capacity(i.len());
-				for v in i.iter() {
-					out.push(Val::Num(f64::from(*v)));
-				}
-				Cc::new(out)
-			}
-			Self::Lazy(vec) => {
-				let mut out = Vec::with_capacity(vec.len());
-				for item in vec.iter() {
-					out.push(item.evaluate()?);
-				}
-				Cc::new(out)
-			}
-			Self::Eager(vec) => vec.clone(),
-			Self::Extended(_v) => {
-				let mut out = Vec::with_capacity(self.len());
-				for item in self.iter() {
-					out.push(item?);
-				}
-				Cc::new(out)
-			}
-			Self::Range(a, b) => {
-				let mut out = Vec::with_capacity(self.len());
-				for i in *a..=*b {
-					out.push(Val::Num(f64::from(i)));
-				}
-				Cc::new(out)
-			}
-			Self::Reversed(r) => {
-				let mut r = r.evaluated()?;
-				Cc::update_with(&mut r, |v| v.reverse());
-				r
-			}
-			Self::Slice(v) => {
-				let mut out = Vec::with_capacity(v.inner.len());
-				for v in v
-					.inner
-					.iter_lazy()
-					.skip(v.from())
-					.take(v.to() - v.from())
-					.step_by(v.step())
-				{
-					out.push(v.evaluate()?);
-				}
-				Cc::new(out)
-			}
-		})
-	}
-
-	/// Iterate over elements, evaluating them.
-	pub fn iter(&self) -> impl DoubleEndedIterator<Item = Result<Val>> + '_ {
-		(0..self.len()).map(move |idx| match self {
-			Self::Bytes(b) => Ok(Val::Num(f64::from(b[idx]))),
-			Self::Lazy(l) => l[idx].evaluate(),
-			Self::Eager(e) => Ok(e[idx].clone()),
-			Self::Extended(..) | Self::Range(..) | Self::Reversed(..) | Self::Slice(..) => {
-				self.get(idx).map(|e| e.expect("idx < len"))
-			}
-		})
-	}
-
-	/// Iterate over elements, returning lazy values.
-	pub fn iter_lazy(&self) -> impl DoubleEndedIterator<Item = Thunk<Val>> + '_ {
-		(0..self.len()).map(move |idx| match self {
-			Self::Bytes(b) => Thunk::evaluated(Val::Num(f64::from(b[idx]))),
-			Self::Lazy(l) => l[idx].clone(),
-			Self::Eager(e) => Thunk::evaluated(e[idx].clone()),
-			Self::Slice(..) | Self::Extended(..) | Self::Range(..) | Self::Reversed(..) => {
-				self.get_lazy(idx).expect("idx < len")
-			}
-		})
-	}
-
-	/// Return a reversed view on current array.
-	#[must_use]
-	pub fn reversed(self) -> Self {
-		Self::Reversed(Box::new(self))
-	}
-
-	/// Return a new array, produced by passing every element of current array to specified callback function.
-	pub fn map(self, mapper: impl Fn(Val) -> Result<Val>) -> Result<Self> {
-		let mut out = Vec::with_capacity(self.len());
-
-		for value in self.iter() {
-			out.push(mapper(value?)?);
-		}
-
-		Ok(Self::Eager(Cc::new(out)))
-	}
-
-	/// Return a new array, produced from current array by removing every value, for which specified callback function returns false.
-	pub fn filter(self, filter: impl Fn(&Val) -> Result<bool>) -> Result<Self> {
-		let mut out = Vec::with_capacity(self.len());
-
-		for value in self.iter() {
-			let value = value?;
-			if filter(&value)? {
-				out.push(value);
-			}
-		}
-
-		Ok(Self::Eager(Cc::new(out)))
-	}
-
-	pub fn ptr_eq(a: &Self, b: &Self) -> bool {
-		match (a, b) {
-			(Self::Lazy(a), Self::Lazy(b)) => Cc::ptr_eq(a, b),
-			(Self::Eager(a), Self::Eager(b)) => Cc::ptr_eq(a, b),
-			_ => false,
-		}
-	}
-}
-
-impl From<Vec<Thunk<Val>>> for ArrValue {
-	fn from(v: Vec<Thunk<Val>>) -> Self {
-		Self::Lazy(Cc::new(v))
-	}
-}
-
-impl From<Vec<Val>> for ArrValue {
-	fn from(v: Vec<Val>) -> Self {
-		Self::Eager(Cc::new(v))
-	}
-}
-
 /// Represents a Jsonnet value, which can be spliced or indexed (string or array).
 #[allow(clippy::module_name_repetitions)]
 pub enum IndexableVal {
@@ -496,15 +174,14 @@
 				let step = step.as_deref().copied().unwrap_or(1);
 
 				if index >= end {
-					return Ok(Self::Arr(ArrValue::new_eager()));
+					return Ok(Self::Arr(ArrValue::empty()));
 				}
 
-				Ok(Self::Arr(ArrValue::Slice(Box::new(Slice {
-					inner: arr.clone(),
-					from: index as u32,
-					to: end as u32,
-					step: step as u32,
-				}))))
+				Ok(Self::Arr(
+					arr.clone()
+						.slice(Some(index), Some(end), Some(step))
+						.expect("arguments checked"),
+				))
 			}
 		}
 	}
@@ -539,10 +216,6 @@
 		}
 	}
 }
-
-// Broken between stable and nightly, as there is new layout size optimization
-// #[cfg(target_pointer_width = "64")]
-// static_assertions::assert_eq_size!(Val, [u8; 24]);
 
 impl Val {
 	pub const fn as_bool(&self) -> Option<bool> {
modifiedcrates/jrsonnet-stdlib/src/arrays.rsdiffbeforeafterboth
--- a/crates/jrsonnet-stdlib/src/arrays.rs
+++ b/crates/jrsonnet-stdlib/src/arrays.rs
@@ -28,8 +28,8 @@
 }
 
 #[builtin]
-pub fn builtin_map(func: NativeFn<((Any,), Any)>, arr: ArrValue) -> Result<ArrValue> {
-	arr.map(|val| Ok(func(Any(val))?.0))
+pub fn builtin_map(func: FuncVal, arr: ArrValue) -> Result<ArrValue> {
+	Ok(arr.map(func))
 }
 
 #[builtin]
@@ -94,9 +94,9 @@
 #[builtin]
 pub fn builtin_range(from: i32, to: i32) -> Result<ArrValue> {
 	if to < from {
-		return Ok(ArrValue::new_eager());
+		return Ok(ArrValue::empty());
 	}
-	Ok(ArrValue::new_range(from, to))
+	Ok(ArrValue::range_inclusive(from, to))
 }
 
 #[builtin]
modifiedcrates/jrsonnet-stdlib/src/misc.rsdiffbeforeafterboth
--- a/crates/jrsonnet-stdlib/src/misc.rs
+++ b/crates/jrsonnet-stdlib/src/misc.rs
@@ -77,7 +77,7 @@
 			} else if b.len() == a.len() {
 				return equals(&Val::Arr(a), &Val::Arr(b));
 			} else {
-				for (a, b) in a.slice(None, Some(b.len()), None).iter().zip(b.iter()) {
+				for (a, b) in a.iter().take(b.len()).zip(b.iter()) {
 					let a = a?;
 					let b = b?;
 					if !equals(&a, &b)? {
@@ -103,11 +103,7 @@
 				return equals(&Val::Arr(a), &Val::Arr(b));
 			} else {
 				let a_len = a.len();
-				for (a, b) in a
-					.slice(Some(a_len - b.len()), None, None)
-					.iter()
-					.zip(b.iter())
-				{
+				for (a, b) in a.iter().skip(a_len - b.len()).zip(b.iter()) {
 					let a = a?;
 					let b = b?;
 					if !equals(&a, &b)? {
modifiedcrates/jrsonnet-stdlib/src/sort.rsdiffbeforeafterboth
--- a/crates/jrsonnet-stdlib/src/sort.rs
+++ b/crates/jrsonnet-stdlib/src/sort.rs
@@ -106,9 +106,9 @@
 	if arr.len() <= 1 {
 		return Ok(arr);
 	}
-	Ok(ArrValue::Eager(super::sort::sort(
+	Ok(ArrValue::eager(super::sort::sort(
 		ctx,
-		arr.evaluated()?,
+		arr.evaluatedcc()?,
 		keyF.unwrap_or_else(FuncVal::identity),
 	)?))
 }