git.delta.rocks / jrsonnet / refs/commits / 7efefe23889c

difftreelog

source

crates/jrsonnet-evaluator/src/val.rs13.5 KiBsourcehistory
1use crate::{2	builtin::manifest::{3		manifest_json_ex, manifest_yaml_ex, ManifestJsonOptions, ManifestType, ManifestYamlOptions,4	},5	cc_ptr_eq,6	error::{Error::*, LocError},7	evaluate,8	function::{parse_function_call, ArgsLike, Builtin, StaticBuiltin},9	gc::TraceBox,10	throw, Context, ObjValue, Result,11};12use gcmodule::{Cc, Trace};13use jrsonnet_interner::IStr;14use jrsonnet_parser::{ExprLocation, LocExpr, ParamsDesc};15use jrsonnet_types::ValType;16use std::{cell::RefCell, fmt::Debug, rc::Rc};1718pub trait LazyValValue: Trace {19	fn get(self: Box<Self>) -> Result<Val>;20}2122#[derive(Trace)]23enum LazyValInternals {24	Computed(Val),25	Errored(LocError),26	Waiting(TraceBox<dyn LazyValValue>),27	Pending,28}2930#[derive(Clone, Trace)]31pub struct LazyVal(Cc<RefCell<LazyValInternals>>);32impl LazyVal {33	pub fn new(f: TraceBox<dyn LazyValValue>) -> Self {34		Self(Cc::new(RefCell::new(LazyValInternals::Waiting(f))))35	}36	pub fn new_resolved(val: Val) -> Self {37		Self(Cc::new(RefCell::new(LazyValInternals::Computed(val))))38	}39	pub fn force(&self) -> Result<()> {40		self.evaluate()?;41		Ok(())42	}43	pub fn evaluate(&self) -> Result<Val> {44		match &*self.0.borrow() {45			LazyValInternals::Computed(v) => return Ok(v.clone()),46			LazyValInternals::Errored(e) => return Err(e.clone()),47			LazyValInternals::Pending => return Err(RecursiveLazyValueEvaluation.into()),48			_ => (),49		};50		let value = if let LazyValInternals::Waiting(value) =51			std::mem::replace(&mut *self.0.borrow_mut(), LazyValInternals::Pending)52		{53			value54		} else {55			unreachable!()56		};57		let new_value = match value.0.get() {58			Ok(v) => v,59			Err(e) => {60				*self.0.borrow_mut() = LazyValInternals::Errored(e.clone());61				return Err(e);62			}63		};64		*self.0.borrow_mut() = LazyValInternals::Computed(new_value.clone());65		Ok(new_value)66	}67}6869impl Debug for LazyVal {70	fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {71		write!(f, "Lazy")72	}73}74impl PartialEq for LazyVal {75	fn eq(&self, other: &Self) -> bool {76		cc_ptr_eq(&self.0, &other.0)77	}78}7980#[derive(Debug, PartialEq, Trace)]81pub struct FuncDesc {82	pub name: IStr,83	pub ctx: Context,84	pub params: ParamsDesc,85	pub body: LocExpr,86}8788#[derive(Trace, Clone)]89pub enum FuncVal {90	/// Plain function implemented in jsonnet91	Normal(Cc<FuncDesc>),92	/// Standard library function93	StaticBuiltin(#[skip_trace] &'static dyn StaticBuiltin),9495	Builtin(Cc<TraceBox<dyn Builtin>>),96}9798impl Debug for FuncVal {99	fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {100		match self {101			Self::Normal(arg0) => f.debug_tuple("Normal").field(arg0).finish(),102			Self::StaticBuiltin(arg0) => f.debug_tuple("Intrinsic").field(&arg0.name()).finish(),103			Self::Builtin(arg0) => f.debug_tuple("Intrinsic").field(&arg0.name()).finish(),104		}105	}106}107108impl PartialEq for FuncVal {109	fn eq(&self, other: &Self) -> bool {110		match (self, other) {111			(Self::Normal(a), Self::Normal(b)) => a == b,112			(Self::StaticBuiltin(an), Self::StaticBuiltin(bn)) => std::ptr::eq(*an, *bn),113			(..) => false,114		}115	}116}117impl FuncVal {118	pub fn args_len(&self) -> usize {119		match self {120			Self::Normal(n) => n.params.iter().filter(|p| p.1.is_none()).count(),121			Self::StaticBuiltin(i) => i.params().iter().filter(|p| !p.has_default).count(),122			Self::Builtin(i) => i.params().iter().filter(|p| !p.has_default).count(),123		}124	}125	pub fn name(&self) -> IStr {126		match self {127			Self::Normal(normal) => normal.name.clone(),128			Self::StaticBuiltin(builtin) => builtin.name().into(),129			Self::Builtin(builtin) => builtin.name().into(),130		}131	}132	pub fn evaluate(133		&self,134		call_ctx: Context,135		loc: Option<&ExprLocation>,136		args: &dyn ArgsLike,137		tailstrict: bool,138	) -> Result<Val> {139		match self {140			Self::Normal(func) => {141				let ctx = parse_function_call(142					call_ctx,143					func.ctx.clone(),144					&func.params,145					args,146					tailstrict,147				)?;148				evaluate(ctx, &func.body)149			}150			Self::StaticBuiltin(name) => name.call(call_ctx, loc, args),151			Self::Builtin(b) => b.call(call_ctx, loc, args),152		}153	}154	pub fn evaluate_simple(&self, args: &dyn ArgsLike) -> Result<Val> {155		self.evaluate(Context::default(), None, args, true)156	}157}158159#[derive(Clone)]160pub enum ManifestFormat {161	YamlStream(Box<ManifestFormat>),162	Yaml(usize),163	Json(usize),164	ToString,165	String,166}167168#[derive(Debug, Clone, Trace)]169#[force_tracking]170pub enum ArrValue {171	Lazy(Cc<Vec<LazyVal>>),172	Eager(Cc<Vec<Val>>),173	Extended(Box<(Self, Self)>),174}175impl ArrValue {176	pub fn new_eager() -> Self {177		Self::Eager(Cc::new(Vec::new()))178	}179180	pub fn len(&self) -> usize {181		match self {182			Self::Lazy(l) => l.len(),183			Self::Eager(e) => e.len(),184			Self::Extended(v) => v.0.len() + v.1.len(),185		}186	}187188	pub fn is_empty(&self) -> bool {189		self.len() == 0190	}191192	pub fn get(&self, index: usize) -> Result<Option<Val>> {193		match self {194			Self::Lazy(vec) => {195				if let Some(v) = vec.get(index) {196					Ok(Some(v.evaluate()?))197				} else {198					Ok(None)199				}200			}201			Self::Eager(vec) => Ok(vec.get(index).cloned()),202			Self::Extended(v) => {203				let a_len = v.0.len();204				if a_len > index {205					v.0.get(index)206				} else {207					v.1.get(index - a_len)208				}209			}210		}211	}212213	pub fn get_lazy(&self, index: usize) -> Option<LazyVal> {214		match self {215			Self::Lazy(vec) => vec.get(index).cloned(),216			Self::Eager(vec) => vec.get(index).cloned().map(LazyVal::new_resolved),217			Self::Extended(v) => {218				let a_len = v.0.len();219				if a_len > index {220					v.0.get_lazy(index)221				} else {222					v.1.get_lazy(index - a_len)223				}224			}225		}226	}227228	pub fn evaluated(&self) -> Result<Cc<Vec<Val>>> {229		Ok(match self {230			Self::Lazy(vec) => {231				let mut out = Vec::with_capacity(vec.len());232				for item in vec.iter() {233					out.push(item.evaluate()?);234				}235				Cc::new(out)236			}237			Self::Eager(vec) => vec.clone(),238			Self::Extended(_v) => {239				let mut out = Vec::with_capacity(self.len());240				for item in self.iter() {241					out.push(item?);242				}243				Cc::new(out)244			}245		})246	}247248	pub fn iter(&self) -> impl DoubleEndedIterator<Item = Result<Val>> + '_ {249		(0..self.len()).map(move |idx| match self {250			Self::Lazy(l) => l[idx].evaluate(),251			Self::Eager(e) => Ok(e[idx].clone()),252			Self::Extended(_) => self.get(idx).map(|e| e.unwrap()),253		})254	}255256	pub fn iter_lazy(&self) -> impl DoubleEndedIterator<Item = LazyVal> + '_ {257		(0..self.len()).map(move |idx| match self {258			Self::Lazy(l) => l[idx].clone(),259			Self::Eager(e) => LazyVal::new_resolved(e[idx].clone()),260			Self::Extended(_) => self.get_lazy(idx).unwrap(),261		})262	}263264	pub fn reversed(self) -> Self {265		match self {266			Self::Lazy(vec) => {267				let mut out = (&vec as &Vec<_>).clone();268				out.reverse();269				Self::Lazy(Cc::new(out))270			}271			Self::Eager(vec) => {272				let mut out = (&vec as &Vec<_>).clone();273				out.reverse();274				Self::Eager(Cc::new(out))275			}276			Self::Extended(b) => Self::Extended(Box::new((b.1.reversed(), b.0.reversed()))),277		}278	}279280	pub fn map(self, mapper: impl Fn(Val) -> Result<Val>) -> Result<Self> {281		let mut out = Vec::with_capacity(self.len());282283		for value in self.iter() {284			out.push(mapper(value?)?);285		}286287		Ok(Self::Eager(Cc::new(out)))288	}289290	pub fn filter(self, filter: impl Fn(&Val) -> Result<bool>) -> Result<Self> {291		let mut out = Vec::with_capacity(self.len());292293		for value in self.iter() {294			let value = value?;295			if filter(&value)? {296				out.push(value);297			}298		}299300		Ok(Self::Eager(Cc::new(out)))301	}302303	pub fn ptr_eq(a: &Self, b: &Self) -> bool {304		match (a, b) {305			(Self::Lazy(a), Self::Lazy(b)) => cc_ptr_eq(a, b),306			(Self::Eager(a), Self::Eager(b)) => cc_ptr_eq(a, b),307			_ => false,308		}309	}310}311312impl From<Vec<LazyVal>> for ArrValue {313	fn from(v: Vec<LazyVal>) -> Self {314		Self::Lazy(Cc::new(v))315	}316}317318impl From<Vec<Val>> for ArrValue {319	fn from(v: Vec<Val>) -> Self {320		Self::Eager(Cc::new(v))321	}322}323324pub enum IndexableVal {325	Str(IStr),326	Arr(ArrValue),327}328329#[derive(Debug, Clone, Trace)]330pub enum Val {331	Bool(bool),332	Null,333	Str(IStr),334	Num(f64),335	Arr(ArrValue),336	Obj(ObjValue),337	Func(FuncVal),338}339340impl Val {341	/// Creates `Val::Num` after checking for numeric overflow.342	/// As numbers are `f64`, we can just check for their finity.343	pub fn new_checked_num(num: f64) -> Result<Self> {344		if num.is_finite() {345			Ok(Self::Num(num))346		} else {347			throw!(RuntimeError("overflow".into()))348		}349	}350351	pub fn try_cast_nullable_num(self, context: &'static str) -> Result<Option<f64>> {352		Ok(match self {353			Val::Null => None,354			Val::Num(num) => Some(num),355			_ => throw!(TypeMismatch(356				context,357				vec![ValType::Null, ValType::Num],358				self.value_type()359			)),360		})361	}362	pub const fn value_type(&self) -> ValType {363		match self {364			Self::Str(..) => ValType::Str,365			Self::Num(..) => ValType::Num,366			Self::Arr(..) => ValType::Arr,367			Self::Obj(..) => ValType::Obj,368			Self::Bool(_) => ValType::Bool,369			Self::Null => ValType::Null,370			Self::Func(..) => ValType::Func,371		}372	}373374	pub fn to_string(&self) -> Result<IStr> {375		Ok(match self {376			Self::Bool(true) => "true".into(),377			Self::Bool(false) => "false".into(),378			Self::Null => "null".into(),379			Self::Str(s) => s.clone(),380			v => manifest_json_ex(381				v,382				&ManifestJsonOptions {383					padding: "",384					mtype: ManifestType::ToString,385					newline: "\n",386					key_val_sep: ": ",387				},388			)?389			.into(),390		})391	}392393	/// Expects value to be object, outputs (key, manifested value) pairs394	pub fn manifest_multi(&self, ty: &ManifestFormat) -> Result<Vec<(IStr, IStr)>> {395		let obj = match self {396			Self::Obj(obj) => obj,397			_ => throw!(MultiManifestOutputIsNotAObject),398		};399		let keys = obj.fields();400		let mut out = Vec::with_capacity(keys.len());401		for key in keys {402			let value = obj403				.get(key.clone())?404				.expect("item in object")405				.manifest(ty)?;406			out.push((key, value));407		}408		Ok(out)409	}410411	/// Expects value to be array, outputs manifested values412	pub fn manifest_stream(&self, ty: &ManifestFormat) -> Result<Vec<IStr>> {413		let arr = match self {414			Self::Arr(a) => a,415			_ => throw!(StreamManifestOutputIsNotAArray),416		};417		let mut out = Vec::with_capacity(arr.len());418		for i in arr.iter() {419			out.push(i?.manifest(ty)?);420		}421		Ok(out)422	}423424	pub fn manifest(&self, ty: &ManifestFormat) -> Result<IStr> {425		Ok(match ty {426			ManifestFormat::YamlStream(format) => {427				let arr = match self {428					Self::Arr(a) => a,429					_ => throw!(StreamManifestOutputIsNotAArray),430				};431				let mut out = String::new();432433				match format as &ManifestFormat {434					ManifestFormat::YamlStream(_) => throw!(StreamManifestOutputCannotBeRecursed),435					ManifestFormat::String => throw!(StreamManifestCannotNestString),436					_ => {}437				};438439				if !arr.is_empty() {440					for v in arr.iter() {441						out.push_str("---\n");442						out.push_str(&v?.manifest(format)?);443						out.push('\n');444					}445					out.push_str("...");446				}447448				out.into()449			}450			ManifestFormat::Yaml(padding) => self.to_yaml(*padding)?,451			ManifestFormat::Json(padding) => self.to_json(*padding)?,452			ManifestFormat::ToString => self.to_string()?,453			ManifestFormat::String => match self {454				Self::Str(s) => s.clone(),455				_ => throw!(StringManifestOutputIsNotAString),456			},457		})458	}459460	/// For manifestification461	pub fn to_json(&self, padding: usize) -> Result<IStr> {462		manifest_json_ex(463			self,464			&ManifestJsonOptions {465				padding: &" ".repeat(padding),466				mtype: if padding == 0 {467					ManifestType::Minify468				} else {469					ManifestType::Manifest470				},471				newline: "\n",472				key_val_sep: ": ",473			},474		)475		.map(|s| s.into())476	}477478	/// Calls `std.manifestJson`479	pub fn to_std_json(&self, padding: usize) -> Result<Rc<str>> {480		manifest_json_ex(481			self,482			&ManifestJsonOptions {483				padding: &" ".repeat(padding),484				mtype: ManifestType::Std,485				newline: "\n",486				key_val_sep: ": ",487			},488		)489		.map(|s| s.into())490	}491492	pub fn to_yaml(&self, padding: usize) -> Result<IStr> {493		let padding = &" ".repeat(padding);494		manifest_yaml_ex(495			self,496			&ManifestYamlOptions {497				padding,498				arr_element_padding: padding,499				quote_keys: false,500			},501		)502		.map(|s| s.into())503	}504	pub fn into_indexable(self) -> Result<IndexableVal> {505		Ok(match self {506			Val::Str(s) => IndexableVal::Str(s),507			Val::Arr(arr) => IndexableVal::Arr(arr),508			_ => throw!(ValueIsNotIndexable(self.value_type())),509		})510	}511}512513const fn is_function_like(val: &Val) -> bool {514	matches!(val, Val::Func(_))515}516517/// Native implementation of `std.primitiveEquals`518pub fn primitive_equals(val_a: &Val, val_b: &Val) -> Result<bool> {519	Ok(match (val_a, val_b) {520		(Val::Bool(a), Val::Bool(b)) => a == b,521		(Val::Null, Val::Null) => true,522		(Val::Str(a), Val::Str(b)) => a == b,523		(Val::Num(a), Val::Num(b)) => (a - b).abs() <= f64::EPSILON,524		(Val::Arr(_), Val::Arr(_)) => throw!(RuntimeError(525			"primitiveEquals operates on primitive types, got array".into(),526		)),527		(Val::Obj(_), Val::Obj(_)) => throw!(RuntimeError(528			"primitiveEquals operates on primitive types, got object".into(),529		)),530		(a, b) if is_function_like(a) && is_function_like(b) => {531			throw!(RuntimeError("cannot test equality of functions".into()))532		}533		(_, _) => false,534	})535}536537/// Native implementation of `std.equals`538pub fn equals(val_a: &Val, val_b: &Val) -> Result<bool> {539	if val_a.value_type() != val_b.value_type() {540		return Ok(false);541	}542	match (val_a, val_b) {543		(Val::Arr(a), Val::Arr(b)) => {544			if ArrValue::ptr_eq(a, b) {545				return Ok(true);546			}547			if a.len() != b.len() {548				return Ok(false);549			}550			for (a, b) in a.iter().zip(b.iter()) {551				if !equals(&a?, &b?)? {552					return Ok(false);553				}554			}555			Ok(true)556		}557		(Val::Obj(a), Val::Obj(b)) => {558			if ObjValue::ptr_eq(a, b) {559				return Ok(true);560			}561			let fields = a.fields();562			if fields != b.fields() {563				return Ok(false);564			}565			for field in fields {566				if !equals(&a.get(field.clone())?.unwrap(), &b.get(field)?.unwrap())? {567					return Ok(false);568				}569			}570			Ok(true)571		}572		(a, b) => Ok(primitive_equals(a, b)?),573	}574}