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

difftreelog

source

crates/jrsonnet-evaluator/src/val.rs17.4 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::*, LocError},9	function::FuncVal,10	gc::{GcHashMap, TraceBox},11	throw,12	typed::BoundedUsize,13	ObjValue, Result, Unbound, WeakObjValue,14};1516pub trait ThunkValue: Trace {17	type Output;18	fn get(self: Box<Self>) -> Result<Self::Output>;19}2021#[derive(Trace)]22enum ThunkInner<T: Trace> {23	Computed(T),24	Errored(LocError),25	Waiting(TraceBox<dyn ThunkValue<Output = T>>),26	Pending,27}2829#[allow(clippy::module_name_repetitions)]30#[derive(Clone, Trace)]31pub struct Thunk<T: Trace>(Cc<RefCell<ThunkInner<T>>>);3233impl<T> Thunk<T>34where35	T: Clone + Trace,36{37	pub fn new(f: TraceBox<dyn ThunkValue<Output = T>>) -> Self {38		Self(Cc::new(RefCell::new(ThunkInner::Waiting(f))))39	}40	pub fn evaluated(val: T) -> Self {41		Self(Cc::new(RefCell::new(ThunkInner::Computed(val))))42	}43	pub fn force(&self) -> Result<()> {44		self.evaluate()?;45		Ok(())46	}47	pub fn evaluate(&self) -> Result<T> {48		match &*self.0.borrow() {49			ThunkInner::Computed(v) => return Ok(v.clone()),50			ThunkInner::Errored(e) => return Err(e.clone()),51			ThunkInner::Pending => return Err(InfiniteRecursionDetected.into()),52			ThunkInner::Waiting(..) => (),53		};54		let ThunkInner::Waiting(value) = std::mem::replace(&mut *self.0.borrow_mut(), ThunkInner::Pending) else {55			unreachable!();56		};57		let new_value = match value.0.get() {58			Ok(v) => v,59			Err(e) => {60				*self.0.borrow_mut() = ThunkInner::Errored(e.clone());61				return Err(e);62			}63		};64		*self.0.borrow_mut() = ThunkInner::Computed(new_value.clone());65		Ok(new_value)66	}67}6869type CacheKey = (Option<WeakObjValue>, Option<WeakObjValue>);7071#[derive(Trace, Clone)]72pub struct CachedUnbound<I, T>73where74	I: Unbound<Bound = T>,75	T: Trace,76{77	cache: Cc<RefCell<GcHashMap<CacheKey, T>>>,78	value: I,79}80impl<I: Unbound<Bound = T>, T: Trace> CachedUnbound<I, T> {81	pub fn new(value: I) -> Self {82		Self {83			cache: Cc::new(RefCell::new(GcHashMap::new())),84			value,85		}86	}87}88impl<I: Unbound<Bound = T>, T: Clone + Trace> Unbound for CachedUnbound<I, T> {89	type Bound = T;90	fn bind(&self, sup: Option<ObjValue>, this: Option<ObjValue>) -> Result<T> {91		let cache_key = (92			sup.as_ref().map(|s| s.clone().downgrade()),93			this.as_ref().map(|t| t.clone().downgrade()),94		);95		{96			if let Some(t) = self.cache.borrow().get(&cache_key) {97				return Ok(t.clone());98			}99		}100		let bound = self.value.bind(sup, this)?;101102		{103			let mut cache = self.cache.borrow_mut();104			cache.insert(cache_key, bound.clone());105		}106107		Ok(bound)108	}109}110111impl<T: Debug + Trace> Debug for Thunk<T> {112	fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {113		write!(f, "Lazy")114	}115}116impl<T: Trace> PartialEq for Thunk<T> {117	fn eq(&self, other: &Self) -> bool {118		Cc::ptr_eq(&self.0, &other.0)119	}120}121122pub trait ManifestFormat {123	fn manifest_buf(&self, val: Val, buf: &mut String) -> Result<()>;124	fn manifest(&self, val: Val) -> Result<String> {125		let mut out = String::new();126		self.manifest_buf(val, &mut out)?;127		Ok(out)128	}129}130impl<T> ManifestFormat for Box<T>131where132	T: ManifestFormat + ?Sized,133{134	fn manifest_buf(&self, val: Val, buf: &mut String) -> Result<()> {135		let inner = &**self;136		inner.manifest_buf(val, buf)137	}138}139impl<T> ManifestFormat for &'_ T140where141	T: ManifestFormat + ?Sized,142{143	fn manifest_buf(&self, val: Val, buf: &mut String) -> Result<()> {144		let inner = &**self;145		inner.manifest_buf(val, buf)146	}147}148149#[derive(Debug, Clone, Trace)]150pub struct Slice {151	pub(crate) inner: ArrValue,152	pub(crate) from: u32,153	pub(crate) to: u32,154	pub(crate) step: u32,155}156impl Slice {157	const fn from(&self) -> usize {158		self.from as usize159	}160	const fn to(&self) -> usize {161		self.to as usize162	}163	const fn step(&self) -> usize {164		self.step as usize165	}166	const fn len(&self) -> usize {167		// TODO: use div_ceil168		let diff = self.to() - self.from();169		let rem = diff % self.step();170		let div = diff / self.step();171172		if rem == 0 {173			div174		} else {175			div + 1176		}177	}178}179180/// Represents a Jsonnet array value.181#[derive(Debug, Clone, Trace)]182// may contrain other ArrValue183#[trace(tracking(force))]184pub enum ArrValue {185	/// Layout optimized byte array.186	Bytes(#[trace(skip)] IBytes),187	/// Every element is lazy evaluated.188	Lazy(Cc<Vec<Thunk<Val>>>),189	/// Every field is already evaluated.190	Eager(Cc<Vec<Val>>),191	/// Concatenation of two arrays of any kind.192	Extended(Box<(Self, Self)>),193	/// Represents a integer array in form `[start, start + 1, ... end - 1, end]`.194	/// This kind of arrays is generated by `std.range(start, end)` call, and used for loops.195	Range(i32, i32),196	/// Sliced array view.197	Slice(Box<Slice>),198	/// Reversed array view.199	/// Returned by `std.reverse(other)` call200	Reversed(Box<Self>),201}202203#[cfg(target_pointer_width = "64")]204static_assertions::assert_eq_size!(ArrValue, [u8; 16]);205206impl ArrValue {207	pub fn new_eager() -> Self {208		Self::Eager(Cc::new(Vec::new()))209	}210	pub fn empty() -> Self {211		Self::new_range(0, 0)212	}213214	/// # Panics215	/// If a > b216	#[inline]217	pub fn new_range(a: i32, b: i32) -> Self {218		assert!(a <= b);219		Self::Range(a, b)220	}221222	/// # Panics223	/// If passed numbers are incorrect224	#[must_use]225	pub fn slice(self, from: Option<usize>, to: Option<usize>, step: Option<usize>) -> Self {226		let len = self.len();227		let from = from.unwrap_or(0);228		let to = to.unwrap_or(len).min(len);229		let step = step.unwrap_or(1);230		assert!(from < to);231		assert!(step > 0);232233		Self::Slice(Box::new(Slice {234			inner: self,235			from: from as u32,236			to: to as u32,237			step: step as u32,238		}))239	}240241	/// Array length.242	pub fn len(&self) -> usize {243		match self {244			Self::Bytes(i) => i.len(),245			Self::Lazy(l) => l.len(),246			Self::Eager(e) => e.len(),247			Self::Extended(v) => v.0.len() + v.1.len(),248			Self::Range(a, b) => a.abs_diff(*b) as usize + 1,249			Self::Reversed(i) => i.len(),250			Self::Slice(s) => s.len(),251		}252	}253254	/// Is array contains no elements?255	pub fn is_empty(&self) -> bool {256		self.len() == 0257	}258259	/// Get array element by index, evaluating it, if it is lazy.260	///261	/// Returns `None` on out-of-bounds condition.262	pub fn get(&self, index: usize) -> Result<Option<Val>> {263		match self {264			Self::Bytes(i) => i265				.get(index)266				.map_or(Ok(None), |v| Ok(Some(Val::Num(f64::from(*v))))),267			Self::Lazy(vec) => {268				if let Some(v) = vec.get(index) {269					Ok(Some(v.evaluate()?))270				} else {271					Ok(None)272				}273			}274			Self::Eager(vec) => Ok(vec.get(index).cloned()),275			Self::Extended(v) => {276				let a_len = v.0.len();277				if a_len > index {278					v.0.get(index)279				} else {280					v.1.get(index - a_len)281				}282			}283			Self::Range(a, _) => {284				if index >= self.len() {285					return Ok(None);286				}287				Ok(Some(Val::Num(((*a as isize) + index as isize) as f64)))288			}289			Self::Reversed(v) => {290				let len = v.len();291				if index >= len {292					return Ok(None);293				}294				v.get(len - index - 1)295			}296			Self::Slice(v) => {297				let index = v.from() + index * v.step();298				if index >= v.to() {299					return Ok(None);300				}301				v.inner.get(index)302			}303		}304	}305306	/// Get array element by index, without evaluation.307	///308	/// Returns `None` on out-of-bounds condition.309	pub fn get_lazy(&self, index: usize) -> Option<Thunk<Val>> {310		match self {311			Self::Bytes(i) => i312				.get(index)313				.map(|b| Thunk::evaluated(Val::Num(f64::from(*b)))),314			Self::Lazy(vec) => vec.get(index).cloned(),315			Self::Eager(vec) => vec.get(index).cloned().map(Thunk::evaluated),316			Self::Extended(v) => {317				let a_len = v.0.len();318				if a_len > index {319					v.0.get_lazy(index)320				} else {321					v.1.get_lazy(index - a_len)322				}323			}324			Self::Range(a, _) => {325				if index >= self.len() {326					return None;327				}328				Some(Thunk::evaluated(Val::Num(329					((*a as isize) + index as isize) as f64,330				)))331			}332			Self::Reversed(v) => {333				let len = v.len();334				if index >= len {335					return None;336				}337				v.get_lazy(len - index - 1)338			}339			Self::Slice(s) => {340				let index = s.from() + index * s.step();341				if index >= s.to() {342					return None;343				}344				s.inner.get_lazy(index)345			}346		}347	}348349	/// Evaluate all array elements, returning new array.350	pub fn evaluated(&self) -> Result<Cc<Vec<Val>>> {351		Ok(match self {352			Self::Bytes(i) => {353				let mut out = Vec::with_capacity(i.len());354				for v in i.iter() {355					out.push(Val::Num(f64::from(*v)));356				}357				Cc::new(out)358			}359			Self::Lazy(vec) => {360				let mut out = Vec::with_capacity(vec.len());361				for item in vec.iter() {362					out.push(item.evaluate()?);363				}364				Cc::new(out)365			}366			Self::Eager(vec) => vec.clone(),367			Self::Extended(_v) => {368				let mut out = Vec::with_capacity(self.len());369				for item in self.iter() {370					out.push(item?);371				}372				Cc::new(out)373			}374			Self::Range(a, b) => {375				let mut out = Vec::with_capacity(self.len());376				for i in *a..*b {377					out.push(Val::Num(f64::from(i)));378				}379				Cc::new(out)380			}381			Self::Reversed(r) => {382				let mut r = r.evaluated()?;383				Cc::update_with(&mut r, |v| v.reverse());384				r385			}386			Self::Slice(v) => {387				let mut out = Vec::with_capacity(v.inner.len());388				for v in v389					.inner390					.iter_lazy()391					.skip(v.from())392					.take(v.to() - v.from())393					.step_by(v.step())394				{395					out.push(v.evaluate()?);396				}397				Cc::new(out)398			}399		})400	}401402	/// Iterate over elements, evaluating them.403	pub fn iter(&self) -> impl DoubleEndedIterator<Item = Result<Val>> + '_ {404		(0..self.len()).map(move |idx| match self {405			Self::Bytes(b) => Ok(Val::Num(f64::from(b[idx]))),406			Self::Lazy(l) => l[idx].evaluate(),407			Self::Eager(e) => Ok(e[idx].clone()),408			Self::Extended(..) | Self::Range(..) | Self::Reversed(..) | Self::Slice(..) => {409				self.get(idx).map(|e| e.expect("idx < len"))410			}411		})412	}413414	/// Iterate over elements, returning lazy values.415	pub fn iter_lazy(&self) -> impl DoubleEndedIterator<Item = Thunk<Val>> + '_ {416		(0..self.len()).map(move |idx| match self {417			Self::Bytes(b) => Thunk::evaluated(Val::Num(f64::from(b[idx]))),418			Self::Lazy(l) => l[idx].clone(),419			Self::Eager(e) => Thunk::evaluated(e[idx].clone()),420			Self::Slice(..) | Self::Extended(..) | Self::Range(..) | Self::Reversed(..) => {421				self.get_lazy(idx).expect("idx < len")422			}423		})424	}425426	/// Return a reversed view on current array.427	#[must_use]428	pub fn reversed(self) -> Self {429		Self::Reversed(Box::new(self))430	}431432	/// Return a new array, produced by passing every element of current array to specified callback function.433	pub fn map(self, mapper: impl Fn(Val) -> Result<Val>) -> Result<Self> {434		let mut out = Vec::with_capacity(self.len());435436		for value in self.iter() {437			out.push(mapper(value?)?);438		}439440		Ok(Self::Eager(Cc::new(out)))441	}442443	/// Return a new array, produced from current array by removing every value, for which specified callback function returns false.444	pub fn filter(self, filter: impl Fn(&Val) -> Result<bool>) -> Result<Self> {445		let mut out = Vec::with_capacity(self.len());446447		for value in self.iter() {448			let value = value?;449			if filter(&value)? {450				out.push(value);451			}452		}453454		Ok(Self::Eager(Cc::new(out)))455	}456457	pub fn ptr_eq(a: &Self, b: &Self) -> bool {458		match (a, b) {459			(Self::Lazy(a), Self::Lazy(b)) => Cc::ptr_eq(a, b),460			(Self::Eager(a), Self::Eager(b)) => Cc::ptr_eq(a, b),461			_ => false,462		}463	}464}465466impl From<Vec<Thunk<Val>>> for ArrValue {467	fn from(v: Vec<Thunk<Val>>) -> Self {468		Self::Lazy(Cc::new(v))469	}470}471472impl From<Vec<Val>> for ArrValue {473	fn from(v: Vec<Val>) -> Self {474		Self::Eager(Cc::new(v))475	}476}477478/// Represents a Jsonnet value, which can be spliced or indexed (string or array).479#[allow(clippy::module_name_repetitions)]480pub enum IndexableVal {481	/// String.482	Str(IStr),483	/// Array.484	Arr(ArrValue),485}486impl IndexableVal {487	/// Slice the value.488	///489	/// # Implementation490	///491	/// For strings, will create a copy of specified interval.492	///493	/// For arrays, nothing will be copied on this call, instead [`ArrValue::Slice`] view will be returned.494	pub fn slice(495		self,496		index: Option<BoundedUsize<0, { i32::MAX as usize }>>,497		end: Option<BoundedUsize<0, { i32::MAX as usize }>>,498		step: Option<BoundedUsize<1, { i32::MAX as usize }>>,499	) -> Result<Self> {500		match &self {501			IndexableVal::Str(s) => {502				let index = index.as_deref().copied().unwrap_or(0);503				let end = end.as_deref().copied().unwrap_or(usize::MAX);504				let step = step.as_deref().copied().unwrap_or(1);505506				if index >= end {507					return Ok(Self::Str("".into()));508				}509510				Ok(Self::Str(511					(s.chars()512						.skip(index)513						.take(end - index)514						.step_by(step)515						.collect::<String>())516					.into(),517				))518			}519			IndexableVal::Arr(arr) => {520				let index = index.as_deref().copied().unwrap_or(0);521				let end = end.as_deref().copied().unwrap_or(usize::MAX).min(arr.len());522				let step = step.as_deref().copied().unwrap_or(1);523524				if index >= end {525					return Ok(Self::Arr(ArrValue::new_eager()));526				}527528				Ok(Self::Arr(ArrValue::Slice(Box::new(Slice {529					inner: arr.clone(),530					from: index as u32,531					to: end as u32,532					step: step as u32,533				}))))534			}535		}536	}537}538539/// Represents any valid Jsonnet value.540#[derive(Debug, Clone, Trace)]541pub enum Val {542	/// Represents a Jsonnet boolean.543	Bool(bool),544	/// Represents a Jsonnet null value.545	Null,546	/// Represents a Jsonnet string.547	Str(IStr),548	/// Represents a Jsonnet number.549	/// Should be finite, and not NaN550	/// This restriction isn't enforced by enum, as enum field can't be marked as private551	Num(f64),552	/// Represents a Jsonnet array.553	Arr(ArrValue),554	/// Represents a Jsonnet object.555	Obj(ObjValue),556	/// Represents a Jsonnet function.557	Func(FuncVal),558}559560impl From<IndexableVal> for Val {561	fn from(v: IndexableVal) -> Self {562		match v {563			IndexableVal::Str(s) => Self::Str(s),564			IndexableVal::Arr(a) => Self::Arr(a),565		}566	}567}568569// Broken between stable and nightly, as there is new layout size optimization570// #[cfg(target_pointer_width = "64")]571// static_assertions::assert_eq_size!(Val, [u8; 24]);572573impl Val {574	pub const fn as_bool(&self) -> Option<bool> {575		match self {576			Self::Bool(v) => Some(*v),577			_ => None,578		}579	}580	pub const fn as_null(&self) -> Option<()> {581		match self {582			Self::Null => Some(()),583			_ => None,584		}585	}586	pub fn as_str(&self) -> Option<IStr> {587		match self {588			Self::Str(s) => Some(s.clone()),589			_ => None,590		}591	}592	pub const fn as_num(&self) -> Option<f64> {593		match self {594			Self::Num(n) => Some(*n),595			_ => None,596		}597	}598	pub fn as_arr(&self) -> Option<ArrValue> {599		match self {600			Self::Arr(a) => Some(a.clone()),601			_ => None,602		}603	}604	pub fn as_obj(&self) -> Option<ObjValue> {605		match self {606			Self::Obj(o) => Some(o.clone()),607			_ => None,608		}609	}610	pub fn as_func(&self) -> Option<FuncVal> {611		match self {612			Self::Func(f) => Some(f.clone()),613			_ => None,614		}615	}616617	/// Creates `Val::Num` after checking for numeric overflow.618	/// As numbers are `f64`, we can just check for their finity.619	pub fn new_checked_num(num: f64) -> Result<Self> {620		if num.is_finite() {621			Ok(Self::Num(num))622		} else {623			throw!("overflow")624		}625	}626627	pub const fn value_type(&self) -> ValType {628		match self {629			Self::Str(..) => ValType::Str,630			Self::Num(..) => ValType::Num,631			Self::Arr(..) => ValType::Arr,632			Self::Obj(..) => ValType::Obj,633			Self::Bool(_) => ValType::Bool,634			Self::Null => ValType::Null,635			Self::Func(..) => ValType::Func,636		}637	}638639	pub fn manifest(&self, format: impl ManifestFormat) -> Result<String> {640		fn manifest_dyn(val: &Val, manifest: &dyn ManifestFormat) -> Result<String> {641			manifest.manifest(val.clone())642		}643		manifest_dyn(self, &format)644	}645646	pub fn to_string(&self) -> Result<IStr> {647		Ok(match self {648			Self::Bool(true) => "true".into(),649			Self::Bool(false) => "false".into(),650			Self::Null => "null".into(),651			Self::Str(s) => s.clone(),652			_ => self653				.manifest(crate::stdlib::manifest::ToStringFormat)654				.map(IStr::from)?,655		})656	}657658	pub fn into_indexable(self) -> Result<IndexableVal> {659		Ok(match self {660			Val::Str(s) => IndexableVal::Str(s),661			Val::Arr(arr) => IndexableVal::Arr(arr),662			_ => throw!(ValueIsNotIndexable(self.value_type())),663		})664	}665}666667const fn is_function_like(val: &Val) -> bool {668	matches!(val, Val::Func(_))669}670671/// Native implementation of `std.primitiveEquals`672pub fn primitive_equals(val_a: &Val, val_b: &Val) -> Result<bool> {673	Ok(match (val_a, val_b) {674		(Val::Bool(a), Val::Bool(b)) => a == b,675		(Val::Null, Val::Null) => true,676		(Val::Str(a), Val::Str(b)) => a == b,677		(Val::Num(a), Val::Num(b)) => (a - b).abs() <= f64::EPSILON,678		(Val::Arr(_), Val::Arr(_)) => {679			throw!("primitiveEquals operates on primitive types, got array")680		}681		(Val::Obj(_), Val::Obj(_)) => {682			throw!("primitiveEquals operates on primitive types, got object")683		}684		(a, b) if is_function_like(a) && is_function_like(b) => {685			throw!("cannot test equality of functions")686		}687		(_, _) => false,688	})689}690691/// Native implementation of `std.equals`692pub fn equals(val_a: &Val, val_b: &Val) -> Result<bool> {693	if val_a.value_type() != val_b.value_type() {694		return Ok(false);695	}696	match (val_a, val_b) {697		(Val::Arr(a), Val::Arr(b)) => {698			if ArrValue::ptr_eq(a, b) {699				return Ok(true);700			}701			if a.len() != b.len() {702				return Ok(false);703			}704			for (a, b) in a.iter().zip(b.iter()) {705				if !equals(&a?, &b?)? {706					return Ok(false);707				}708			}709			Ok(true)710		}711		(Val::Obj(a), Val::Obj(b)) => {712			if ObjValue::ptr_eq(a, b) {713				return Ok(true);714			}715			let fields = a.fields(716				#[cfg(feature = "exp-preserve-order")]717				false,718			);719			if fields720				!= b.fields(721					#[cfg(feature = "exp-preserve-order")]722					false,723				) {724				return Ok(false);725			}726			for field in fields {727				if !equals(728					&a.get(field.clone())?.expect("field exists"),729					&b.get(field)?.expect("field exists"),730				)? {731					return Ok(false);732				}733			}734			Ok(true)735		}736		(a, b) => Ok(primitive_equals(a, b)?),737	}738}