git.delta.rocks / jrsonnet / refs/commits / 028057c85dc5

difftreelog

refactor! remove Lazy from Val

Yaroslav Bolyukin2020-12-01parent: #194642f.patch.diff
in: master
Now lazy is used only in objects/arrays
BREAKING CHANGE: value_type() is never fails

9 files changed

modifiedbindings/jsonnet/src/val_extract.rsdiffbeforeafterboth
--- a/bindings/jsonnet/src/val_extract.rs
+++ b/bindings/jsonnet/src/val_extract.rs
@@ -9,7 +9,7 @@
 
 #[no_mangle]
 pub extern "C" fn jsonnet_json_extract_string(_vm: &EvaluationState, v: &Val) -> *mut c_char {
-	match v.unwrap_if_lazy().unwrap() {
+	match v {
 		Val::Str(s) => CString::new(&*s as &str).unwrap().into_raw(),
 		_ => std::ptr::null_mut(),
 	}
@@ -20,9 +20,9 @@
 	v: &Val,
 	out: &mut c_double,
 ) -> c_int {
-	match v.unwrap_if_lazy().unwrap() {
+	match v {
 		Val::Num(n) => {
-			*out = n;
+			*out = *n;
 			1
 		}
 		_ => 0,
@@ -30,7 +30,7 @@
 }
 #[no_mangle]
 pub extern "C" fn jsonnet_json_extract_bool(_vm: &EvaluationState, v: &Val) -> c_int {
-	match v.unwrap_if_lazy().unwrap() {
+	match v {
 		Val::Bool(false) => 0,
 		Val::Bool(true) => 1,
 		_ => 2,
@@ -38,7 +38,7 @@
 }
 #[no_mangle]
 pub extern "C" fn jsonnet_json_extract_null(_vm: &EvaluationState, v: &Val) -> c_int {
-	match v.unwrap_if_lazy().unwrap() {
+	match v {
 		Val::Null => 1,
 		_ => 0,
 	}
modifiedcrates/jrsonnet-evaluator/src/builtin/format.rsdiffbeforeafterboth
--- a/crates/jrsonnet-evaluator/src/builtin/format.rs
+++ b/crates/jrsonnet-evaluator/src/builtin/format.rs
@@ -1,7 +1,8 @@
 //! faster std.format impl
 #![allow(clippy::too_many_arguments)]
 
-use crate::{error::Error::*, throw, LocError, ObjValue, Result, Val, ValType};
+use crate::{error::Error::*, throw, LocError, ObjValue, Result, Val};
+use jrsonnet_types::ValType;
 use thiserror::Error;
 
 #[derive(Debug, Clone, Error)]
@@ -573,7 +574,7 @@
 				);
 			}
 		}
-		ConvTypeV::Char => match value.clone().unwrap_if_lazy()? {
+		ConvTypeV::Char => match value.clone() {
 			Val::Num(n) => tmp_out.push(
 				std::char::from_u32(n as u32)
 					.ok_or_else(|| InvalidUnicodeCodepointGot(n as u32))?,
@@ -590,7 +591,7 @@
 				throw!(TypeMismatch(
 					"%c requires number/string",
 					vec![ValType::Num, ValType::Str],
-					value.value_type()?,
+					value.value_type(),
 				));
 			}
 		},
modifiedcrates/jrsonnet-evaluator/src/builtin/manifest.rsdiffbeforeafterboth
--- a/crates/jrsonnet-evaluator/src/builtin/manifest.rs
+++ b/crates/jrsonnet-evaluator/src/builtin/manifest.rs
@@ -33,9 +33,9 @@
 ) -> Result<()> {
 	use std::fmt::Write;
 	let mtype = options.mtype;
-	match val.unwrap_if_lazy()? {
+	match val {
 		Val::Bool(v) => {
-			if v {
+			if *v {
 				buf.push_str("true");
 			} else {
 				buf.push_str("false");
@@ -63,7 +63,7 @@
 						}
 					}
 					buf.push_str(cur_padding);
-					manifest_json_ex_buf(item, buf, cur_padding, options)?;
+					manifest_json_ex_buf(&item?, buf, cur_padding, options)?;
 				}
 				cur_padding.truncate(old_len);
 
@@ -118,7 +118,6 @@
 			buf.push('}');
 		}
 		Val::Func(_) => throw!(RuntimeError("tried to manifest function".into())),
-		Val::Lazy(_) => unreachable!(),
 	};
 	Ok(())
 }
modifiedcrates/jrsonnet-evaluator/src/builtin/sort.rsdiffbeforeafterboth
--- a/crates/jrsonnet-evaluator/src/builtin/sort.rs
+++ b/crates/jrsonnet-evaluator/src/builtin/sort.rs
@@ -46,7 +46,6 @@
 	let mut sort_type = SortKeyType::Unknown;
 	for i in values.iter_mut() {
 		let i = key_getter(i);
-		i.inplace_unwrap()?;
 		match (i, sort_type) {
 			(Val::Str(_), SortKeyType::Unknown) => sort_type = SortKeyType::String,
 			(Val::Num(_), SortKeyType::Unknown) => sort_type = SortKeyType::Number,
modifiedcrates/jrsonnet-evaluator/src/evaluate.rsdiffbeforeafterboth
--- a/crates/jrsonnet-evaluator/src/evaluate.rs
+++ b/crates/jrsonnet-evaluator/src/evaluate.rs
@@ -1,7 +1,6 @@
 use crate::{
 	context_creator, error::Error::*, future_wrapper, lazy_val, push, throw, with_state, Context,
 	ContextCreator, FuncDesc, FuncVal, LazyBinding, LazyVal, ObjMember, ObjValue, Result, Val,
-	ValType,
 };
 use closure::closure;
 use jrsonnet_parser::{
@@ -9,6 +8,7 @@
 	ForSpecData, IfSpecData, LiteralType, LocExpr, Member, ObjBody, ParamsDesc, UnaryOpType,
 	Visibility,
 };
+use jrsonnet_types::ValType;
 use rustc_hash::FxHashMap;
 use std::{collections::HashMap, rc::Rc};
 
@@ -61,8 +61,7 @@
 	Ok(match field_name {
 		jrsonnet_parser::FieldName::Fixed(n) => Some(n.clone()),
 		jrsonnet_parser::FieldName::Dyn(expr) => {
-			let lazy = evaluate(context, expr)?;
-			let value = lazy.unwrap_if_lazy()?;
+			let value = evaluate(context, expr)?;
 			if matches!(value, Val::Null) {
 				None
 			} else {
@@ -74,11 +73,10 @@
 
 pub fn evaluate_unary_op(op: UnaryOpType, b: &Val) -> Result<Val> {
 	Ok(match (op, b) {
-		(o, Val::Lazy(l)) => evaluate_unary_op(o, &l.evaluate()?)?,
 		(UnaryOpType::Not, Val::Bool(v)) => Val::Bool(!v),
 		(UnaryOpType::Minus, Val::Num(n)) => Val::Num(-*n),
 		(UnaryOpType::BitNot, Val::Num(n)) => Val::Num(!(*n as i32) as f64),
-		(op, o) => throw!(UnaryOperatorDoesNotOperateOnType(op, o.value_type()?)),
+		(op, o) => throw!(UnaryOperatorDoesNotOperateOnType(op, o.value_type())),
 	})
 }
 
@@ -94,12 +92,17 @@
 		(o, Val::Str(s)) => Val::Str(format!("{}{}", o.clone().to_string()?, s).into()),
 
 		(Val::Obj(v1), Val::Obj(v2)) => Val::Obj(v2.with_super(v1.clone())),
-		(Val::Arr(a), Val::Arr(b)) => Val::Arr(Rc::new([&a[..], &b[..]].concat())),
+		(Val::Arr(a), Val::Arr(b)) => {
+			let mut out = Vec::with_capacity(a.len() + b.len());
+			out.extend(a.iter_lazy());
+			out.extend(b.iter_lazy());
+			Val::Arr(out.into())
+		}
 		(Val::Num(v1), Val::Num(v2)) => Val::new_checked_num(v1 + v2)?,
 		_ => throw!(BinaryOperatorDoesNotOperateOnValues(
 			BinaryOpType::Add,
-			a.value_type()?,
-			b.value_type()?,
+			a.value_type(),
+			b.value_type(),
 		)),
 	})
 }
@@ -110,15 +113,11 @@
 	op: BinaryOpType,
 	b: &LocExpr,
 ) -> Result<Val> {
-	Ok(
-		match (evaluate(context.clone(), a)?.unwrap_if_lazy()?, op, b) {
-			(Val::Bool(true), BinaryOpType::Or, _o) => Val::Bool(true),
-			(Val::Bool(false), BinaryOpType::And, _o) => Val::Bool(false),
-			(a, op, eb) => {
-				evaluate_binary_op_normal(&a, op, &evaluate(context, eb)?.unwrap_if_lazy()?)?
-			}
-		},
-	)
+	Ok(match (evaluate(context.clone(), a)?, op, b) {
+		(Val::Bool(true), BinaryOpType::Or, _o) => Val::Bool(true),
+		(Val::Bool(false), BinaryOpType::And, _o) => Val::Bool(false),
+		(a, op, eb) => evaluate_binary_op_normal(&a, op, &evaluate(context, eb)?)?,
+	})
 }
 
 pub fn evaluate_binary_op_normal(a: &Val, op: BinaryOpType, b: &Val) -> Result<Val> {
@@ -177,8 +176,8 @@
 
 		_ => throw!(BinaryOperatorDoesNotOperateOnValues(
 			op,
-			a.value_type()?,
-			b.value_type()?,
+			a.value_type(),
+			b.value_type(),
 		)),
 	})
 }
@@ -200,23 +199,20 @@
 				None
 			}
 		}
-		Some(CompSpec::ForSpec(ForSpecData(var, expr))) => {
-			match evaluate(context.clone(), expr)?.unwrap_if_lazy()? {
-				Val::Arr(list) => {
-					let mut out = Vec::new();
-					for item in list.iter() {
-						let item = item.unwrap_if_lazy()?;
-						out.push(evaluate_comp(
-							context.clone().with_var(var.clone(), item.clone()),
-							value,
-							&specs[1..],
-						)?);
-					}
-					Some(out.into_iter().flatten().flatten().collect())
+		Some(CompSpec::ForSpec(ForSpecData(var, expr))) => match evaluate(context.clone(), expr)? {
+			Val::Arr(list) => {
+				let mut out = Vec::new();
+				for item in list.iter() {
+					out.push(evaluate_comp(
+						context.clone().with_var(var.clone(), item?.clone()),
+						value,
+						&specs[1..],
+					)?);
 				}
-				_ => throw!(InComprehensionCanOnlyIterateOverArray),
+				Some(out.into_iter().flatten().flatten().collect())
 			}
-		}
+			_ => throw!(InComprehensionCanOnlyIterateOverArray),
+		},
 	})
 }
 
@@ -375,7 +371,7 @@
 							},
 						);
 					}
-					v => throw!(FieldMustBeStringGot(v.value_type()?)),
+					v => throw!(FieldMustBeStringGot(v.value_type())),
 				}
 			}
 
@@ -391,8 +387,7 @@
 	loc: &Option<ExprLocation>,
 	tailstrict: bool,
 ) -> Result<Val> {
-	let lazy = evaluate(context.clone(), value)?;
-	let value = lazy.unwrap_if_lazy()?;
+	let value = evaluate(context.clone(), value)?;
 	Ok(match value {
 		Val::Func(f) => {
 			let body = || f.evaluate(context, loc, args, tailstrict);
@@ -402,7 +397,7 @@
 				push(loc, || format!("function <{}> call", f.name()), body)?
 			}
 		}
-		v => throw!(OnlyFunctionsCanBeCalledGot(v.value_type()?)),
+		v => throw!(OnlyFunctionsCanBeCalledGot(v.value_type())),
 	})
 }
 
@@ -436,7 +431,7 @@
 		Var(name) => push(
 			loc,
 			|| format!("variable <{}>", name),
-			|| Ok(Val::Lazy(context.binding(name.clone())?).unwrap_if_lazy()?),
+			|| Ok(context.binding(name.clone())?.evaluate()?),
 		)?,
 		Index(LocExpr(v, _), index) if matches!(&**v, Expr::Literal(LiteralType::Super)) => {
 			let name = evaluate(context.clone(), index)?.try_cast_str("object index")?;
@@ -444,14 +439,11 @@
 				.super_obj()
 				.clone()
 				.expect("no super found")
-				.get_raw(name, &context.this().clone().expect("no this found"))?
+				.get_raw(name, Some(&context.this().clone().expect("no this found")))?
 				.expect("value not found")
 		}
 		Index(value, index) => {
-			match (
-				evaluate(context.clone(), value)?.unwrap_if_lazy()?,
-				evaluate(context, index)?,
-			) {
+			match (evaluate(context.clone(), value)?, evaluate(context, index)?) {
 				(Val::Obj(v), Val::Str(s)) => {
 					let sn = s.clone();
 					push(
@@ -459,7 +451,7 @@
 						|| format!("field <{}> access", sn),
 						|| {
 							if let Some(v) = v.get(s.clone())? {
-								Ok(v.unwrap_if_lazy()?)
+								Ok(v)
 							} else if v.get("__intrinsic_namespace__".into())?.is_some() {
 								Ok(Val::Func(Rc::new(FuncVal::Intrinsic(s))))
 							} else {
@@ -471,23 +463,22 @@
 				(Val::Obj(_), n) => throw!(ValueIndexMustBeTypeGot(
 					ValType::Obj,
 					ValType::Str,
-					n.value_type()?,
+					n.value_type(),
 				)),
 
 				(Val::Arr(v), Val::Num(n)) => {
 					if n.fract() > f64::EPSILON {
 						throw!(FractionalIndex)
 					}
-					v.get(n as usize)
+					v.get(n as usize)?
 						.ok_or_else(|| ArrayBoundsError(n as usize, v.len()))?
 						.clone()
-						.unwrap_if_lazy()?
 				}
 				(Val::Arr(_), Val::Str(n)) => throw!(AttemptedIndexAnArrayWithString(n)),
 				(Val::Arr(_), n) => throw!(ValueIndexMustBeTypeGot(
 					ValType::Arr,
 					ValType::Num,
-					n.value_type()?,
+					n.value_type(),
 				)),
 
 				(Val::Str(s), Val::Num(n)) => Val::Str(
@@ -500,10 +491,10 @@
 				(Val::Str(_), n) => throw!(ValueIndexMustBeTypeGot(
 					ValType::Str,
 					ValType::Num,
-					n.value_type()?,
+					n.value_type(),
 				)),
 
-				(v, _) => throw!(CantIndexInto(v.value_type()?)),
+				(v, _) => throw!(CantIndexInto(v.value_type())),
 			}
 		}
 		LocalExpr(bindings, returned) => {
@@ -529,17 +520,19 @@
 		Arr(items) => {
 			let mut out = Vec::with_capacity(items.len());
 			for item in items {
-				out.push(Val::Lazy(lazy_val!(
+				out.push(LazyVal::new(Box::new(
 					closure!(clone context, clone item, || {
 						evaluate(context.clone(), &item)
-					})
+					}),
 				)));
 			}
-			Val::Arr(Rc::new(out))
+			Val::Arr(out.into())
 		}
 		ArrComp(expr, comp_specs) => Val::Arr(
 			// First comp_spec should be for_spec, so no "None" possible here
-			Rc::new(evaluate_comp(context, &|ctx| evaluate(ctx, expr), comp_specs)?.unwrap()),
+			evaluate_comp(context, &|ctx| evaluate(ctx, expr), comp_specs)?
+				.unwrap()
+				.into(),
 		),
 		Obj(body) => Val::Obj(evaluate_object(context, body)?),
 		ObjExtend(s, t) => evaluate_add_op(
modifiedcrates/jrsonnet-evaluator/src/integrations/serde.rsdiffbeforeafterboth
--- a/crates/jrsonnet-evaluator/src/integrations/serde.rs
+++ b/crates/jrsonnet-evaluator/src/integrations/serde.rs
@@ -22,11 +22,10 @@
 			} else {
 				Number::from_f64(*n).expect("to json number")
 			}),
-			Val::Lazy(v) => (&v.evaluate()?).try_into()?,
 			Val::Arr(a) => {
 				let mut out = Vec::with_capacity(a.len());
 				for item in a.iter() {
-					out.push(item.try_into()?);
+					out.push((&item?).try_into()?);
 				}
 				Self::Array(out)
 			}
@@ -55,9 +54,9 @@
 			Value::Array(a) => {
 				let mut out = Vec::with_capacity(a.len());
 				for v in a {
-					out.push(v.into());
+					out.push(LazyVal::new_resolved(v.into()));
 				}
-				Self::Arr(Rc::new(out))
+				Self::Arr(out.into())
 			}
 			Value::Object(o) => {
 				let mut entries = HashMap::with_capacity(o.len());
modifiedcrates/jrsonnet-evaluator/src/obj.rsdiffbeforeafterboth
--- a/crates/jrsonnet-evaluator/src/obj.rs
+++ b/crates/jrsonnet-evaluator/src/obj.rs
@@ -102,9 +102,10 @@
 		visible_fields
 	}
 	pub fn get(&self, key: Rc<str>) -> Result<Option<Val>> {
-		Ok(self.get_raw(key, self)?)
+		Ok(self.get_raw(key, None)?)
 	}
-	pub(crate) fn get_raw(&self, key: Rc<str>, real_this: &Self) -> Result<Option<Val>> {
+	pub(crate) fn get_raw(&self, key: Rc<str>, real_this: Option<&Self>) -> Result<Option<Val>> {
+		let real_this = real_this.unwrap_or(self);
 		let cache_key = (key.clone(), Rc::as_ptr(&real_this.0) as usize);
 
 		if let Some(v) = self.0.value_cache.borrow().get(&cache_key) {
@@ -115,7 +116,7 @@
 			(Some(k), Some(s)) => {
 				let our = self.evaluate_this(k, real_this)?;
 				if k.add {
-					s.get_raw(key, real_this)?
+					s.get_raw(key, Some(real_this))?
 						.map_or(Ok(Some(our.clone())), |v| {
 							Ok(Some(evaluate_add_op(&v, &our)?))
 						})
@@ -123,7 +124,7 @@
 					Ok(Some(our))
 				}
 			}
-			(None, Some(s)) => s.get_raw(key, real_this),
+			(None, Some(s)) => s.get_raw(key, Some(real_this)),
 			(None, None) => Ok(None),
 		}?;
 		self.0
modifiedcrates/jrsonnet-evaluator/src/val.rsdiffbeforeafterboth
before · crates/jrsonnet-evaluator/src/val.rs
1use crate::{2	builtin::{3		call_builtin,4		manifest::{manifest_json_ex, ManifestJsonOptions, ManifestType},5	},6	error::Error::*,7	evaluate,8	function::{parse_function_call, parse_function_call_map, place_args},9	native::NativeCallback,10	throw, with_state, Context, ObjValue, Result,11};12use jrsonnet_parser::{el, Arg, ArgsDesc, Expr, ExprLocation, LiteralType, LocExpr, ParamsDesc};13use std::{14	cell::RefCell,15	collections::HashMap,16	fmt::{Debug, Display},17	rc::Rc,18};1920enum LazyValInternals {21	Computed(Val),22	Waiting(Box<dyn Fn() -> Result<Val>>),23}24#[derive(Clone)]25pub struct LazyVal(Rc<RefCell<LazyValInternals>>);26impl LazyVal {27	pub fn new(f: Box<dyn Fn() -> Result<Val>>) -> Self {28		Self(Rc::new(RefCell::new(LazyValInternals::Waiting(f))))29	}30	pub fn new_resolved(val: Val) -> Self {31		Self(Rc::new(RefCell::new(LazyValInternals::Computed(val))))32	}33	pub fn evaluate(&self) -> Result<Val> {34		let new_value = match &*self.0.borrow() {35			LazyValInternals::Computed(v) => return Ok(v.clone()),36			LazyValInternals::Waiting(f) => f()?,37		};38		*self.0.borrow_mut() = LazyValInternals::Computed(new_value.clone());39		Ok(new_value)40	}41}4243#[macro_export]44macro_rules! lazy_val {45	($f: expr) => {46		$crate::LazyVal::new(Box::new($f))47	};48}49#[macro_export]50macro_rules! resolved_lazy_val {51	($f: expr) => {52		$crate::LazyVal::new_resolved($f)53	};54}55impl Debug for LazyVal {56	fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {57		write!(f, "Lazy")58	}59}60impl PartialEq for LazyVal {61	fn eq(&self, other: &Self) -> bool {62		Rc::ptr_eq(&self.0, &other.0)63	}64}6566#[derive(Debug, PartialEq)]67pub struct FuncDesc {68	pub name: Rc<str>,69	pub ctx: Context,70	pub params: ParamsDesc,71	pub body: LocExpr,72}7374#[derive(Debug)]75pub enum FuncVal {76	/// Plain function implemented in jsonnet77	Normal(FuncDesc),78	/// Standard library function79	Intrinsic(Rc<str>),80	/// Library functions implemented in native81	NativeExt(Rc<str>, Rc<NativeCallback>),82}8384impl PartialEq for FuncVal {85	fn eq(&self, other: &Self) -> bool {86		match (self, other) {87			(Self::Normal(a), Self::Normal(b)) => a == b,88			(Self::Intrinsic(an), Self::Intrinsic(bn)) => an == bn,89			(Self::NativeExt(an, _), Self::NativeExt(bn, _)) => an == bn,90			(..) => false,91		}92	}93}94impl FuncVal {95	pub fn is_ident(&self) -> bool {96		matches!(&self, Self::Intrinsic(n) if n as &str == "id")97	}98	pub fn name(&self) -> Rc<str> {99		match self {100			Self::Normal(normal) => normal.name.clone(),101			Self::Intrinsic(name) => format!("std.{}", name).into(),102			Self::NativeExt(n, _) => format!("native.{}", n).into(),103		}104	}105	pub fn evaluate(106		&self,107		call_ctx: Context,108		loc: &Option<ExprLocation>,109		args: &ArgsDesc,110		tailstrict: bool,111	) -> Result<Val> {112		match self {113			Self::Normal(func) => {114				let ctx = parse_function_call(115					call_ctx,116					Some(func.ctx.clone()),117					&func.params,118					args,119					tailstrict,120				)?;121				evaluate(ctx, &func.body)122			}123			Self::Intrinsic(name) => call_builtin(call_ctx, loc, name, args),124			Self::NativeExt(_name, handler) => {125				let args = parse_function_call(call_ctx, None, &handler.params, args, true)?;126				let mut out_args = Vec::with_capacity(handler.params.len());127				for p in handler.params.0.iter() {128					out_args.push(args.binding(p.0.clone())?.evaluate()?);129				}130				Ok(handler.call(&out_args)?)131			}132		}133	}134135	pub fn evaluate_map(136		&self,137		call_ctx: Context,138		args: &HashMap<Rc<str>, Val>,139		tailstrict: bool,140	) -> Result<Val> {141		match self {142			Self::Normal(func) => {143				let ctx = parse_function_call_map(144					call_ctx,145					Some(func.ctx.clone()),146					&func.params,147					args,148					tailstrict,149				)?;150				evaluate(ctx, &func.body)151			}152			Self::Intrinsic(_) => todo!(),153			Self::NativeExt(_, _) => todo!(),154		}155	}156157	pub fn evaluate_values(&self, call_ctx: Context, args: &[Val]) -> Result<Val> {158		match self {159			Self::Normal(func) => {160				let ctx = place_args(call_ctx, Some(func.ctx.clone()), &func.params, args)?;161				evaluate(ctx, &func.body)162			}163			Self::Intrinsic(_) => todo!(),164			Self::NativeExt(_, _) => todo!(),165		}166	}167}168169#[derive(Debug, Clone, Copy, PartialEq)]170pub enum ValType {171	Bool,172	Null,173	Str,174	Num,175	Arr,176	Obj,177	Func,178}179impl ValType {180	pub const fn name(&self) -> &'static str {181		use ValType::*;182		match self {183			Bool => "boolean",184			Null => "null",185			Str => "string",186			Num => "number",187			Arr => "array",188			Obj => "object",189			Func => "function",190		}191	}192}193impl Display for ValType {194	fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {195		write!(f, "{}", self.name())196	}197}198199#[derive(Clone)]200pub enum ManifestFormat {201	YamlStream(Box<ManifestFormat>),202	Yaml(usize),203	Json(usize),204	ToString,205	String,206}207208#[derive(Debug, Clone)]209pub enum Val {210	Bool(bool),211	Null,212	Str(Rc<str>),213	Num(f64),214	Lazy(LazyVal),215	Arr(Rc<Vec<Val>>),216	Obj(ObjValue),217	Func(Rc<FuncVal>),218}219220macro_rules! matches_unwrap {221	($e: expr, $p: pat, $r: expr) => {222		match $e {223			$p => $r,224			_ => panic!("no match"),225			}226	};227}228impl Val {229	/// Creates `Val::Num` after checking for numeric overflow.230	/// As numbers are `f64`, we can just check for their finity.231	pub fn new_checked_num(num: f64) -> Result<Self> {232		if num.is_finite() {233			Ok(Self::Num(num))234		} else {235			throw!(RuntimeError("overflow".into()))236		}237	}238239	pub fn assert_type(&self, context: &'static str, val_type: ValType) -> Result<()> {240		let this_type = self.value_type()?;241		if this_type != val_type {242			throw!(TypeMismatch(context, vec![val_type], this_type))243		} else {244			Ok(())245		}246	}247	pub fn try_cast_bool(self, context: &'static str) -> Result<bool> {248		self.assert_type(context, ValType::Bool)?;249		Ok(matches_unwrap!(self.unwrap_if_lazy()?, Self::Bool(v), v))250	}251	pub fn try_cast_str(self, context: &'static str) -> Result<Rc<str>> {252		self.assert_type(context, ValType::Str)?;253		Ok(matches_unwrap!(self.unwrap_if_lazy()?, Self::Str(v), v))254	}255	pub fn try_cast_num(self, context: &'static str) -> Result<f64> {256		self.assert_type(context, ValType::Num)?;257		Ok(matches_unwrap!(self.unwrap_if_lazy()?, Self::Num(v), v))258	}259	pub fn inplace_unwrap(&mut self) -> Result<()> {260		while let Self::Lazy(lazy) = self {261			*self = lazy.evaluate()?;262		}263		Ok(())264	}265	pub fn unwrap_if_lazy(&self) -> Result<Self> {266		Ok(if let Self::Lazy(v) = self {267			v.evaluate()?.unwrap_if_lazy()?268		} else {269			self.clone()270		})271	}272	pub fn value_type(&self) -> Result<ValType> {273		Ok(match self {274			Self::Str(..) => ValType::Str,275			Self::Num(..) => ValType::Num,276			Self::Arr(..) => ValType::Arr,277			Self::Obj(..) => ValType::Obj,278			Self::Bool(_) => ValType::Bool,279			Self::Null => ValType::Null,280			Self::Func(..) => ValType::Func,281			Self::Lazy(_) => self.clone().unwrap_if_lazy()?.value_type()?,282		})283	}284285	pub fn to_string(&self) -> Result<Rc<str>> {286		Ok(match self.unwrap_if_lazy()? {287			Self::Bool(true) => "true".into(),288			Self::Bool(false) => "false".into(),289			Self::Null => "null".into(),290			Self::Str(s) => s,291			v => manifest_json_ex(292				&v,293				&ManifestJsonOptions {294					padding: "",295					mtype: ManifestType::ToString,296				},297			)?298			.into(),299		})300	}301302	/// Expects value to be object, outputs (key, manifested value) pairs303	pub fn manifest_multi(&self, ty: &ManifestFormat) -> Result<Vec<(Rc<str>, Rc<str>)>> {304		let obj = match self {305			Self::Obj(obj) => obj,306			_ => throw!(MultiManifestOutputIsNotAObject),307		};308		let keys = obj.visible_fields();309		let mut out = Vec::with_capacity(keys.len());310		for key in keys {311			let value = obj312				.get(key.clone())?313				.expect("item in object")314				.manifest(ty)?;315			out.push((key, value));316		}317		Ok(out)318	}319320	/// Expects value to be array, outputs manifested values321	pub fn manifest_stream(&self, ty: &ManifestFormat) -> Result<Vec<Rc<str>>> {322		let arr = match self {323			Self::Arr(a) => a,324			_ => throw!(StreamManifestOutputIsNotAArray),325		};326		let mut out = Vec::with_capacity(arr.len());327		for i in arr.iter() {328			out.push(i.manifest(ty)?);329		}330		Ok(out)331	}332333	pub fn manifest(&self, ty: &ManifestFormat) -> Result<Rc<str>> {334		Ok(match ty {335			ManifestFormat::YamlStream(format) => {336				let arr = match self {337					Self::Arr(a) => a,338					_ => throw!(StreamManifestOutputIsNotAArray),339				};340				let mut out = String::new();341342				match format as &ManifestFormat {343					ManifestFormat::YamlStream(_) => throw!(StreamManifestOutputCannotBeRecursed),344					ManifestFormat::String => throw!(StreamManifestCannotNestString),345					_ => {}346				};347348				if !arr.is_empty() {349					for v in arr.iter() {350						out.push_str("---\n");351						out.push_str(&v.manifest(format)?);352						out.push('\n');353					}354					out.push_str("...");355				}356357				out.into()358			}359			ManifestFormat::Yaml(padding) => self.to_yaml(*padding)?,360			ManifestFormat::Json(padding) => self.to_json(*padding)?,361			ManifestFormat::ToString => self.to_string()?,362			ManifestFormat::String => match self {363				Self::Str(s) => s.clone(),364				_ => throw!(StringManifestOutputIsNotAString),365			},366		})367	}368369	/// For manifestification370	pub fn to_json(&self, padding: usize) -> Result<Rc<str>> {371		manifest_json_ex(372			self,373			&ManifestJsonOptions {374				padding: &" ".repeat(padding),375				mtype: if padding == 0 {376					ManifestType::Minify377				} else {378					ManifestType::Manifest379				},380			},381		)382		.map(|s| s.into())383	}384385	/// Calls `std.manifestJson`386	#[cfg(feature = "faster")]387	pub fn to_std_json(&self, padding: usize) -> Result<Rc<str>> {388		manifest_json_ex(389			self,390			&ManifestJsonOptions {391				padding: &" ".repeat(padding),392				mtype: ManifestType::Std,393			},394		)395		.map(|s| s.into())396	}397398	/// Calls `std.manifestJson`399	#[cfg(not(feature = "faster"))]400	pub fn to_std_json(&self, padding: usize) -> Result<Rc<str>> {401		with_state(|s| {402			let ctx = s403				.create_default_context()?404				.with_var("__tmp__to_json__".into(), self.clone())?;405			Ok(evaluate(406				ctx,407				&el!(Expr::Apply(408					el!(Expr::Index(409						el!(Expr::Var("std".into())),410						el!(Expr::Str("manifestJsonEx".into()))411					)),412					ArgsDesc(vec![413						Arg(None, el!(Expr::Var("__tmp__to_json__".into()))),414						Arg(None, el!(Expr::Str(" ".repeat(padding).into())))415					]),416					false417				)),418			)?419			.try_cast_str("to json")?)420		})421	}422	pub fn to_yaml(&self, padding: usize) -> Result<Rc<str>> {423		with_state(|s| {424			let ctx = s425				.create_default_context()?426				.with_var("__tmp__to_json__".into(), self.clone());427			Ok(evaluate(428				ctx,429				&el!(Expr::Apply(430					el!(Expr::Index(431						el!(Expr::Var("std".into())),432						el!(Expr::Str("manifestYamlDoc".into()))433					)),434					ArgsDesc(vec![435						Arg(None, el!(Expr::Var("__tmp__to_json__".into()))),436						Arg(437							None,438							el!(Expr::Literal(if padding != 0 {439								LiteralType::True440							} else {441								LiteralType::False442							}))443						)444					]),445					false446				)),447			)?448			.try_cast_str("to json")?)449		})450	}451}452453const fn is_function_like(val: &Val) -> bool {454	matches!(val, Val::Func(_))455}456457/// Native implementation of `std.primitiveEquals`458pub fn primitive_equals(val_a: &Val, val_b: &Val) -> Result<bool> {459	Ok(match (val_a.unwrap_if_lazy()?, val_b.unwrap_if_lazy()?) {460		(Val::Bool(a), Val::Bool(b)) => a == b,461		(Val::Null, Val::Null) => true,462		(Val::Str(a), Val::Str(b)) => a == b,463		(Val::Num(a), Val::Num(b)) => (a - b).abs() <= f64::EPSILON,464		(Val::Arr(_), Val::Arr(_)) => throw!(RuntimeError(465			"primitiveEquals operates on primitive types, got array".into(),466		)),467		(Val::Obj(_), Val::Obj(_)) => throw!(RuntimeError(468			"primitiveEquals operates on primitive types, got object".into(),469		)),470		(a, b) if is_function_like(&a) && is_function_like(&b) => {471			throw!(RuntimeError("cannot test equality of functions".into()))472		}473		(_, _) => false,474	})475}476477/// Native implementation of `std.equals`478pub fn equals(val_a: &Val, val_b: &Val) -> Result<bool> {479	let val_a = val_a.unwrap_if_lazy()?;480	let val_b = val_b.unwrap_if_lazy()?;481482	if val_a.value_type()? != val_b.value_type()? {483		return Ok(false);484	}485	match (val_a, val_b) {486		// Cant test for ptr equality, because all fields needs to be evaluated487		(Val::Arr(a), Val::Arr(b)) => {488			if a.len() != b.len() {489				return Ok(false);490			}491			for (a, b) in a.iter().zip(b.iter()) {492				if !equals(&a.unwrap_if_lazy()?, &b.unwrap_if_lazy()?)? {493					return Ok(false);494				}495			}496			Ok(true)497		}498		(Val::Obj(a), Val::Obj(b)) => {499			let fields = a.visible_fields();500			if fields != b.visible_fields() {501				return Ok(false);502			}503			for field in fields {504				if !equals(&a.get(field.clone())?.unwrap(), &b.get(field)?.unwrap())? {505					return Ok(false);506				}507			}508			Ok(true)509		}510		(a, b) => Ok(primitive_equals(&a, &b)?),511	}512}
after · crates/jrsonnet-evaluator/src/val.rs
1use crate::{2	builtin::{3		call_builtin,4		manifest::{manifest_json_ex, ManifestJsonOptions, ManifestType},5	},6	error::Error::*,7	evaluate,8	function::{parse_function_call, parse_function_call_map, place_args},9	native::NativeCallback,10	throw, with_state, Context, ObjValue, Result,11};12use jrsonnet_parser::{el, Arg, ArgsDesc, Expr, ExprLocation, LiteralType, LocExpr, ParamsDesc};13use jrsonnet_types::ValType;14use std::{cell::RefCell, collections::HashMap, fmt::Debug, rc::Rc};1516enum LazyValInternals {17	Computed(Val),18	Waiting(Box<dyn Fn() -> Result<Val>>),19}20#[derive(Clone)]21pub struct LazyVal(Rc<RefCell<LazyValInternals>>);22impl LazyVal {23	pub fn new(f: Box<dyn Fn() -> Result<Val>>) -> Self {24		Self(Rc::new(RefCell::new(LazyValInternals::Waiting(f))))25	}26	pub fn new_resolved(val: Val) -> Self {27		Self(Rc::new(RefCell::new(LazyValInternals::Computed(val))))28	}29	pub fn evaluate(&self) -> Result<Val> {30		let new_value = match &*self.0.borrow() {31			LazyValInternals::Computed(v) => return Ok(v.clone()),32			LazyValInternals::Waiting(f) => f()?,33		};34		*self.0.borrow_mut() = LazyValInternals::Computed(new_value.clone());35		Ok(new_value)36	}37}3839#[macro_export]40macro_rules! lazy_val {41	($f: expr) => {42		$crate::LazyVal::new(Box::new($f))43	};44}45#[macro_export]46macro_rules! resolved_lazy_val {47	($f: expr) => {48		$crate::LazyVal::new_resolved($f)49	};50}51impl Debug for LazyVal {52	fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {53		write!(f, "Lazy")54	}55}56impl PartialEq for LazyVal {57	fn eq(&self, other: &Self) -> bool {58		Rc::ptr_eq(&self.0, &other.0)59	}60}6162#[derive(Debug, PartialEq)]63pub struct FuncDesc {64	pub name: Rc<str>,65	pub ctx: Context,66	pub params: ParamsDesc,67	pub body: LocExpr,68}6970#[derive(Debug)]71pub enum FuncVal {72	/// Plain function implemented in jsonnet73	Normal(FuncDesc),74	/// Standard library function75	Intrinsic(Rc<str>),76	/// Library functions implemented in native77	NativeExt(Rc<str>, Rc<NativeCallback>),78}7980impl PartialEq for FuncVal {81	fn eq(&self, other: &Self) -> bool {82		match (self, other) {83			(Self::Normal(a), Self::Normal(b)) => a == b,84			(Self::Intrinsic(an), Self::Intrinsic(bn)) => an == bn,85			(Self::NativeExt(an, _), Self::NativeExt(bn, _)) => an == bn,86			(..) => false,87		}88	}89}90impl FuncVal {91	pub fn is_ident(&self) -> bool {92		matches!(&self, Self::Intrinsic(n) if n as &str == "id")93	}94	pub fn name(&self) -> Rc<str> {95		match self {96			Self::Normal(normal) => normal.name.clone(),97			Self::Intrinsic(name) => format!("std.{}", name).into(),98			Self::NativeExt(n, _) => format!("native.{}", n).into(),99		}100	}101	pub fn evaluate(102		&self,103		call_ctx: Context,104		loc: &Option<ExprLocation>,105		args: &ArgsDesc,106		tailstrict: bool,107	) -> Result<Val> {108		match self {109			Self::Normal(func) => {110				let ctx = parse_function_call(111					call_ctx,112					Some(func.ctx.clone()),113					&func.params,114					args,115					tailstrict,116				)?;117				evaluate(ctx, &func.body)118			}119			Self::Intrinsic(name) => call_builtin(call_ctx, loc, name, args),120			Self::NativeExt(_name, handler) => {121				let args = parse_function_call(call_ctx, None, &handler.params, args, true)?;122				let mut out_args = Vec::with_capacity(handler.params.len());123				for p in handler.params.0.iter() {124					out_args.push(args.binding(p.0.clone())?.evaluate()?);125				}126				Ok(handler.call(&out_args)?)127			}128		}129	}130131	pub fn evaluate_map(132		&self,133		call_ctx: Context,134		args: &HashMap<Rc<str>, Val>,135		tailstrict: bool,136	) -> Result<Val> {137		match self {138			Self::Normal(func) => {139				let ctx = parse_function_call_map(140					call_ctx,141					Some(func.ctx.clone()),142					&func.params,143					args,144					tailstrict,145				)?;146				evaluate(ctx, &func.body)147			}148			Self::Intrinsic(_) => todo!(),149			Self::NativeExt(_, _) => todo!(),150		}151	}152153	pub fn evaluate_values(&self, call_ctx: Context, args: &[Val]) -> Result<Val> {154		match self {155			Self::Normal(func) => {156				let ctx = place_args(call_ctx, Some(func.ctx.clone()), &func.params, args)?;157				evaluate(ctx, &func.body)158			}159			Self::Intrinsic(_) => todo!(),160			Self::NativeExt(_, _) => todo!(),161		}162	}163}164165#[derive(Clone)]166pub enum ManifestFormat {167	YamlStream(Box<ManifestFormat>),168	Yaml(usize),169	Json(usize),170	ToString,171	String,172}173174#[derive(Debug, Clone)]175pub enum ArrValue {176	Lazy(Rc<Vec<LazyVal>>),177	Eager(Rc<Vec<Val>>),178}179impl ArrValue {180	pub fn len(&self) -> usize {181		match self {182			ArrValue::Lazy(l) => l.len(),183			ArrValue::Eager(e) => e.len(),184		}185	}186187	pub fn is_empty(&self) -> bool {188		self.len() == 0189	}190191	pub fn get(&self, index: usize) -> Result<Option<Val>> {192		match self {193			ArrValue::Lazy(vec) => {194				if let Some(v) = vec.get(index) {195					Ok(Some(v.evaluate()?))196				} else {197					Ok(None)198				}199			}200			ArrValue::Eager(vec) => Ok(vec.get(index).cloned()),201		}202	}203204	pub fn get_lazy(&self, index: usize) -> Option<LazyVal> {205		match self {206			ArrValue::Lazy(vec) => vec.get(index).cloned(),207			ArrValue::Eager(vec) => vec208				.get(index)209				.cloned()210				.map(|val| LazyVal::new_resolved(val)),211		}212	}213214	pub fn evaluated(&self) -> Result<Rc<Vec<Val>>> {215		Ok(match self {216			ArrValue::Lazy(vec) => {217				let mut out = Vec::with_capacity(vec.len());218				for item in vec.iter() {219					out.push(item.evaluate()?);220				}221				Rc::new(out)222			}223			ArrValue::Eager(vec) => vec.clone(),224		})225	}226227	pub fn iter(&self) -> impl DoubleEndedIterator<Item = Result<Val>> + '_ {228		(0..self.len()).map(move |idx| match self {229			ArrValue::Lazy(l) => l[idx].evaluate(),230			ArrValue::Eager(e) => Ok(e[idx].clone()),231		})232	}233234	pub fn iter_lazy(&self) -> impl DoubleEndedIterator<Item = LazyVal> + '_ {235		(0..self.len()).map(move |idx| match self {236			ArrValue::Lazy(l) => l[idx].clone(),237			ArrValue::Eager(e) => LazyVal::new_resolved(e[idx].clone()),238		})239	}240241	pub fn reversed(self) -> Self {242		match self {243			ArrValue::Lazy(vec) => {244				let mut out = (&vec as &Vec<_>).clone();245				out.reverse();246				Self::Lazy(Rc::new(out))247			}248			ArrValue::Eager(vec) => {249				let mut out = (&vec as &Vec<_>).clone();250				out.reverse();251				Self::Eager(Rc::new(out))252			}253		}254	}255}256257impl From<Vec<LazyVal>> for ArrValue {258	fn from(v: Vec<LazyVal>) -> Self {259		Self::Lazy(Rc::new(v))260	}261}262263impl From<Vec<Val>> for ArrValue {264	fn from(v: Vec<Val>) -> Self {265		Self::Eager(Rc::new(v))266	}267}268269#[derive(Debug, Clone)]270pub enum Val {271	Bool(bool),272	Null,273	Str(Rc<str>),274	Num(f64),275	Arr(ArrValue),276	Obj(ObjValue),277	Func(Rc<FuncVal>),278}279280macro_rules! matches_unwrap {281	($e: expr, $p: pat, $r: expr) => {282		match $e {283			$p => $r,284			_ => panic!("no match"),285			}286	};287}288impl Val {289	/// Creates `Val::Num` after checking for numeric overflow.290	/// As numbers are `f64`, we can just check for their finity.291	pub fn new_checked_num(num: f64) -> Result<Self> {292		if num.is_finite() {293			Ok(Self::Num(num))294		} else {295			throw!(RuntimeError("overflow".into()))296		}297	}298299	pub fn assert_type(&self, context: &'static str, val_type: ValType) -> Result<()> {300		let this_type = self.value_type();301		if this_type != val_type {302			throw!(TypeMismatch(context, vec![val_type], this_type))303		} else {304			Ok(())305		}306	}307	pub fn unwrap_num(self) -> Result<f64> {308		Ok(matches_unwrap!(self, Self::Num(v), v))309	}310	pub fn unwrap_func(self) -> Result<Rc<FuncVal>> {311		Ok(matches_unwrap!(self, Self::Func(v), v))312	}313	pub fn try_cast_bool(self, context: &'static str) -> Result<bool> {314		self.assert_type(context, ValType::Bool)?;315		Ok(matches_unwrap!(self, Self::Bool(v), v))316	}317	pub fn try_cast_str(self, context: &'static str) -> Result<Rc<str>> {318		self.assert_type(context, ValType::Str)?;319		Ok(matches_unwrap!(self, Self::Str(v), v))320	}321	pub fn try_cast_num(self, context: &'static str) -> Result<f64> {322		self.assert_type(context, ValType::Num)?;323		self.unwrap_num()324	}325	pub fn value_type(&self) -> ValType {326		match self {327			Self::Str(..) => ValType::Str,328			Self::Num(..) => ValType::Num,329			Self::Arr(..) => ValType::Arr,330			Self::Obj(..) => ValType::Obj,331			Self::Bool(_) => ValType::Bool,332			Self::Null => ValType::Null,333			Self::Func(..) => ValType::Func,334		}335	}336337	pub fn to_string(&self) -> Result<Rc<str>> {338		Ok(match self {339			Self::Bool(true) => "true".into(),340			Self::Bool(false) => "false".into(),341			Self::Null => "null".into(),342			Self::Str(s) => s.clone(),343			v => manifest_json_ex(344				&v,345				&ManifestJsonOptions {346					padding: "",347					mtype: ManifestType::ToString,348				},349			)?350			.into(),351		})352	}353354	/// Expects value to be object, outputs (key, manifested value) pairs355	pub fn manifest_multi(&self, ty: &ManifestFormat) -> Result<Vec<(Rc<str>, Rc<str>)>> {356		let obj = match self {357			Self::Obj(obj) => obj,358			_ => throw!(MultiManifestOutputIsNotAObject),359		};360		let keys = obj.visible_fields();361		let mut out = Vec::with_capacity(keys.len());362		for key in keys {363			let value = obj364				.get(key.clone())?365				.expect("item in object")366				.manifest(ty)?;367			out.push((key, value));368		}369		Ok(out)370	}371372	/// Expects value to be array, outputs manifested values373	pub fn manifest_stream(&self, ty: &ManifestFormat) -> Result<Vec<Rc<str>>> {374		let arr = match self {375			Self::Arr(a) => a,376			_ => throw!(StreamManifestOutputIsNotAArray),377		};378		let mut out = Vec::with_capacity(arr.len());379		for i in arr.iter() {380			out.push(i?.manifest(ty)?);381		}382		Ok(out)383	}384385	pub fn manifest(&self, ty: &ManifestFormat) -> Result<Rc<str>> {386		Ok(match ty {387			ManifestFormat::YamlStream(format) => {388				let arr = match self {389					Self::Arr(a) => a,390					_ => throw!(StreamManifestOutputIsNotAArray),391				};392				let mut out = String::new();393394				match format as &ManifestFormat {395					ManifestFormat::YamlStream(_) => throw!(StreamManifestOutputCannotBeRecursed),396					ManifestFormat::String => throw!(StreamManifestCannotNestString),397					_ => {}398				};399400				if !arr.is_empty() {401					for v in arr.iter() {402						out.push_str("---\n");403						out.push_str(&v?.manifest(format)?);404						out.push('\n');405					}406					out.push_str("...");407				}408409				out.into()410			}411			ManifestFormat::Yaml(padding) => self.to_yaml(*padding)?,412			ManifestFormat::Json(padding) => self.to_json(*padding)?,413			ManifestFormat::ToString => self.to_string()?,414			ManifestFormat::String => match self {415				Self::Str(s) => s.clone(),416				_ => throw!(StringManifestOutputIsNotAString),417			},418		})419	}420421	/// For manifestification422	pub fn to_json(&self, padding: usize) -> Result<Rc<str>> {423		manifest_json_ex(424			self,425			&ManifestJsonOptions {426				padding: &" ".repeat(padding),427				mtype: if padding == 0 {428					ManifestType::Minify429				} else {430					ManifestType::Manifest431				},432			},433		)434		.map(|s| s.into())435	}436437	/// Calls `std.manifestJson`438	#[cfg(feature = "faster")]439	pub fn to_std_json(&self, padding: usize) -> Result<Rc<str>> {440		manifest_json_ex(441			self,442			&ManifestJsonOptions {443				padding: &" ".repeat(padding),444				mtype: ManifestType::Std,445			},446		)447		.map(|s| s.into())448	}449450	/// Calls `std.manifestJson`451	#[cfg(not(feature = "faster"))]452	pub fn to_std_json(&self, padding: usize) -> Result<Rc<str>> {453		with_state(|s| {454			let ctx = s455				.create_default_context()?456				.with_var("__tmp__to_json__".into(), self.clone())?;457			Ok(evaluate(458				ctx,459				&el!(Expr::Apply(460					el!(Expr::Index(461						el!(Expr::Var("std".into())),462						el!(Expr::Str("manifestJsonEx".into()))463					)),464					ArgsDesc(vec![465						Arg(None, el!(Expr::Var("__tmp__to_json__".into()))),466						Arg(None, el!(Expr::Str(" ".repeat(padding).into())))467					]),468					false469				)),470			)?471			.try_cast_str("to json")?)472		})473	}474	pub fn to_yaml(&self, padding: usize) -> Result<Rc<str>> {475		with_state(|s| {476			let ctx = s477				.create_default_context()?478				.with_var("__tmp__to_json__".into(), self.clone());479			Ok(evaluate(480				ctx,481				&el!(Expr::Apply(482					el!(Expr::Index(483						el!(Expr::Var("std".into())),484						el!(Expr::Str("manifestYamlDoc".into()))485					)),486					ArgsDesc(vec![487						Arg(None, el!(Expr::Var("__tmp__to_json__".into()))),488						Arg(489							None,490							el!(Expr::Literal(if padding != 0 {491								LiteralType::True492							} else {493								LiteralType::False494							}))495						)496					]),497					false498				)),499			)?500			.try_cast_str("to json")?)501		})502	}503}504505const fn is_function_like(val: &Val) -> bool {506	matches!(val, Val::Func(_))507}508509/// Native implementation of `std.primitiveEquals`510pub fn primitive_equals(val_a: &Val, val_b: &Val) -> Result<bool> {511	Ok(match (val_a, val_b) {512		(Val::Bool(a), Val::Bool(b)) => a == b,513		(Val::Null, Val::Null) => true,514		(Val::Str(a), Val::Str(b)) => a == b,515		(Val::Num(a), Val::Num(b)) => (a - b).abs() <= f64::EPSILON,516		(Val::Arr(_), Val::Arr(_)) => throw!(RuntimeError(517			"primitiveEquals operates on primitive types, got array".into(),518		)),519		(Val::Obj(_), Val::Obj(_)) => throw!(RuntimeError(520			"primitiveEquals operates on primitive types, got object".into(),521		)),522		(a, b) if is_function_like(&a) && is_function_like(&b) => {523			throw!(RuntimeError("cannot test equality of functions".into()))524		}525		(_, _) => false,526	})527}528529/// Native implementation of `std.equals`530pub fn equals(val_a: &Val, val_b: &Val) -> Result<bool> {531	if val_a.value_type() != val_b.value_type() {532		return Ok(false);533	}534	match (val_a, val_b) {535		// Cant test for ptr equality, because all fields needs to be evaluated536		(Val::Arr(a), Val::Arr(b)) => {537			if a.len() != b.len() {538				return Ok(false);539			}540			for (a, b) in a.iter().zip(b.iter()) {541				if !equals(&a?, &b?)? {542					return Ok(false);543				}544			}545			Ok(true)546		}547		(Val::Obj(a), Val::Obj(b)) => {548			let fields = a.visible_fields();549			if fields != b.visible_fields() {550				return Ok(false);551			}552			for field in fields {553				if !equals(&a.get(field.clone())?.unwrap(), &b.get(field)?.unwrap())? {554					return Ok(false);555				}556			}557			Ok(true)558		}559		(a, b) => Ok(primitive_equals(&a, &b)?),560	}561}
modifiedcrates/jrsonnet-parser/src/expr.rsdiffbeforeafterboth
--- a/crates/jrsonnet-parser/src/expr.rs
+++ b/crates/jrsonnet-parser/src/expr.rs
@@ -97,6 +97,7 @@
 	Mul,
 	Div,
 
+	/// Implemented as intrinsic, put here for completeness
 	Mod,
 
 	Add,