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

difftreelog

source

crates/jrsonnet-evaluator/src/val.rs16.8 KiBsourcehistory
1use std::{cell::RefCell, fmt::Debug};23use jrsonnet_gcmodule::{Cc, Trace};4use jrsonnet_interner::{IBytes, IStr};5use jrsonnet_types::ValType;67use crate::{8	error::{Error, ErrorKind::*},9	function::FuncVal,10	gc::{GcHashMap, TraceBox},11	manifest::{ManifestFormat, ToStringFormat},12	throw,13	typed::BoundedUsize,14	ObjValue, Result, Unbound, WeakObjValue,15};1617pub trait ThunkValue: Trace {18	type Output;19	fn get(self: Box<Self>) -> Result<Self::Output>;20}2122#[derive(Trace)]23enum ThunkInner<T: Trace> {24	Computed(T),25	Errored(Error),26	Waiting(TraceBox<dyn ThunkValue<Output = T>>),27	Pending,28}2930#[allow(clippy::module_name_repetitions)]31#[derive(Clone, Trace)]32pub struct Thunk<T: Trace>(Cc<RefCell<ThunkInner<T>>>);3334impl<T> Thunk<T>35where36	T: Clone + Trace,37{38	pub fn new(f: TraceBox<dyn ThunkValue<Output = T>>) -> Self {39		Self(Cc::new(RefCell::new(ThunkInner::Waiting(f))))40	}41	pub fn evaluated(val: T) -> Self {42		Self(Cc::new(RefCell::new(ThunkInner::Computed(val))))43	}44	pub fn force(&self) -> Result<()> {45		self.evaluate()?;46		Ok(())47	}48	pub fn evaluate(&self) -> Result<T> {49		match &*self.0.borrow() {50			ThunkInner::Computed(v) => return Ok(v.clone()),51			ThunkInner::Errored(e) => return Err(e.clone()),52			ThunkInner::Pending => return Err(InfiniteRecursionDetected.into()),53			ThunkInner::Waiting(..) => (),54		};55		let ThunkInner::Waiting(value) = std::mem::replace(&mut *self.0.borrow_mut(), ThunkInner::Pending) else {56			unreachable!();57		};58		let new_value = match value.0.get() {59			Ok(v) => v,60			Err(e) => {61				*self.0.borrow_mut() = ThunkInner::Errored(e.clone());62				return Err(e);63			}64		};65		*self.0.borrow_mut() = ThunkInner::Computed(new_value.clone());66		Ok(new_value)67	}68}6970type CacheKey = (Option<WeakObjValue>, Option<WeakObjValue>);7172#[derive(Trace, Clone)]73pub struct CachedUnbound<I, T>74where75	I: Unbound<Bound = T>,76	T: Trace,77{78	cache: Cc<RefCell<GcHashMap<CacheKey, T>>>,79	value: I,80}81impl<I: Unbound<Bound = T>, T: Trace> CachedUnbound<I, T> {82	pub fn new(value: I) -> Self {83		Self {84			cache: Cc::new(RefCell::new(GcHashMap::new())),85			value,86		}87	}88}89impl<I: Unbound<Bound = T>, T: Clone + Trace> Unbound for CachedUnbound<I, T> {90	type Bound = T;91	fn bind(&self, sup: Option<ObjValue>, this: Option<ObjValue>) -> Result<T> {92		let cache_key = (93			sup.as_ref().map(|s| s.clone().downgrade()),94			this.as_ref().map(|t| t.clone().downgrade()),95		);96		{97			if let Some(t) = self.cache.borrow().get(&cache_key) {98				return Ok(t.clone());99			}100		}101		let bound = self.value.bind(sup, this)?;102103		{104			let mut cache = self.cache.borrow_mut();105			cache.insert(cache_key, bound.clone());106		}107108		Ok(bound)109	}110}111112impl<T: Debug + Trace> Debug for Thunk<T> {113	fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {114		write!(f, "Lazy")115	}116}117impl<T: Trace> PartialEq for Thunk<T> {118	fn eq(&self, other: &Self) -> bool {119		Cc::ptr_eq(&self.0, &other.0)120	}121}122123#[derive(Debug, Clone, Trace)]124pub struct Slice {125	pub(crate) inner: ArrValue,126	pub(crate) from: u32,127	pub(crate) to: u32,128	pub(crate) step: u32,129}130impl Slice {131	const fn from(&self) -> usize {132		self.from as usize133	}134	const fn to(&self) -> usize {135		self.to as usize136	}137	const fn step(&self) -> usize {138		self.step as usize139	}140	const fn len(&self) -> usize {141		// TODO: use div_ceil142		let diff = self.to() - self.from();143		let rem = diff % self.step();144		let div = diff / self.step();145146		if rem == 0 {147			div148		} else {149			div + 1150		}151	}152}153154/// Represents a Jsonnet array value.155#[derive(Debug, Clone, Trace)]156// may contrain other ArrValue157#[trace(tracking(force))]158pub enum ArrValue {159	/// Layout optimized byte array.160	Bytes(#[trace(skip)] IBytes),161	/// Every element is lazy evaluated.162	Lazy(Cc<Vec<Thunk<Val>>>),163	/// Every field is already evaluated.164	Eager(Cc<Vec<Val>>),165	/// Concatenation of two arrays of any kind.166	Extended(Box<(Self, Self)>),167	/// Represents a integer array in form `[start, start + 1, ... end - 1, end]`.168	/// This kind of arrays is generated by `std.range(start, end)` call, and used for loops.169	Range(i32, i32),170	/// Sliced array view.171	Slice(Box<Slice>),172	/// Reversed array view.173	/// Returned by `std.reverse(other)` call174	Reversed(Box<Self>),175}176177#[cfg(target_pointer_width = "64")]178static_assertions::assert_eq_size!(ArrValue, [u8; 16]);179180impl ArrValue {181	pub fn new_eager() -> Self {182		Self::Eager(Cc::new(Vec::new()))183	}184	pub fn empty() -> Self {185		Self::new_range(0, 0)186	}187188	/// # Panics189	/// If a > b190	#[inline]191	pub fn new_range(a: i32, b: i32) -> Self {192		assert!(a <= b);193		Self::Range(a, b)194	}195196	/// # Panics197	/// If passed numbers are incorrect198	#[must_use]199	pub fn slice(self, from: Option<usize>, to: Option<usize>, step: Option<usize>) -> Self {200		let len = self.len();201		let from = from.unwrap_or(0);202		let to = to.unwrap_or(len).min(len);203		let step = step.unwrap_or(1);204		assert!(from < to);205		assert!(step > 0);206207		Self::Slice(Box::new(Slice {208			inner: self,209			from: from as u32,210			to: to as u32,211			step: step as u32,212		}))213	}214215	/// Array length.216	pub fn len(&self) -> usize {217		match self {218			Self::Bytes(i) => i.len(),219			Self::Lazy(l) => l.len(),220			Self::Eager(e) => e.len(),221			Self::Extended(v) => v.0.len() + v.1.len(),222			Self::Range(a, b) => a.abs_diff(*b) as usize + 1,223			Self::Reversed(i) => i.len(),224			Self::Slice(s) => s.len(),225		}226	}227228	/// Is array contains no elements?229	pub fn is_empty(&self) -> bool {230		self.len() == 0231	}232233	/// Get array element by index, evaluating it, if it is lazy.234	///235	/// Returns `None` on out-of-bounds condition.236	pub fn get(&self, index: usize) -> Result<Option<Val>> {237		match self {238			Self::Bytes(i) => i239				.get(index)240				.map_or(Ok(None), |v| Ok(Some(Val::Num(f64::from(*v))))),241			Self::Lazy(vec) => {242				if let Some(v) = vec.get(index) {243					Ok(Some(v.evaluate()?))244				} else {245					Ok(None)246				}247			}248			Self::Eager(vec) => Ok(vec.get(index).cloned()),249			Self::Extended(v) => {250				let a_len = v.0.len();251				if a_len > index {252					v.0.get(index)253				} else {254					v.1.get(index - a_len)255				}256			}257			Self::Range(a, _) => {258				if index >= self.len() {259					return Ok(None);260				}261				Ok(Some(Val::Num(((*a as isize) + index as isize) as f64)))262			}263			Self::Reversed(v) => {264				let len = v.len();265				if index >= len {266					return Ok(None);267				}268				v.get(len - index - 1)269			}270			Self::Slice(v) => {271				let index = v.from() + index * v.step();272				if index >= v.to() {273					return Ok(None);274				}275				v.inner.get(index)276			}277		}278	}279280	/// Get array element by index, without evaluation.281	///282	/// Returns `None` on out-of-bounds condition.283	pub fn get_lazy(&self, index: usize) -> Option<Thunk<Val>> {284		match self {285			Self::Bytes(i) => i286				.get(index)287				.map(|b| Thunk::evaluated(Val::Num(f64::from(*b)))),288			Self::Lazy(vec) => vec.get(index).cloned(),289			Self::Eager(vec) => vec.get(index).cloned().map(Thunk::evaluated),290			Self::Extended(v) => {291				let a_len = v.0.len();292				if a_len > index {293					v.0.get_lazy(index)294				} else {295					v.1.get_lazy(index - a_len)296				}297			}298			Self::Range(a, _) => {299				if index >= self.len() {300					return None;301				}302				Some(Thunk::evaluated(Val::Num(303					((*a as isize) + index as isize) as f64,304				)))305			}306			Self::Reversed(v) => {307				let len = v.len();308				if index >= len {309					return None;310				}311				v.get_lazy(len - index - 1)312			}313			Self::Slice(s) => {314				let index = s.from() + index * s.step();315				if index >= s.to() {316					return None;317				}318				s.inner.get_lazy(index)319			}320		}321	}322323	/// Evaluate all array elements, returning new array.324	pub fn evaluated(&self) -> Result<Cc<Vec<Val>>> {325		Ok(match self {326			Self::Bytes(i) => {327				let mut out = Vec::with_capacity(i.len());328				for v in i.iter() {329					out.push(Val::Num(f64::from(*v)));330				}331				Cc::new(out)332			}333			Self::Lazy(vec) => {334				let mut out = Vec::with_capacity(vec.len());335				for item in vec.iter() {336					out.push(item.evaluate()?);337				}338				Cc::new(out)339			}340			Self::Eager(vec) => vec.clone(),341			Self::Extended(_v) => {342				let mut out = Vec::with_capacity(self.len());343				for item in self.iter() {344					out.push(item?);345				}346				Cc::new(out)347			}348			Self::Range(a, b) => {349				let mut out = Vec::with_capacity(self.len());350				for i in *a..=*b {351					out.push(Val::Num(f64::from(i)));352				}353				Cc::new(out)354			}355			Self::Reversed(r) => {356				let mut r = r.evaluated()?;357				Cc::update_with(&mut r, |v| v.reverse());358				r359			}360			Self::Slice(v) => {361				let mut out = Vec::with_capacity(v.inner.len());362				for v in v363					.inner364					.iter_lazy()365					.skip(v.from())366					.take(v.to() - v.from())367					.step_by(v.step())368				{369					out.push(v.evaluate()?);370				}371				Cc::new(out)372			}373		})374	}375376	/// Iterate over elements, evaluating them.377	pub fn iter(&self) -> impl DoubleEndedIterator<Item = Result<Val>> + '_ {378		(0..self.len()).map(move |idx| match self {379			Self::Bytes(b) => Ok(Val::Num(f64::from(b[idx]))),380			Self::Lazy(l) => l[idx].evaluate(),381			Self::Eager(e) => Ok(e[idx].clone()),382			Self::Extended(..) | Self::Range(..) | Self::Reversed(..) | Self::Slice(..) => {383				self.get(idx).map(|e| e.expect("idx < len"))384			}385		})386	}387388	/// Iterate over elements, returning lazy values.389	pub fn iter_lazy(&self) -> impl DoubleEndedIterator<Item = Thunk<Val>> + '_ {390		(0..self.len()).map(move |idx| match self {391			Self::Bytes(b) => Thunk::evaluated(Val::Num(f64::from(b[idx]))),392			Self::Lazy(l) => l[idx].clone(),393			Self::Eager(e) => Thunk::evaluated(e[idx].clone()),394			Self::Slice(..) | Self::Extended(..) | Self::Range(..) | Self::Reversed(..) => {395				self.get_lazy(idx).expect("idx < len")396			}397		})398	}399400	/// Return a reversed view on current array.401	#[must_use]402	pub fn reversed(self) -> Self {403		Self::Reversed(Box::new(self))404	}405406	/// Return a new array, produced by passing every element of current array to specified callback function.407	pub fn map(self, mapper: impl Fn(Val) -> Result<Val>) -> Result<Self> {408		let mut out = Vec::with_capacity(self.len());409410		for value in self.iter() {411			out.push(mapper(value?)?);412		}413414		Ok(Self::Eager(Cc::new(out)))415	}416417	/// Return a new array, produced from current array by removing every value, for which specified callback function returns false.418	pub fn filter(self, filter: impl Fn(&Val) -> Result<bool>) -> Result<Self> {419		let mut out = Vec::with_capacity(self.len());420421		for value in self.iter() {422			let value = value?;423			if filter(&value)? {424				out.push(value);425			}426		}427428		Ok(Self::Eager(Cc::new(out)))429	}430431	pub fn ptr_eq(a: &Self, b: &Self) -> bool {432		match (a, b) {433			(Self::Lazy(a), Self::Lazy(b)) => Cc::ptr_eq(a, b),434			(Self::Eager(a), Self::Eager(b)) => Cc::ptr_eq(a, b),435			_ => false,436		}437	}438}439440impl From<Vec<Thunk<Val>>> for ArrValue {441	fn from(v: Vec<Thunk<Val>>) -> Self {442		Self::Lazy(Cc::new(v))443	}444}445446impl From<Vec<Val>> for ArrValue {447	fn from(v: Vec<Val>) -> Self {448		Self::Eager(Cc::new(v))449	}450}451452/// Represents a Jsonnet value, which can be spliced or indexed (string or array).453#[allow(clippy::module_name_repetitions)]454pub enum IndexableVal {455	/// String.456	Str(IStr),457	/// Array.458	Arr(ArrValue),459}460impl IndexableVal {461	/// Slice the value.462	///463	/// # Implementation464	///465	/// For strings, will create a copy of specified interval.466	///467	/// For arrays, nothing will be copied on this call, instead [`ArrValue::Slice`] view will be returned.468	pub fn slice(469		self,470		index: Option<BoundedUsize<0, { i32::MAX as usize }>>,471		end: Option<BoundedUsize<0, { i32::MAX as usize }>>,472		step: Option<BoundedUsize<1, { i32::MAX as usize }>>,473	) -> Result<Self> {474		match &self {475			IndexableVal::Str(s) => {476				let index = index.as_deref().copied().unwrap_or(0);477				let end = end.as_deref().copied().unwrap_or(usize::MAX);478				let step = step.as_deref().copied().unwrap_or(1);479480				if index >= end {481					return Ok(Self::Str("".into()));482				}483484				Ok(Self::Str(485					(s.chars()486						.skip(index)487						.take(end - index)488						.step_by(step)489						.collect::<String>())490					.into(),491				))492			}493			IndexableVal::Arr(arr) => {494				let index = index.as_deref().copied().unwrap_or(0);495				let end = end.as_deref().copied().unwrap_or(usize::MAX).min(arr.len());496				let step = step.as_deref().copied().unwrap_or(1);497498				if index >= end {499					return Ok(Self::Arr(ArrValue::new_eager()));500				}501502				Ok(Self::Arr(ArrValue::Slice(Box::new(Slice {503					inner: arr.clone(),504					from: index as u32,505					to: end as u32,506					step: step as u32,507				}))))508			}509		}510	}511}512513/// Represents any valid Jsonnet value.514#[derive(Debug, Clone, Trace)]515pub enum Val {516	/// Represents a Jsonnet boolean.517	Bool(bool),518	/// Represents a Jsonnet null value.519	Null,520	/// Represents a Jsonnet string.521	Str(IStr),522	/// Represents a Jsonnet number.523	/// Should be finite, and not NaN524	/// This restriction isn't enforced by enum, as enum field can't be marked as private525	Num(f64),526	/// Represents a Jsonnet array.527	Arr(ArrValue),528	/// Represents a Jsonnet object.529	Obj(ObjValue),530	/// Represents a Jsonnet function.531	Func(FuncVal),532}533534impl From<IndexableVal> for Val {535	fn from(v: IndexableVal) -> Self {536		match v {537			IndexableVal::Str(s) => Self::Str(s),538			IndexableVal::Arr(a) => Self::Arr(a),539		}540	}541}542543// Broken between stable and nightly, as there is new layout size optimization544// #[cfg(target_pointer_width = "64")]545// static_assertions::assert_eq_size!(Val, [u8; 24]);546547impl Val {548	pub const fn as_bool(&self) -> Option<bool> {549		match self {550			Self::Bool(v) => Some(*v),551			_ => None,552		}553	}554	pub const fn as_null(&self) -> Option<()> {555		match self {556			Self::Null => Some(()),557			_ => None,558		}559	}560	pub fn as_str(&self) -> Option<IStr> {561		match self {562			Self::Str(s) => Some(s.clone()),563			_ => None,564		}565	}566	pub const fn as_num(&self) -> Option<f64> {567		match self {568			Self::Num(n) => Some(*n),569			_ => None,570		}571	}572	pub fn as_arr(&self) -> Option<ArrValue> {573		match self {574			Self::Arr(a) => Some(a.clone()),575			_ => None,576		}577	}578	pub fn as_obj(&self) -> Option<ObjValue> {579		match self {580			Self::Obj(o) => Some(o.clone()),581			_ => None,582		}583	}584	pub fn as_func(&self) -> Option<FuncVal> {585		match self {586			Self::Func(f) => Some(f.clone()),587			_ => None,588		}589	}590591	/// Creates `Val::Num` after checking for numeric overflow.592	/// As numbers are `f64`, we can just check for their finity.593	pub fn new_checked_num(num: f64) -> Result<Self> {594		if num.is_finite() {595			Ok(Self::Num(num))596		} else {597			throw!("overflow")598		}599	}600601	pub const fn value_type(&self) -> ValType {602		match self {603			Self::Str(..) => ValType::Str,604			Self::Num(..) => ValType::Num,605			Self::Arr(..) => ValType::Arr,606			Self::Obj(..) => ValType::Obj,607			Self::Bool(_) => ValType::Bool,608			Self::Null => ValType::Null,609			Self::Func(..) => ValType::Func,610		}611	}612613	pub fn manifest(&self, format: impl ManifestFormat) -> Result<String> {614		fn manifest_dyn(val: &Val, manifest: &dyn ManifestFormat) -> Result<String> {615			manifest.manifest(val.clone())616		}617		manifest_dyn(self, &format)618	}619620	pub fn to_string(&self) -> Result<IStr> {621		Ok(match self {622			Self::Bool(true) => "true".into(),623			Self::Bool(false) => "false".into(),624			Self::Null => "null".into(),625			Self::Str(s) => s.clone(),626			_ => self.manifest(ToStringFormat).map(IStr::from)?,627		})628	}629630	pub fn into_indexable(self) -> Result<IndexableVal> {631		Ok(match self {632			Val::Str(s) => IndexableVal::Str(s),633			Val::Arr(arr) => IndexableVal::Arr(arr),634			_ => throw!(ValueIsNotIndexable(self.value_type())),635		})636	}637}638639const fn is_function_like(val: &Val) -> bool {640	matches!(val, Val::Func(_))641}642643/// Native implementation of `std.primitiveEquals`644pub fn primitive_equals(val_a: &Val, val_b: &Val) -> Result<bool> {645	Ok(match (val_a, val_b) {646		(Val::Bool(a), Val::Bool(b)) => a == b,647		(Val::Null, Val::Null) => true,648		(Val::Str(a), Val::Str(b)) => a == b,649		(Val::Num(a), Val::Num(b)) => (a - b).abs() <= f64::EPSILON,650		(Val::Arr(_), Val::Arr(_)) => {651			throw!("primitiveEquals operates on primitive types, got array")652		}653		(Val::Obj(_), Val::Obj(_)) => {654			throw!("primitiveEquals operates on primitive types, got object")655		}656		(a, b) if is_function_like(a) && is_function_like(b) => {657			throw!("cannot test equality of functions")658		}659		(_, _) => false,660	})661}662663/// Native implementation of `std.equals`664pub fn equals(val_a: &Val, val_b: &Val) -> Result<bool> {665	if val_a.value_type() != val_b.value_type() {666		return Ok(false);667	}668	match (val_a, val_b) {669		(Val::Arr(a), Val::Arr(b)) => {670			if ArrValue::ptr_eq(a, b) {671				return Ok(true);672			}673			if a.len() != b.len() {674				return Ok(false);675			}676			for (a, b) in a.iter().zip(b.iter()) {677				if !equals(&a?, &b?)? {678					return Ok(false);679				}680			}681			Ok(true)682		}683		(Val::Obj(a), Val::Obj(b)) => {684			if ObjValue::ptr_eq(a, b) {685				return Ok(true);686			}687			let fields = a.fields(688				#[cfg(feature = "exp-preserve-order")]689				false,690			);691			if fields692				!= b.fields(693					#[cfg(feature = "exp-preserve-order")]694					false,695				) {696				return Ok(false);697			}698			for field in fields {699				if !equals(700					&a.get(field.clone())?.expect("field exists"),701					&b.get(field)?.expect("field exists"),702				)? {703					return Ok(false);704				}705			}706			Ok(true)707		}708		(a, b) => Ok(primitive_equals(a, b)?),709	}710}