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

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::typed::NativeFn;10use crate::val::NumValue;11use crate::{12	error::ErrorKind::InfiniteRecursionDetected, evaluate, typed::Typed, val::ThunkValue, Context,13	Error, ObjValue, Result, Thunk, Val,14};1516pub trait ArrayLike: Any + Trace + Debug {17	fn len(&self) -> usize;18	fn is_empty(&self) -> bool {19		self.len() == 020	}21	fn get(&self, index: usize) -> Result<Option<Val>>;22	fn get_lazy(&self, index: usize) -> Option<Thunk<Val>>;23	fn get_cheap(&self, index: usize) -> Option<Val>;2425	fn is_cheap(&self) -> bool;26}2728#[derive(Debug, Trace)]29pub struct SliceArray {30	pub(crate) inner: ArrValue,31	pub(crate) from: u32,32	pub(crate) to: u32,33	pub(crate) step: u32,34}3536impl SliceArray {37	fn map_idx(&self, index: usize) -> usize {38		self.from as usize + self.step as usize * index39	}40}41impl ArrayLike for SliceArray {42	fn len(&self) -> usize {43		(self.to - self.from).div_ceil(self.step) as usize44	}4546	fn get(&self, index: usize) -> Result<Option<Val>> {47		self.inner.get(self.map_idx(index))48	}4950	fn get_lazy(&self, index: usize) -> Option<Thunk<Val>> {51		self.inner.get_lazy(self.map_idx(index))52	}5354	fn get_cheap(&self, index: usize) -> Option<Val> {55		self.inner.get_cheap(self.map_idx(index))56	}57	fn is_cheap(&self) -> bool {58		self.inner.is_cheap()59	}60}6162#[derive(Trace, Debug)]63pub struct CharArray(pub Vec<char>);64impl ArrayLike for CharArray {65	fn len(&self) -> usize {66		self.0.len()67	}6869	fn get(&self, index: usize) -> Result<Option<Val>> {70		Ok(self.get_cheap(index))71	}7273	fn get_lazy(&self, index: usize) -> Option<Thunk<Val>> {74		self.get_cheap(index).map(Thunk::evaluated)75	}7677	fn get_cheap(&self, index: usize) -> Option<Val> {78		self.0.get(index).map(|v| Val::string(*v))79	}80	fn is_cheap(&self) -> bool {81		true82	}83}8485#[derive(Trace, Debug)]86pub struct BytesArray(pub IBytes);87impl ArrayLike for BytesArray {88	fn len(&self) -> usize {89		self.0.len()90	}9192	fn get(&self, index: usize) -> Result<Option<Val>> {93		Ok(self.get_cheap(index))94	}9596	fn get_lazy(&self, index: usize) -> Option<Thunk<Val>> {97		self.get_cheap(index).map(Thunk::evaluated)98	}99100	fn get_cheap(&self, index: usize) -> Option<Val> {101		self.0.get(index).map(|v| Val::Num((*v).into()))102	}103	fn is_cheap(&self) -> bool {104		true105	}106}107108#[derive(Debug, Trace, Clone)]109enum ArrayThunk {110	Computed(Val),111	Errored(Error),112	Waiting,113	Pending,114}115116#[derive(Debug, Trace, Clone)]117pub struct ExprArray {118	ctx: Context,119	src: Rc<Vec<Spanned<Expr>>>,120	cached: Cc<RefCell<Vec<ArrayThunk>>>,121}122impl ExprArray {123	pub fn new(ctx: Context, src: Rc<Vec<Spanned<Expr>>>) -> Self {124		Self {125			ctx,126			cached: Cc::new(RefCell::new(vec![ArrayThunk::Waiting; src.len()])),127			src,128		}129	}130}131impl ArrayLike for ExprArray {132	fn len(&self) -> usize {133		self.cached.borrow().len()134	}135	fn get(&self, index: usize) -> Result<Option<Val>> {136		if index >= self.len() {137			return Ok(None);138		}139		match &self.cached.borrow()[index] {140			ArrayThunk::Computed(c) => return Ok(Some(c.clone())),141			ArrayThunk::Errored(e) => return Err(e.clone()),142			ArrayThunk::Pending => return Err(InfiniteRecursionDetected.into()),143			ArrayThunk::Waiting => {}144		}145146		let ArrayThunk::Waiting =147			replace(&mut self.cached.borrow_mut()[index], ArrayThunk::Pending)148		else {149			unreachable!()150		};151152		let new_value = match evaluate(self.ctx.clone(), &self.src[index]) {153			Ok(v) => v,154			Err(e) => {155				self.cached.borrow_mut()[index] = ArrayThunk::Errored(e.clone());156				return Err(e);157			}158		};159		self.cached.borrow_mut()[index] = ArrayThunk::Computed(new_value.clone());160		Ok(Some(new_value))161	}162	fn get_lazy(&self, index: usize) -> Option<Thunk<Val>> {163		#[derive(Trace)]164		struct ExprArrThunk {165			expr: ExprArray,166			index: usize,167		}168		impl ThunkValue for ExprArrThunk {169			type Output = Val;170171			fn get(&self) -> Result<Self::Output> {172				self.expr173					.get(self.index)174					.transpose()175					.expect("index checked")176			}177		}178179		if index >= self.len() {180			return None;181		}182		match &self.cached.borrow()[index] {183			ArrayThunk::Computed(c) => return Some(Thunk::evaluated(c.clone())),184			ArrayThunk::Errored(e) => return Some(Thunk::errored(e.clone())),185			ArrayThunk::Waiting | ArrayThunk::Pending => {}186		}187188		Some(Thunk::new(ExprArrThunk {189			expr: self.clone(),190			index,191		}))192	}193	fn get_cheap(&self, _index: usize) -> Option<Val> {194		None195	}196	fn is_cheap(&self) -> bool {197		false198	}199}200201#[derive(Trace, Debug)]202pub struct ExtendedArray {203	pub a: ArrValue,204	pub b: ArrValue,205	split: usize,206	len: usize,207}208impl ExtendedArray {209	pub fn new(a: ArrValue, b: ArrValue) -> Self {210		let a_len = a.len();211		let b_len = b.len();212		Self {213			a,214			b,215			split: a_len,216			len: a_len.checked_add(b_len).expect("too large array value"),217		}218	}219}220221struct WithExactSize<I>(I, usize);222impl<I, T> Iterator for WithExactSize<I>223where224	I: Iterator<Item = T>,225{226	type Item = T;227228	fn next(&mut self) -> Option<Self::Item> {229		self.0.next()230	}231	fn nth(&mut self, n: usize) -> Option<Self::Item> {232		self.0.nth(n)233	}234	fn size_hint(&self) -> (usize, Option<usize>) {235		(self.1, Some(self.1))236	}237}238impl<I> DoubleEndedIterator for WithExactSize<I>239where240	I: DoubleEndedIterator,241{242	fn next_back(&mut self) -> Option<Self::Item> {243		self.0.next_back()244	}245	fn nth_back(&mut self, n: usize) -> Option<Self::Item> {246		self.0.nth_back(n)247	}248}249impl<I> ExactSizeIterator for WithExactSize<I>250where251	I: Iterator,252{253	fn len(&self) -> usize {254		self.1255	}256}257impl ArrayLike for ExtendedArray {258	fn get(&self, index: usize) -> Result<Option<Val>> {259		if self.split > index {260			self.a.get(index)261		} else {262			self.b.get(index - self.split)263		}264	}265	fn get_lazy(&self, index: usize) -> Option<Thunk<Val>> {266		if self.split > index {267			self.a.get_lazy(index)268		} else {269			self.b.get_lazy(index - self.split)270		}271	}272273	fn len(&self) -> usize {274		self.len275	}276277	fn get_cheap(&self, index: usize) -> Option<Val> {278		if self.split > index {279			self.a.get_cheap(index)280		} else {281			self.b.get_cheap(index - self.split)282		}283	}284	fn is_cheap(&self) -> bool {285		self.a.is_cheap() && self.b.is_cheap()286	}287}288289#[derive(Trace, Debug)]290pub struct LazyArray(pub Vec<Thunk<Val>>);291impl ArrayLike for LazyArray {292	fn len(&self) -> usize {293		self.0.len()294	}295	fn get(&self, index: usize) -> Result<Option<Val>> {296		let Some(v) = self.0.get(index) else {297			return Ok(None);298		};299		v.evaluate().map(Some)300	}301	fn get_cheap(&self, _index: usize) -> Option<Val> {302		None303	}304	fn get_lazy(&self, index: usize) -> Option<Thunk<Val>> {305		self.0.get(index).cloned()306	}307	fn is_cheap(&self) -> bool {308		false309	}310}311312#[derive(Trace, Debug)]313pub struct EagerArray(pub Vec<Val>);314impl ArrayLike for EagerArray {315	fn len(&self) -> usize {316		self.0.len()317	}318319	fn get(&self, index: usize) -> Result<Option<Val>> {320		Ok(self.0.get(index).cloned())321	}322323	fn get_lazy(&self, index: usize) -> Option<Thunk<Val>> {324		self.0.get(index).cloned().map(Thunk::evaluated)325	}326327	fn get_cheap(&self, index: usize) -> Option<Val> {328		self.0.get(index).cloned()329	}330	fn is_cheap(&self) -> bool {331		true332	}333}334335/// Inclusive range type336#[derive(Debug, Trace, PartialEq, Eq)]337pub struct RangeArray {338	start: i32,339	end: i32,340}341impl RangeArray {342	pub fn empty() -> Self {343		Self::new_exclusive(0, 0)344	}345	pub fn new_exclusive(start: i32, end: i32) -> Self {346		end.checked_sub(1)347			.map_or_else(Self::empty, |end| Self { start, end })348	}349	pub fn new_inclusive(start: i32, end: i32) -> Self {350		Self { start, end }351	}352	fn range(&self) -> impl ExactSizeIterator<Item = i32> + DoubleEndedIterator {353		WithExactSize(354			self.start..=self.end,355			(self.end as usize)356				.wrapping_sub(self.start as usize)357				.wrapping_add(1),358		)359	}360}361362impl ArrayLike for RangeArray {363	fn len(&self) -> usize {364		self.range().len()365	}366	fn is_empty(&self) -> bool {367		self.range().len() == 0368	}369370	fn get(&self, index: usize) -> Result<Option<Val>> {371		Ok(self.get_cheap(index))372	}373374	fn get_lazy(&self, index: usize) -> Option<Thunk<Val>> {375		self.get_cheap(index).map(Thunk::evaluated)376	}377378	fn get_cheap(&self, index: usize) -> Option<Val> {379		self.range().nth(index).map(|i| Val::Num(i.into()))380	}381	fn is_cheap(&self) -> bool {382		true383	}384}385386#[derive(Debug, Trace)]387pub struct ReverseArray(pub ArrValue);388impl ArrayLike for ReverseArray {389	fn len(&self) -> usize {390		self.0.len()391	}392393	fn get(&self, index: usize) -> Result<Option<Val>> {394		self.0.get(self.0.len() - index - 1)395	}396397	fn get_lazy(&self, index: usize) -> Option<Thunk<Val>> {398		self.0.get_lazy(self.0.len() - index - 1)399	}400401	fn get_cheap(&self, index: usize) -> Option<Val> {402		self.0.get_cheap(self.0.len() - index - 1)403	}404	fn is_cheap(&self) -> bool {405		self.0.is_cheap()406	}407}408409#[derive(Trace, Clone, Debug)]410pub enum ArrayMapper {411	Plain(NativeFn!((Val) -> Val)),412	WithIndex(NativeFn!((u32, Val) -> Val)),413}414415#[derive(Trace, Debug, Clone)]416pub struct MappedArray {417	inner: ArrValue,418	cached: Cc<RefCell<Vec<ArrayThunk>>>,419	mapper: ArrayMapper,420}421impl MappedArray {422	pub fn new(inner: ArrValue, mapper: ArrayMapper) -> Self {423		let len = inner.len();424		Self {425			inner,426			cached: Cc::new(RefCell::new(vec![ArrayThunk::Waiting; len])),427			mapper,428		}429	}430	fn evaluate(&self, index: usize, value: Val) -> Result<Val> {431		match &self.mapper {432			ArrayMapper::Plain(f) => f.call(value),433			ArrayMapper::WithIndex(f) => f.call(index as u32, value),434		}435	}436}437impl ArrayLike for MappedArray {438	fn len(&self) -> usize {439		self.cached.borrow().len()440	}441442	fn get(&self, index: usize) -> Result<Option<Val>> {443		if index >= self.len() {444			return Ok(None);445		}446		match &self.cached.borrow()[index] {447			ArrayThunk::Computed(c) => return Ok(Some(c.clone())),448			ArrayThunk::Errored(e) => return Err(e.clone()),449			ArrayThunk::Pending => return Err(InfiniteRecursionDetected.into()),450			ArrayThunk::Waiting => {}451		}452453		let ArrayThunk::Waiting =454			replace(&mut self.cached.borrow_mut()[index], ArrayThunk::Pending)455		else {456			unreachable!()457		};458459		let val = self460			.inner461			.get(index)462			.transpose()463			.expect("index checked")464			.and_then(|r| self.evaluate(index, r));465466		let new_value = match val {467			Ok(v) => v,468			Err(e) => {469				self.cached.borrow_mut()[index] = ArrayThunk::Errored(e.clone());470				return Err(e);471			}472		};473		self.cached.borrow_mut()[index] = ArrayThunk::Computed(new_value.clone());474		Ok(Some(new_value))475	}476	fn get_lazy(&self, index: usize) -> Option<Thunk<Val>> {477		#[derive(Trace)]478		struct MappedArrayThunk {479			arr: MappedArray,480			index: usize,481		}482		impl ThunkValue for MappedArrayThunk {483			type Output = Val;484485			fn get(&self) -> Result<Self::Output> {486				self.arr.get(self.index).transpose().expect("index checked")487			}488		}489490		if index >= self.len() {491			return None;492		}493		match &self.cached.borrow()[index] {494			ArrayThunk::Computed(c) => return Some(Thunk::evaluated(c.clone())),495			ArrayThunk::Errored(e) => return Some(Thunk::errored(e.clone())),496			ArrayThunk::Waiting | ArrayThunk::Pending => {}497		}498499		Some(Thunk::new(MappedArrayThunk {500			arr: self.clone(),501			index,502		}))503	}504505	fn get_cheap(&self, _index: usize) -> Option<Val> {506		None507	}508	fn is_cheap(&self) -> bool {509		false510	}511}512513#[derive(Trace, Debug)]514pub struct RepeatedArray {515	data: ArrValue,516	repeats: usize,517	total_len: usize,518}519impl RepeatedArray {520	pub fn new(data: ArrValue, repeats: usize) -> Option<Self> {521		let total_len = data.len().checked_mul(repeats)?;522		Some(Self {523			data,524			repeats,525			total_len,526		})527	}528}529530impl ArrayLike for RepeatedArray {531	fn len(&self) -> usize {532		self.total_len533	}534535	fn get(&self, index: usize) -> Result<Option<Val>> {536		if index > self.total_len {537			return Ok(None);538		}539		self.data.get(index % self.data.len())540	}541542	fn get_lazy(&self, index: usize) -> Option<Thunk<Val>> {543		if index > self.total_len {544			return None;545		}546		self.data.get_lazy(index % self.data.len())547	}548549	fn get_cheap(&self, index: usize) -> Option<Val> {550		if index > self.total_len {551			return None;552		}553		self.data.get_cheap(index % self.data.len())554	}555	fn is_cheap(&self) -> bool {556		self.data.is_cheap()557	}558}559560#[derive(Trace, Debug)]561pub struct PickObjectValues {562	obj: ObjValue,563	keys: Vec<IStr>,564}565566impl PickObjectValues {567	pub fn new(obj: ObjValue, keys: Vec<IStr>) -> Self {568		Self { obj, keys }569	}570}571572impl ArrayLike for PickObjectValues {573	fn len(&self) -> usize {574		self.keys.len()575	}576577	fn get(&self, index: usize) -> Result<Option<Val>> {578		let Some(key) = self.keys.get(index) else {579			return Ok(None);580		};581		Ok(Some(self.obj.get_or_bail(key.clone())?))582	}583584	fn get_lazy(&self, index: usize) -> Option<Thunk<Val>> {585		let key = self.keys.get(index)?;586		Some(self.obj.get_lazy_or_bail(key.clone()))587	}588589	fn get_cheap(&self, _index: usize) -> Option<Val> {590		None591	}592593	fn is_cheap(&self) -> bool {594		false595	}596}597598#[derive(Trace, Debug)]599pub struct PickObjectKeyValues {600	obj: ObjValue,601	keys: Vec<IStr>,602}603604impl PickObjectKeyValues {605	pub fn new(obj: ObjValue, keys: Vec<IStr>) -> Self {606		Self { obj, keys }607	}608}609610#[derive(Typed)]611pub struct KeyValue {612	key: IStr,613	value: Thunk<Val>,614}615616impl ArrayLike for PickObjectKeyValues {617	fn len(&self) -> usize {618		self.keys.len()619	}620621	fn get(&self, index: usize) -> Result<Option<Val>> {622		let Some(key) = self.keys.get(index) else {623			return Ok(None);624		};625		Ok(Some(626			KeyValue::into_untyped(KeyValue {627				key: key.clone(),628				value: Thunk::evaluated(self.obj.get_or_bail(key.clone())?),629			})630			.expect("convertible"),631		))632	}633634	fn get_lazy(&self, index: usize) -> Option<Thunk<Val>> {635		let key = self.keys.get(index)?;636		// Nothing can fail in the key part, yet value is still637		// lazy-evaluated638		Some(Thunk::evaluated(639			KeyValue::into_untyped(KeyValue {640				key: key.clone(),641				value: self.obj.get_lazy_or_bail(key.clone()),642			})643			.expect("convertible"),644		))645	}646647	fn get_cheap(&self, _index: usize) -> Option<Val> {648		None649	}650651	fn is_cheap(&self) -> bool {652		false653	}654}