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

difftreelog

source

crates/jrsonnet-evaluator/src/val.rs13.5 KiBsourcehistory
1use std::{2	cell::RefCell,3	fmt::{self, Debug, Display},4	mem::replace,5	rc::Rc,6};78use jrsonnet_gcmodule::{Cc, Trace};9use jrsonnet_interner::IStr;10use jrsonnet_types::ValType;1112pub use crate::arr::{ArrValue, ArrayLike};13use crate::{14	bail,15	error::{Error, ErrorKind::*},16	function::FuncVal,17	gc::{GcHashMap, TraceBox},18	manifest::{ManifestFormat, ToStringFormat},19	tb,20	typed::BoundedUsize,21	ObjValue, Result, Unbound, WeakObjValue,22};2324pub trait ThunkValue: Trace {25	type Output;26	fn get(self: Box<Self>) -> Result<Self::Output>;27}2829#[derive(Trace)]30enum ThunkInner<T: Trace> {31	Computed(T),32	Errored(Error),33	Waiting(TraceBox<dyn ThunkValue<Output = T>>),34	Pending,35}3637/// Lazily evaluated value38#[allow(clippy::module_name_repetitions)]39#[derive(Clone, Trace)]40pub struct Thunk<T: Trace>(Cc<RefCell<ThunkInner<T>>>);4142impl<T: Trace> Thunk<T> {43	pub fn evaluated(val: T) -> Self {44		Self(Cc::new(RefCell::new(ThunkInner::Computed(val))))45	}46	pub fn new(f: impl ThunkValue<Output = T> + 'static) -> Self {47		Self(Cc::new(RefCell::new(ThunkInner::Waiting(tb!(f)))))48	}49	pub fn errored(e: Error) -> Self {50		Self(Cc::new(RefCell::new(ThunkInner::Errored(e))))51	}52	pub fn result(res: Result<T, Error>) -> Self {53		match res {54			Ok(o) => Self::evaluated(o),55			Err(e) => Self::errored(e),56		}57	}58}5960impl<T> Thunk<T>61where62	T: Clone + Trace,63{64	pub fn force(&self) -> Result<()> {65		self.evaluate()?;66		Ok(())67	}6869	/// Evaluate thunk, or return cached value70	///71	/// # Errors72	///73	/// - Lazy value evaluation returned error74	/// - This method was called during inner value evaluation75	pub fn evaluate(&self) -> Result<T> {76		match &*self.0.borrow() {77			ThunkInner::Computed(v) => return Ok(v.clone()),78			ThunkInner::Errored(e) => return Err(e.clone()),79			ThunkInner::Pending => return Err(InfiniteRecursionDetected.into()),80			ThunkInner::Waiting(..) => (),81		};82		let ThunkInner::Waiting(value) = replace(&mut *self.0.borrow_mut(), ThunkInner::Pending)83		else {84			unreachable!();85		};86		let new_value = match value.0.get() {87			Ok(v) => v,88			Err(e) => {89				*self.0.borrow_mut() = ThunkInner::Errored(e.clone());90				return Err(e);91			}92		};93		*self.0.borrow_mut() = ThunkInner::Computed(new_value.clone());94		Ok(new_value)95	}96}9798pub trait ThunkMapper<Input>: Trace {99	type Output;100	fn map(self, from: Input) -> Result<Self::Output>;101}102impl<Input> Thunk<Input>103where104	Input: Trace + Clone,105{106	pub fn map<M>(self, mapper: M) -> Thunk<M::Output>107	where108		M: ThunkMapper<Input>,109		M::Output: Trace,110	{111		#[derive(Trace)]112		struct Mapped<Input: Trace, Mapper: Trace> {113			inner: Thunk<Input>,114			mapper: Mapper,115		}116		impl<Input, Mapper> ThunkValue for Mapped<Input, Mapper>117		where118			Input: Trace + Clone,119			Mapper: ThunkMapper<Input>,120		{121			type Output = Mapper::Output;122123			fn get(self: Box<Self>) -> Result<Self::Output> {124				let value = self.inner.evaluate()?;125				let mapped = self.mapper.map(value)?;126				Ok(mapped)127			}128		}129130		Thunk::new(Mapped::<Input, M> {131			inner: self,132			mapper,133		})134	}135}136137impl<T: Trace> From<Result<T>> for Thunk<T> {138	fn from(value: Result<T>) -> Self {139		match value {140			Ok(o) => Self::evaluated(o),141			Err(e) => Self::errored(e),142		}143	}144}145impl<T, V: Trace> From<T> for Thunk<V>146where147	T: ThunkValue<Output = V>,148{149	fn from(value: T) -> Self {150		Thunk::new(value)151	}152}153154impl<T: Trace + Default> Default for Thunk<T> {155	fn default() -> Self {156		Self::evaluated(T::default())157	}158}159160type CacheKey = (Option<WeakObjValue>, Option<WeakObjValue>);161162#[derive(Trace, Clone)]163pub struct CachedUnbound<I, T>164where165	I: Unbound<Bound = T>,166	T: Trace,167{168	cache: Cc<RefCell<GcHashMap<CacheKey, T>>>,169	value: I,170}171impl<I: Unbound<Bound = T>, T: Trace> CachedUnbound<I, T> {172	pub fn new(value: I) -> Self {173		Self {174			cache: Cc::new(RefCell::new(GcHashMap::new())),175			value,176		}177	}178}179impl<I: Unbound<Bound = T>, T: Clone + Trace> Unbound for CachedUnbound<I, T> {180	type Bound = T;181	fn bind(&self, sup: Option<ObjValue>, this: Option<ObjValue>) -> Result<T> {182		let cache_key = (183			sup.as_ref().map(|s| s.clone().downgrade()),184			this.as_ref().map(|t| t.clone().downgrade()),185		);186		{187			if let Some(t) = self.cache.borrow().get(&cache_key) {188				return Ok(t.clone());189			}190		}191		let bound = self.value.bind(sup, this)?;192193		{194			let mut cache = self.cache.borrow_mut();195			cache.insert(cache_key, bound.clone());196		}197198		Ok(bound)199	}200}201202impl<T: Debug + Trace> Debug for Thunk<T> {203	fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {204		write!(f, "Lazy")205	}206}207impl<T: Trace> PartialEq for Thunk<T> {208	fn eq(&self, other: &Self) -> bool {209		Cc::ptr_eq(&self.0, &other.0)210	}211}212213/// Represents a Jsonnet value, which can be sliced or indexed (string or array).214#[allow(clippy::module_name_repetitions)]215pub enum IndexableVal {216	/// String.217	Str(IStr),218	/// Array.219	Arr(ArrValue),220}221impl IndexableVal {222	pub fn to_array(self) -> ArrValue {223		match self {224			IndexableVal::Str(s) => ArrValue::chars(s.chars()),225			IndexableVal::Arr(arr) => arr,226		}227	}228	/// Slice the value.229	///230	/// # Implementation231	///232	/// For strings, will create a copy of specified interval.233	///234	/// For arrays, nothing will be copied on this call, instead [`ArrValue::Slice`] view will be returned.235	pub fn slice(236		self,237		index: Option<BoundedUsize<0, { i32::MAX as usize }>>,238		end: Option<BoundedUsize<0, { i32::MAX as usize }>>,239		step: Option<BoundedUsize<1, { i32::MAX as usize }>>,240	) -> Result<Self> {241		match &self {242			IndexableVal::Str(s) => {243				let index = index.as_deref().copied().unwrap_or(0);244				let end = end.as_deref().copied().unwrap_or(usize::MAX);245				let step = step.as_deref().copied().unwrap_or(1);246247				if index >= end {248					return Ok(Self::Str("".into()));249				}250251				Ok(Self::Str(252					(s.chars()253						.skip(index)254						.take(end - index)255						.step_by(step)256						.collect::<String>())257					.into(),258				))259			}260			IndexableVal::Arr(arr) => {261				let index = index.as_deref().copied().unwrap_or(0);262				let end = end.as_deref().copied().unwrap_or(usize::MAX).min(arr.len());263				let step = step.as_deref().copied().unwrap_or(1);264265				if index >= end {266					return Ok(Self::Arr(ArrValue::empty()));267				}268269				Ok(Self::Arr(270					arr.clone()271						.slice(Some(index), Some(end), Some(step))272						.expect("arguments checked"),273				))274			}275		}276	}277}278279#[derive(Debug, Clone, Trace)]280pub enum StrValue {281	Flat(IStr),282	Tree(Rc<(StrValue, StrValue, usize)>),283}284impl StrValue {285	pub fn concat(a: StrValue, b: StrValue) -> Self {286		// TODO: benchmark for an optimal value, currently just a arbitrary choice287		const STRING_EXTEND_THRESHOLD: usize = 100;288289		if a.is_empty() {290			b291		} else if b.is_empty() {292			a293		} else if a.len() + b.len() < STRING_EXTEND_THRESHOLD {294			Self::Flat(format!("{a}{b}").into())295		} else {296			let len = a.len() + b.len();297			Self::Tree(Rc::new((a, b, len)))298		}299	}300	pub fn into_flat(self) -> IStr {301		#[cold]302		fn write_buf(s: &StrValue, out: &mut String) {303			match s {304				StrValue::Flat(f) => out.push_str(f),305				StrValue::Tree(t) => {306					write_buf(&t.0, out);307					write_buf(&t.1, out);308				}309			}310		}311		match self {312			StrValue::Flat(f) => f,313			StrValue::Tree(_) => {314				let mut buf = String::with_capacity(self.len());315				write_buf(&self, &mut buf);316				buf.into()317			}318		}319	}320	pub fn len(&self) -> usize {321		match self {322			StrValue::Flat(v) => v.len(),323			StrValue::Tree(t) => t.2,324		}325	}326	pub fn is_empty(&self) -> bool {327		match self {328			Self::Flat(v) => v.is_empty(),329			// Can't create non-flat empty string330			Self::Tree(_) => false,331		}332	}333}334impl<T> From<T> for StrValue335where336	IStr: From<T>,337{338	fn from(value: T) -> Self {339		Self::Flat(IStr::from(value))340	}341}342impl Display for StrValue {343	fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {344		match self {345			StrValue::Flat(v) => write!(f, "{v}"),346			StrValue::Tree(t) => {347				write!(f, "{}", t.0)?;348				write!(f, "{}", t.1)349			}350		}351	}352}353impl PartialEq for StrValue {354	fn eq(&self, other: &Self) -> bool {355		let a = self.clone().into_flat();356		let b = other.clone().into_flat();357		a == b358	}359}360impl Eq for StrValue {}361impl PartialOrd for StrValue {362	fn partial_cmp(&self, other: &Self) -> Option<std::cmp::Ordering> {363		Some(self.cmp(other))364	}365}366impl Ord for StrValue {367	fn cmp(&self, other: &Self) -> std::cmp::Ordering {368		let a = self.clone().into_flat();369		let b = other.clone().into_flat();370		a.cmp(&b)371	}372}373374/// Represents any valid Jsonnet value.375#[derive(Debug, Clone, Trace, Default)]376pub enum Val {377	/// Represents a Jsonnet boolean.378	Bool(bool),379	/// Represents a Jsonnet null value.380	#[default]381	Null,382	/// Represents a Jsonnet string.383	Str(StrValue),384	/// Represents a Jsonnet number.385	/// Should be finite, and not NaN386	/// This restriction isn't enforced by enum, as enum field can't be marked as private387	Num(f64),388	/// Experimental bigint389	#[cfg(feature = "exp-bigint")]390	BigInt(#[trace(skip)] Box<num_bigint::BigInt>),391	/// Represents a Jsonnet array.392	Arr(ArrValue),393	/// Represents a Jsonnet object.394	Obj(ObjValue),395	/// Represents a Jsonnet function.396	Func(FuncVal),397}398399#[cfg(target_pointer_width = "64")]400static_assertions::assert_eq_size!(Val, [u8; 24]);401402impl From<IndexableVal> for Val {403	fn from(v: IndexableVal) -> Self {404		match v {405			IndexableVal::Str(s) => Self::string(s),406			IndexableVal::Arr(a) => Self::Arr(a),407		}408	}409}410411impl Val {412	pub const fn as_bool(&self) -> Option<bool> {413		match self {414			Self::Bool(v) => Some(*v),415			_ => None,416		}417	}418	pub const fn as_null(&self) -> Option<()> {419		match self {420			Self::Null => Some(()),421			_ => None,422		}423	}424	pub fn as_str(&self) -> Option<IStr> {425		match self {426			Self::Str(s) => Some(s.clone().into_flat()),427			_ => None,428		}429	}430	pub const fn as_num(&self) -> Option<f64> {431		match self {432			Self::Num(n) => Some(*n),433			_ => None,434		}435	}436	pub fn as_arr(&self) -> Option<ArrValue> {437		match self {438			Self::Arr(a) => Some(a.clone()),439			_ => None,440		}441	}442	pub fn as_obj(&self) -> Option<ObjValue> {443		match self {444			Self::Obj(o) => Some(o.clone()),445			_ => None,446		}447	}448	pub fn as_func(&self) -> Option<FuncVal> {449		match self {450			Self::Func(f) => Some(f.clone()),451			_ => None,452		}453	}454455	/// Creates `Val::Num` after checking for numeric overflow.456	/// As numbers are `f64`, we can just check for their finity.457	pub fn new_checked_num(num: f64) -> Result<Self> {458		if num.is_finite() {459			Ok(Self::Num(num))460		} else {461			bail!("overflow")462		}463	}464465	pub const fn value_type(&self) -> ValType {466		match self {467			Self::Str(..) => ValType::Str,468			Self::Num(..) => ValType::Num,469			#[cfg(feature = "exp-bigint")]470			Self::BigInt(..) => ValType::BigInt,471			Self::Arr(..) => ValType::Arr,472			Self::Obj(..) => ValType::Obj,473			Self::Bool(_) => ValType::Bool,474			Self::Null => ValType::Null,475			Self::Func(..) => ValType::Func,476		}477	}478479	pub fn manifest(&self, format: impl ManifestFormat) -> Result<String> {480		fn manifest_dyn(val: &Val, manifest: &dyn ManifestFormat) -> Result<String> {481			manifest.manifest(val.clone())482		}483		manifest_dyn(self, &format)484	}485486	pub fn to_string(&self) -> Result<IStr> {487		Ok(match self {488			Self::Bool(true) => "true".into(),489			Self::Bool(false) => "false".into(),490			Self::Null => "null".into(),491			Self::Str(s) => s.clone().into_flat(),492			_ => self.manifest(ToStringFormat).map(IStr::from)?,493		})494	}495496	pub fn into_indexable(self) -> Result<IndexableVal> {497		Ok(match self {498			Val::Str(s) => IndexableVal::Str(s.into_flat()),499			Val::Arr(arr) => IndexableVal::Arr(arr),500			_ => bail!(ValueIsNotIndexable(self.value_type())),501		})502	}503504	pub fn function(function: impl Into<FuncVal>) -> Self {505		Self::Func(function.into())506	}507	pub fn string(string: impl Into<StrValue>) -> Self {508		Self::Str(string.into())509	}510}511512impl From<IStr> for Val {513	fn from(value: IStr) -> Self {514		Self::string(value)515	}516}517impl From<String> for Val {518	fn from(value: String) -> Self {519		Self::string(value)520	}521}522impl From<&str> for Val {523	fn from(value: &str) -> Self {524		Self::string(value)525	}526}527impl From<ObjValue> for Val {528	fn from(value: ObjValue) -> Self {529		Self::Obj(value)530	}531}532533const fn is_function_like(val: &Val) -> bool {534	matches!(val, Val::Func(_))535}536537/// Native implementation of `std.primitiveEquals`538pub fn primitive_equals(val_a: &Val, val_b: &Val) -> Result<bool> {539	Ok(match (val_a, val_b) {540		(Val::Bool(a), Val::Bool(b)) => a == b,541		(Val::Null, Val::Null) => true,542		(Val::Str(a), Val::Str(b)) => a == b,543		(Val::Num(a), Val::Num(b)) => (a - b).abs() <= f64::EPSILON,544		#[cfg(feature = "exp-bigint")]545		(Val::BigInt(a), Val::BigInt(b)) => a == b,546		(Val::Arr(_), Val::Arr(_)) => {547			bail!("primitiveEquals operates on primitive types, got array")548		}549		(Val::Obj(_), Val::Obj(_)) => {550			bail!("primitiveEquals operates on primitive types, got object")551		}552		(a, b) if is_function_like(a) && is_function_like(b) => {553			bail!("cannot test equality of functions")554		}555		(_, _) => false,556	})557}558559/// Native implementation of `std.equals`560pub fn equals(val_a: &Val, val_b: &Val) -> Result<bool> {561	if val_a.value_type() != val_b.value_type() {562		return Ok(false);563	}564	match (val_a, val_b) {565		(Val::Arr(a), Val::Arr(b)) => {566			if ArrValue::ptr_eq(a, b) {567				return Ok(true);568			}569			if a.len() != b.len() {570				return Ok(false);571			}572			for (a, b) in a.iter().zip(b.iter()) {573				if !equals(&a?, &b?)? {574					return Ok(false);575				}576			}577			Ok(true)578		}579		(Val::Obj(a), Val::Obj(b)) => {580			if ObjValue::ptr_eq(a, b) {581				return Ok(true);582			}583			let fields = a.fields(584				#[cfg(feature = "exp-preserve-order")]585				false,586			);587			if fields588				!= b.fields(589					#[cfg(feature = "exp-preserve-order")]590					false,591				) {592				return Ok(false);593			}594			for field in fields {595				if !equals(596					&a.get(field.clone())?.expect("field exists"),597					&b.get(field)?.expect("field exists"),598				)? {599					return Ok(false);600				}601			}602			Ok(true)603		}604		(a, b) => Ok(primitive_equals(a, b)?),605	}606}