git.delta.rocks / jrsonnet / refs/commits / b3f009bb7b2e

difftreelog

source

crates/jrsonnet-evaluator/src/arr/spec.rs13.6 KiBsourcehistory
1use std::rc::Rc;2use std::{any::Any, cell::RefCell, fmt::Debug, mem::replace};34use jrsonnet_gcmodule::{Cc, Trace};5use jrsonnet_interner::{IBytes, IStr};6use jrsonnet_parser::{Expr, Spanned};78use super::ArrValue;9use crate::{10	error::ErrorKind::InfiniteRecursionDetected, evaluate, function::FuncVal, typed::Typed,11	val::ThunkValue, Context, Error, ObjValue, Result, Thunk, Val,12};1314pub trait ArrayLike: Any + Trace + Debug {15	fn len(&self) -> usize;16	fn is_empty(&self) -> bool {17		self.len() == 018	}19	fn get(&self, index: usize) -> Result<Option<Val>>;20	fn get_lazy(&self, index: usize) -> Option<Thunk<Val>>;21	fn get_cheap(&self, index: usize) -> Option<Val>;2223	fn is_cheap(&self) -> bool;24}2526#[derive(Debug, Trace)]27pub struct SliceArray {28	pub(crate) inner: ArrValue,29	pub(crate) from: u32,30	pub(crate) to: u32,31	pub(crate) step: u32,32}3334impl SliceArray {35	fn map_idx(&self, index: usize) -> usize {36		self.from as usize + self.step as usize * index37	}38}39impl ArrayLike for SliceArray {40	fn len(&self) -> usize {41		((self.to - self.from + self.step - 1) / self.step) as usize42	}4344	fn get(&self, index: usize) -> Result<Option<Val>> {45		self.inner.get(self.map_idx(index))46	}4748	fn get_lazy(&self, index: usize) -> Option<Thunk<Val>> {49		self.inner.get_lazy(self.map_idx(index))50	}5152	fn get_cheap(&self, index: usize) -> Option<Val> {53		self.inner.get_cheap(self.map_idx(index))54	}55	fn is_cheap(&self) -> bool {56		self.inner.is_cheap()57	}58}5960#[derive(Trace, Debug)]61pub struct CharArray(pub Vec<char>);62impl ArrayLike for CharArray {63	fn len(&self) -> usize {64		self.0.len()65	}6667	fn get(&self, index: usize) -> Result<Option<Val>> {68		Ok(self.get_cheap(index))69	}7071	fn get_lazy(&self, index: usize) -> Option<Thunk<Val>> {72		self.get_cheap(index).map(Thunk::evaluated)73	}7475	fn get_cheap(&self, index: usize) -> Option<Val> {76		self.0.get(index).map(|v| Val::string(*v))77	}78	fn is_cheap(&self) -> bool {79		true80	}81}8283#[derive(Trace, Debug)]84pub struct BytesArray(pub IBytes);85impl ArrayLike for BytesArray {86	fn len(&self) -> usize {87		self.0.len()88	}8990	fn get(&self, index: usize) -> Result<Option<Val>> {91		Ok(self.get_cheap(index))92	}9394	fn get_lazy(&self, index: usize) -> Option<Thunk<Val>> {95		self.get_cheap(index).map(Thunk::evaluated)96	}9798	fn get_cheap(&self, index: usize) -> Option<Val> {99		self.0.get(index).map(|v| Val::Num((*v).into()))100	}101	fn is_cheap(&self) -> bool {102		true103	}104}105106#[derive(Debug, Trace, Clone)]107enum ArrayThunk {108	Computed(Val),109	Errored(Error),110	Waiting,111	Pending,112}113114#[derive(Debug, Trace, Clone)]115pub struct ExprArray {116	ctx: Context,117	src: Rc<Vec<Spanned<Expr>>>,118	cached: Cc<RefCell<Vec<ArrayThunk>>>,119}120impl ExprArray {121	pub fn new(ctx: Context, src: Rc<Vec<Spanned<Expr>>>) -> Self {122		Self {123			ctx,124			cached: Cc::new(RefCell::new(vec![ArrayThunk::Waiting; src.len()])),125			src,126		}127	}128}129impl ArrayLike for ExprArray {130	fn len(&self) -> usize {131		self.cached.borrow().len()132	}133	fn get(&self, index: usize) -> Result<Option<Val>> {134		if index >= self.len() {135			return Ok(None);136		}137		match &self.cached.borrow()[index] {138			ArrayThunk::Computed(c) => return Ok(Some(c.clone())),139			ArrayThunk::Errored(e) => return Err(e.clone()),140			ArrayThunk::Pending => return Err(InfiniteRecursionDetected.into()),141			ArrayThunk::Waiting => {}142		};143144		let ArrayThunk::Waiting =145			replace(&mut self.cached.borrow_mut()[index], ArrayThunk::Pending)146		else {147			unreachable!()148		};149150		let new_value = match evaluate(self.ctx.clone(), &self.src[index]) {151			Ok(v) => v,152			Err(e) => {153				self.cached.borrow_mut()[index] = ArrayThunk::Errored(e.clone());154				return Err(e);155			}156		};157		self.cached.borrow_mut()[index] = ArrayThunk::Computed(new_value.clone());158		Ok(Some(new_value))159	}160	fn get_lazy(&self, index: usize) -> Option<Thunk<Val>> {161		if index >= self.len() {162			return None;163		}164		match &self.cached.borrow()[index] {165			ArrayThunk::Computed(c) => return Some(Thunk::evaluated(c.clone())),166			ArrayThunk::Errored(e) => return Some(Thunk::errored(e.clone())),167			ArrayThunk::Waiting | ArrayThunk::Pending => {}168		};169170		#[derive(Trace)]171		struct ExprArrThunk {172			expr: ExprArray,173			index: usize,174		}175		impl ThunkValue for ExprArrThunk {176			type Output = Val;177178			fn get(&self) -> Result<Self::Output> {179				self.expr180					.get(self.index)181					.transpose()182					.expect("index checked")183			}184		}185186		Some(Thunk::new(ExprArrThunk {187			expr: self.clone(),188			index,189		}))190	}191	fn get_cheap(&self, _index: usize) -> Option<Val> {192		None193	}194	fn is_cheap(&self) -> bool {195		false196	}197}198199#[derive(Trace, Debug)]200pub struct ExtendedArray {201	pub a: ArrValue,202	pub b: ArrValue,203	split: usize,204	len: usize,205}206impl ExtendedArray {207	pub fn new(a: ArrValue, b: ArrValue) -> Self {208		let a_len = a.len();209		let b_len = b.len();210		Self {211			a,212			b,213			split: a_len,214			len: a_len.checked_add(b_len).expect("too large array value"),215		}216	}217}218219struct WithExactSize<I>(I, usize);220impl<I, T> Iterator for WithExactSize<I>221where222	I: Iterator<Item = T>,223{224	type Item = T;225226	fn next(&mut self) -> Option<Self::Item> {227		self.0.next()228	}229	fn nth(&mut self, n: usize) -> Option<Self::Item> {230		self.0.nth(n)231	}232	fn size_hint(&self) -> (usize, Option<usize>) {233		(self.1, Some(self.1))234	}235}236impl<I> DoubleEndedIterator for WithExactSize<I>237where238	I: DoubleEndedIterator,239{240	fn next_back(&mut self) -> Option<Self::Item> {241		self.0.next_back()242	}243	fn nth_back(&mut self, n: usize) -> Option<Self::Item> {244		self.0.nth_back(n)245	}246}247impl<I> ExactSizeIterator for WithExactSize<I>248where249	I: Iterator,250{251	fn len(&self) -> usize {252		self.1253	}254}255impl ArrayLike for ExtendedArray {256	fn get(&self, index: usize) -> Result<Option<Val>> {257		if self.split > index {258			self.a.get(index)259		} else {260			self.b.get(index - self.split)261		}262	}263	fn get_lazy(&self, index: usize) -> Option<Thunk<Val>> {264		if self.split > index {265			self.a.get_lazy(index)266		} else {267			self.b.get_lazy(index - self.split)268		}269	}270271	fn len(&self) -> usize {272		self.len273	}274275	fn get_cheap(&self, index: usize) -> Option<Val> {276		if self.split > index {277			self.a.get_cheap(index)278		} else {279			self.b.get_cheap(index - self.split)280		}281	}282	fn is_cheap(&self) -> bool {283		self.a.is_cheap() && self.b.is_cheap()284	}285}286287#[derive(Trace, Debug)]288pub struct LazyArray(pub Vec<Thunk<Val>>);289impl ArrayLike for LazyArray {290	fn len(&self) -> usize {291		self.0.len()292	}293	fn get(&self, index: usize) -> Result<Option<Val>> {294		let Some(v) = self.0.get(index) else {295			return Ok(None);296		};297		v.evaluate().map(Some)298	}299	fn get_cheap(&self, _index: usize) -> Option<Val> {300		None301	}302	fn get_lazy(&self, index: usize) -> Option<Thunk<Val>> {303		self.0.get(index).cloned()304	}305	fn is_cheap(&self) -> bool {306		false307	}308}309310#[derive(Trace, Debug)]311pub struct EagerArray(pub Vec<Val>);312impl ArrayLike for EagerArray {313	fn len(&self) -> usize {314		self.0.len()315	}316317	fn get(&self, index: usize) -> Result<Option<Val>> {318		Ok(self.0.get(index).cloned())319	}320321	fn get_lazy(&self, index: usize) -> Option<Thunk<Val>> {322		self.0.get(index).cloned().map(Thunk::evaluated)323	}324325	fn get_cheap(&self, index: usize) -> Option<Val> {326		self.0.get(index).cloned()327	}328	fn is_cheap(&self) -> bool {329		true330	}331}332333/// Inclusive range type334#[derive(Debug, Trace, PartialEq, Eq)]335pub struct RangeArray {336	start: i32,337	end: i32,338}339impl RangeArray {340	pub fn empty() -> Self {341		Self::new_exclusive(0, 0)342	}343	pub fn new_exclusive(start: i32, end: i32) -> Self {344		end.checked_sub(1)345			.map_or_else(Self::empty, |end| Self { start, end })346	}347	pub fn new_inclusive(start: i32, end: i32) -> Self {348		Self { start, end }349	}350	fn range(&self) -> impl ExactSizeIterator<Item = i32> + DoubleEndedIterator {351		WithExactSize(352			self.start..=self.end,353			(self.end as usize)354				.wrapping_sub(self.start as usize)355				.wrapping_add(1),356		)357	}358}359360impl ArrayLike for RangeArray {361	fn len(&self) -> usize {362		self.range().len()363	}364	fn is_empty(&self) -> bool {365		self.range().len() == 0366	}367368	fn get(&self, index: usize) -> Result<Option<Val>> {369		Ok(self.get_cheap(index))370	}371372	fn get_lazy(&self, index: usize) -> Option<Thunk<Val>> {373		self.get_cheap(index).map(Thunk::evaluated)374	}375376	fn get_cheap(&self, index: usize) -> Option<Val> {377		self.range().nth(index).map(|i| Val::Num(i.into()))378	}379	fn is_cheap(&self) -> bool {380		true381	}382}383384#[derive(Debug, Trace)]385pub struct ReverseArray(pub ArrValue);386impl ArrayLike for ReverseArray {387	fn len(&self) -> usize {388		self.0.len()389	}390391	fn get(&self, index: usize) -> Result<Option<Val>> {392		self.0.get(self.0.len() - index - 1)393	}394395	fn get_lazy(&self, index: usize) -> Option<Thunk<Val>> {396		self.0.get_lazy(self.0.len() - index - 1)397	}398399	fn get_cheap(&self, index: usize) -> Option<Val> {400		self.0.get_cheap(self.0.len() - index - 1)401	}402	fn is_cheap(&self) -> bool {403		self.0.is_cheap()404	}405}406407#[derive(Trace, Debug, Clone)]408pub struct MappedArray<const WITH_INDEX: bool> {409	inner: ArrValue,410	cached: Cc<RefCell<Vec<ArrayThunk>>>,411	mapper: FuncVal,412}413impl<const WITH_INDEX: bool> MappedArray<WITH_INDEX> {414	pub fn new(inner: ArrValue, mapper: FuncVal) -> Self {415		let len = inner.len();416		Self {417			inner,418			cached: Cc::new(RefCell::new(vec![ArrayThunk::Waiting; len])),419			mapper,420		}421	}422	fn evaluate(&self, index: usize, value: Val) -> Result<Val> {423		if WITH_INDEX {424			self.mapper.evaluate_simple(&(index, value), false)425		} else {426			self.mapper.evaluate_simple(&(value,), false)427		}428	}429}430impl<const WITH_INDEX: bool> ArrayLike for MappedArray<WITH_INDEX> {431	fn len(&self) -> usize {432		self.cached.borrow().len()433	}434435	fn get(&self, index: usize) -> Result<Option<Val>> {436		if index >= self.len() {437			return Ok(None);438		}439		match &self.cached.borrow()[index] {440			ArrayThunk::Computed(c) => return Ok(Some(c.clone())),441			ArrayThunk::Errored(e) => return Err(e.clone()),442			ArrayThunk::Pending => return Err(InfiniteRecursionDetected.into()),443			ArrayThunk::Waiting => {}444		};445446		let ArrayThunk::Waiting =447			replace(&mut self.cached.borrow_mut()[index], ArrayThunk::Pending)448		else {449			unreachable!()450		};451452		let val = self453			.inner454			.get(index)455			.transpose()456			.expect("index checked")457			.and_then(|r| self.evaluate(index, r));458459		let new_value = match val {460			Ok(v) => v,461			Err(e) => {462				self.cached.borrow_mut()[index] = ArrayThunk::Errored(e.clone());463				return Err(e);464			}465		};466		self.cached.borrow_mut()[index] = ArrayThunk::Computed(new_value.clone());467		Ok(Some(new_value))468	}469	fn get_lazy(&self, index: usize) -> Option<Thunk<Val>> {470		if index >= self.len() {471			return None;472		}473		match &self.cached.borrow()[index] {474			ArrayThunk::Computed(c) => return Some(Thunk::evaluated(c.clone())),475			ArrayThunk::Errored(e) => return Some(Thunk::errored(e.clone())),476			ArrayThunk::Waiting | ArrayThunk::Pending => {}477		};478479		#[derive(Trace)]480		struct MappedArrayThunk<const WITH_INDEX: bool> {481			arr: MappedArray<WITH_INDEX>,482			index: usize,483		}484		impl<const WITH_INDEX: bool> ThunkValue for MappedArrayThunk<WITH_INDEX> {485			type Output = Val;486487			fn get(&self) -> Result<Self::Output> {488				self.arr.get(self.index).transpose().expect("index checked")489			}490		}491492		Some(Thunk::new(MappedArrayThunk {493			arr: self.clone(),494			index,495		}))496	}497498	fn get_cheap(&self, _index: usize) -> Option<Val> {499		None500	}501	fn is_cheap(&self) -> bool {502		false503	}504}505506#[derive(Trace, Debug)]507pub struct RepeatedArray {508	data: ArrValue,509	repeats: usize,510	total_len: usize,511}512impl RepeatedArray {513	pub fn new(data: ArrValue, repeats: usize) -> Option<Self> {514		let total_len = data.len().checked_mul(repeats)?;515		Some(Self {516			data,517			repeats,518			total_len,519		})520	}521}522523impl ArrayLike for RepeatedArray {524	fn len(&self) -> usize {525		self.total_len526	}527528	fn get(&self, index: usize) -> Result<Option<Val>> {529		if index > self.total_len {530			return Ok(None);531		}532		self.data.get(index % self.data.len())533	}534535	fn get_lazy(&self, index: usize) -> Option<Thunk<Val>> {536		if index > self.total_len {537			return None;538		}539		self.data.get_lazy(index % self.data.len())540	}541542	fn get_cheap(&self, index: usize) -> Option<Val> {543		if index > self.total_len {544			return None;545		}546		self.data.get_cheap(index % self.data.len())547	}548	fn is_cheap(&self) -> bool {549		self.data.is_cheap()550	}551}552553#[derive(Trace, Debug)]554pub struct PickObjectValues {555	obj: ObjValue,556	keys: Vec<IStr>,557}558559impl PickObjectValues {560	pub fn new(obj: ObjValue, keys: Vec<IStr>) -> Self {561		Self { obj, keys }562	}563}564565impl ArrayLike for PickObjectValues {566	fn len(&self) -> usize {567		self.keys.len()568	}569570	fn get(&self, index: usize) -> Result<Option<Val>> {571		let Some(key) = self.keys.get(index) else {572			return Ok(None);573		};574		Ok(Some(self.obj.get_or_bail(key.clone())?))575	}576577	fn get_lazy(&self, index: usize) -> Option<Thunk<Val>> {578		let key = self.keys.get(index)?;579		Some(self.obj.get_lazy_or_bail(key.clone()))580	}581582	fn get_cheap(&self, _index: usize) -> Option<Val> {583		None584	}585586	fn is_cheap(&self) -> bool {587		false588	}589}590591#[derive(Trace, Debug)]592pub struct PickObjectKeyValues {593	obj: ObjValue,594	keys: Vec<IStr>,595}596597impl PickObjectKeyValues {598	pub fn new(obj: ObjValue, keys: Vec<IStr>) -> Self {599		Self { obj, keys }600	}601}602603#[derive(Typed)]604pub struct KeyValue {605	key: IStr,606	value: Thunk<Val>,607}608609impl ArrayLike for PickObjectKeyValues {610	fn len(&self) -> usize {611		self.keys.len()612	}613614	fn get(&self, index: usize) -> Result<Option<Val>> {615		let Some(key) = self.keys.get(index) else {616			return Ok(None);617		};618		Ok(Some(619			KeyValue::into_untyped(KeyValue {620				key: key.clone(),621				value: Thunk::evaluated(self.obj.get_or_bail(key.clone())?),622			})623			.expect("convertible"),624		))625	}626627	fn get_lazy(&self, index: usize) -> Option<Thunk<Val>> {628		let key = self.keys.get(index)?;629		// Nothing can fail in the key part, yet value is still630		// lazy-evaluated631		Some(Thunk::evaluated(632			KeyValue::into_untyped(KeyValue {633				key: key.clone(),634				value: self.obj.get_lazy_or_bail(key.clone()),635			})636			.expect("convertible"),637		))638	}639640	fn get_cheap(&self, _index: usize) -> Option<Val> {641		None642	}643644	fn is_cheap(&self) -> bool {645		false646	}647}