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

difftreelog

refactor Option<&ExprLocation> -> &Option<_>

Yaroslav Bolyukin2021-01-24parent: #a16a15d.patch.diff
in: master

6 files changed

modifiedcrates/jrsonnet-evaluator/src/builtin/mod.rsdiffbeforeafterboth
--- a/crates/jrsonnet-evaluator/src/builtin/mod.rs
+++ b/crates/jrsonnet-evaluator/src/builtin/mod.rs
@@ -22,7 +22,7 @@
 
 fn std_format(str: IStr, vals: Val) -> Result<Val> {
 	push(
-		&Some(ExprLocation(Rc::from(PathBuf::from("std.jsonnet")), 0, 0)),
+		Some(&ExprLocation(Rc::from(PathBuf::from("std.jsonnet")), 0, 0)),
 		|| format!("std.format of {}", str),
 		|| {
 			Ok(match vals {
@@ -34,7 +34,7 @@
 	)
 }
 
-type Builtin = fn(context: Context, loc: &Option<ExprLocation>, args: &ArgsDesc) -> Result<Val>;
+type Builtin = fn(context: Context, loc: Option<&ExprLocation>, args: &ArgsDesc) -> Result<Val>;
 
 type BuiltinsType = HashMap<Box<str>, Builtin>;
 
@@ -78,7 +78,7 @@
 	};
 }
 
-fn builtin_length(context: Context, _loc: &Option<ExprLocation>, args: &ArgsDesc) -> Result<Val> {
+fn builtin_length(context: Context, _loc: Option<&ExprLocation>, args: &ArgsDesc) -> Result<Val> {
 	parse_args!(context, "length", args, 1, [
 		0, x: ty!((string | object | array));
 	], {
@@ -96,7 +96,7 @@
 	})
 }
 
-fn builtin_type(context: Context, _loc: &Option<ExprLocation>, args: &ArgsDesc) -> Result<Val> {
+fn builtin_type(context: Context, _loc: Option<&ExprLocation>, args: &ArgsDesc) -> Result<Val> {
 	parse_args!(context, "type", args, 1, [
 		0, x: ty!(any);
 	], {
@@ -106,7 +106,7 @@
 
 fn builtin_make_array(
 	context: Context,
-	_loc: &Option<ExprLocation>,
+	_loc: Option<&ExprLocation>,
 	args: &ArgsDesc,
 ) -> Result<Val> {
 	parse_args!(context, "makeArray", args, 2, [
@@ -126,7 +126,7 @@
 
 fn builtin_codepoint(
 	context: Context,
-	_loc: &Option<ExprLocation>,
+	_loc: Option<&ExprLocation>,
 	args: &ArgsDesc,
 ) -> Result<Val> {
 	parse_args!(context, "codepoint", args, 1, [
@@ -138,7 +138,7 @@
 
 fn builtin_object_fields_ex(
 	context: Context,
-	_loc: &Option<ExprLocation>,
+	_loc: Option<&ExprLocation>,
 	args: &ArgsDesc,
 ) -> Result<Val> {
 	parse_args!(context, "objectFieldsEx", args, 2, [
@@ -157,7 +157,7 @@
 
 fn builtin_object_has_ex(
 	context: Context,
-	_loc: &Option<ExprLocation>,
+	_loc: Option<&ExprLocation>,
 	args: &ArgsDesc,
 ) -> Result<Val> {
 	parse_args!(context, "objectHasEx", args, 3, [
@@ -175,7 +175,7 @@
 }
 
 // faster
-fn builtin_slice(context: Context, _loc: &Option<ExprLocation>, args: &ArgsDesc) -> Result<Val> {
+fn builtin_slice(context: Context, _loc: Option<&ExprLocation>, args: &ArgsDesc) -> Result<Val> {
 	parse_args!(context, "slice", args, 4, [
 		0, indexable: ty!((string | array));
 		1, index: ty!((number | null));
@@ -216,7 +216,7 @@
 // faster
 fn builtin_primitive_equals(
 	context: Context,
-	_loc: &Option<ExprLocation>,
+	_loc: Option<&ExprLocation>,
 	args: &ArgsDesc,
 ) -> Result<Val> {
 	parse_args!(context, "primitiveEquals", args, 2, [
@@ -228,7 +228,7 @@
 }
 
 // faster
-fn builtin_equals(context: Context, _loc: &Option<ExprLocation>, args: &ArgsDesc) -> Result<Val> {
+fn builtin_equals(context: Context, _loc: Option<&ExprLocation>, args: &ArgsDesc) -> Result<Val> {
 	parse_args!(context, "equals", args, 2, [
 		0, a: ty!(any);
 		1, b: ty!(any);
@@ -237,7 +237,7 @@
 	})
 }
 
-fn builtin_modulo(context: Context, _loc: &Option<ExprLocation>, args: &ArgsDesc) -> Result<Val> {
+fn builtin_modulo(context: Context, _loc: Option<&ExprLocation>, args: &ArgsDesc) -> Result<Val> {
 	parse_args!(context, "modulo", args, 2, [
 		0, a: ty!(number) => Val::Num;
 		1, b: ty!(number) => Val::Num;
@@ -246,7 +246,7 @@
 	})
 }
 
-fn builtin_mod(context: Context, _loc: &Option<ExprLocation>, args: &ArgsDesc) -> Result<Val> {
+fn builtin_mod(context: Context, _loc: Option<&ExprLocation>, args: &ArgsDesc) -> Result<Val> {
 	parse_args!(context, "mod", args, 2, [
 		0, a: ty!((number | string));
 		1, b: ty!(any);
@@ -259,7 +259,7 @@
 	})
 }
 
-fn builtin_floor(context: Context, _loc: &Option<ExprLocation>, args: &ArgsDesc) -> Result<Val> {
+fn builtin_floor(context: Context, _loc: Option<&ExprLocation>, args: &ArgsDesc) -> Result<Val> {
 	parse_args!(context, "floor", args, 1, [
 		0, x: ty!(number) => Val::Num;
 	], {
@@ -267,7 +267,7 @@
 	})
 }
 
-fn builtin_log(context: Context, _loc: &Option<ExprLocation>, args: &ArgsDesc) -> Result<Val> {
+fn builtin_log(context: Context, _loc: Option<&ExprLocation>, args: &ArgsDesc) -> Result<Val> {
 	parse_args!(context, "log", args, 1, [
 		0, n: ty!(number) => Val::Num;
 	], {
@@ -275,7 +275,7 @@
 	})
 }
 
-fn builtin_pow(context: Context, _loc: &Option<ExprLocation>, args: &ArgsDesc) -> Result<Val> {
+fn builtin_pow(context: Context, _loc: Option<&ExprLocation>, args: &ArgsDesc) -> Result<Val> {
 	parse_args!(context, "pow", args, 2, [
 		0, x: ty!(number) => Val::Num;
 		1, n: ty!(number) => Val::Num;
@@ -284,7 +284,7 @@
 	})
 }
 
-fn builtin_ext_var(context: Context, _loc: &Option<ExprLocation>, args: &ArgsDesc) -> Result<Val> {
+fn builtin_ext_var(context: Context, _loc: Option<&ExprLocation>, args: &ArgsDesc) -> Result<Val> {
 	parse_args!(context, "extVar", args, 1, [
 		0, x: ty!(string) => Val::Str;
 	], {
@@ -292,7 +292,7 @@
 	})
 }
 
-fn builtin_native(context: Context, _loc: &Option<ExprLocation>, args: &ArgsDesc) -> Result<Val> {
+fn builtin_native(context: Context, _loc: Option<&ExprLocation>, args: &ArgsDesc) -> Result<Val> {
 	parse_args!(context, "native", args, 1, [
 		0, x: ty!(string) => Val::Str;
 	], {
@@ -300,7 +300,7 @@
 	})
 }
 
-fn builtin_filter(context: Context, _loc: &Option<ExprLocation>, args: &ArgsDesc) -> Result<Val> {
+fn builtin_filter(context: Context, _loc: Option<&ExprLocation>, args: &ArgsDesc) -> Result<Val> {
 	parse_args!(context, "filter", args, 2, [
 		0, func: ty!(function) => Val::Func;
 		1, arr: ty!(array) => Val::Arr;
@@ -318,7 +318,7 @@
 	})
 }
 
-fn builtin_foldl(context: Context, _loc: &Option<ExprLocation>, args: &ArgsDesc) -> Result<Val> {
+fn builtin_foldl(context: Context, _loc: Option<&ExprLocation>, args: &ArgsDesc) -> Result<Val> {
 	parse_args!(context, "foldl", args, 3, [
 		0, func: ty!(function) => Val::Func;
 		1, arr: ty!(array) => Val::Arr;
@@ -332,7 +332,7 @@
 	})
 }
 
-fn builtin_foldr(context: Context, _loc: &Option<ExprLocation>, args: &ArgsDesc) -> Result<Val> {
+fn builtin_foldr(context: Context, _loc: Option<&ExprLocation>, args: &ArgsDesc) -> Result<Val> {
 	parse_args!(context, "foldr", args, 3, [
 		0, func: ty!(function) => Val::Func;
 		1, arr: ty!(array) => Val::Arr;
@@ -349,7 +349,7 @@
 #[allow(non_snake_case)]
 fn builtin_sort_impl(
 	context: Context,
-	_loc: &Option<ExprLocation>,
+	_loc: Option<&ExprLocation>,
 	args: &ArgsDesc,
 ) -> Result<Val> {
 	parse_args!(context, "sort", args, 2, [
@@ -364,7 +364,7 @@
 }
 
 // faster
-fn builtin_format(context: Context, _loc: &Option<ExprLocation>, args: &ArgsDesc) -> Result<Val> {
+fn builtin_format(context: Context, _loc: Option<&ExprLocation>, args: &ArgsDesc) -> Result<Val> {
 	parse_args!(context, "format", args, 2, [
 		0, str: ty!(string) => Val::Str;
 		1, vals: ty!(any)
@@ -373,7 +373,7 @@
 	})
 }
 
-fn builtin_range(context: Context, _loc: &Option<ExprLocation>, args: &ArgsDesc) -> Result<Val> {
+fn builtin_range(context: Context, _loc: Option<&ExprLocation>, args: &ArgsDesc) -> Result<Val> {
 	parse_args!(context, "range", args, 2, [
 		0, from: ty!(number) => Val::Num;
 		1, to: ty!(number) => Val::Num;
@@ -386,7 +386,7 @@
 	})
 }
 
-fn builtin_char(context: Context, _loc: &Option<ExprLocation>, args: &ArgsDesc) -> Result<Val> {
+fn builtin_char(context: Context, _loc: Option<&ExprLocation>, args: &ArgsDesc) -> Result<Val> {
 	parse_args!(context, "char", args, 1, [
 		0, n: ty!(number) => Val::Num;
 	], {
@@ -400,7 +400,7 @@
 
 fn builtin_encode_utf8(
 	context: Context,
-	_loc: &Option<ExprLocation>,
+	_loc: Option<&ExprLocation>,
 	args: &ArgsDesc,
 ) -> Result<Val> {
 	parse_args!(context, "encodeUTF8", args, 1, [
@@ -410,7 +410,7 @@
 	})
 }
 
-fn builtin_md5(context: Context, _loc: &Option<ExprLocation>, args: &ArgsDesc) -> Result<Val> {
+fn builtin_md5(context: Context, _loc: Option<&ExprLocation>, args: &ArgsDesc) -> Result<Val> {
 	parse_args!(context, "md5", args, 1, [
 		0, str: ty!(string) => Val::Str;
 	], {
@@ -418,7 +418,7 @@
 	})
 }
 
-fn builtin_trace(context: Context, loc: &Option<ExprLocation>, args: &ArgsDesc) -> Result<Val> {
+fn builtin_trace(context: Context, loc: Option<&ExprLocation>, args: &ArgsDesc) -> Result<Val> {
 	parse_args!(context, "trace", args, 2, [
 		0, str: ty!(string) => Val::Str;
 		1, rest: ty!(any);
@@ -435,7 +435,7 @@
 	})
 }
 
-fn builtin_base64(context: Context, _loc: &Option<ExprLocation>, args: &ArgsDesc) -> Result<Val> {
+fn builtin_base64(context: Context, _loc: Option<&ExprLocation>, args: &ArgsDesc) -> Result<Val> {
 	parse_args!(context, "base64", args, 1, [
 		0, input: ty!((string | (Array<number>)));
 	], {
@@ -453,7 +453,7 @@
 	})
 }
 
-fn builtin_join(context: Context, _loc: &Option<ExprLocation>, args: &ArgsDesc) -> Result<Val> {
+fn builtin_join(context: Context, _loc: Option<&ExprLocation>, args: &ArgsDesc) -> Result<Val> {
 	parse_args!(context, "join", args, 2, [
 		0, sep: ty!((string | array));
 		1, arr: ty!(array) => Val::Arr;
@@ -513,7 +513,7 @@
 // faster
 fn builtin_escape_string_json(
 	context: Context,
-	_loc: &Option<ExprLocation>,
+	_loc: Option<&ExprLocation>,
 	args: &ArgsDesc,
 ) -> Result<Val> {
 	parse_args!(context, "escapeStringJson", args, 1, [
@@ -526,7 +526,7 @@
 // faster
 fn builtin_manifest_json_ex(
 	context: Context,
-	_loc: &Option<ExprLocation>,
+	_loc: Option<&ExprLocation>,
 	args: &ArgsDesc,
 ) -> Result<Val> {
 	parse_args!(context, "manifestJsonEx", args, 2, [
@@ -541,7 +541,7 @@
 }
 
 // faster
-fn builtin_reverse(context: Context, _loc: &Option<ExprLocation>, args: &ArgsDesc) -> Result<Val> {
+fn builtin_reverse(context: Context, _loc: Option<&ExprLocation>, args: &ArgsDesc) -> Result<Val> {
 	parse_args!(context, "reverse", args, 1, [
 		0, value: ty!(array) => Val::Arr;
 	], {
@@ -549,7 +549,7 @@
 	})
 }
 
-fn builtin_id(context: Context, _loc: &Option<ExprLocation>, args: &ArgsDesc) -> Result<Val> {
+fn builtin_id(context: Context, _loc: Option<&ExprLocation>, args: &ArgsDesc) -> Result<Val> {
 	parse_args!(context, "id", args, 1, [
 		0, v: ty!(any);
 	], {
@@ -560,7 +560,7 @@
 // faster
 fn builtin_str_replace(
 	context: Context,
-	_loc: &Option<ExprLocation>,
+	_loc: Option<&ExprLocation>,
 	args: &ArgsDesc,
 ) -> Result<Val> {
 	parse_args!(context, "strReplace", args, 3, [
@@ -583,10 +583,9 @@
 	})
 }
 
-#[allow(clippy::cognitive_complexity)]
 pub fn call_builtin(
 	context: Context,
-	loc: &Option<ExprLocation>,
+	loc: Option<&ExprLocation>,
 	name: &str,
 	args: &ArgsDesc,
 ) -> Result<Val> {
modifiedcrates/jrsonnet-evaluator/src/evaluate.rsdiffbeforeafterboth
--- a/crates/jrsonnet-evaluator/src/evaluate.rs
+++ b/crates/jrsonnet-evaluator/src/evaluate.rs
@@ -385,7 +385,7 @@
 	context: Context,
 	value: &LocExpr,
 	args: &ArgsDesc,
-	loc: &Option<ExprLocation>,
+	loc: Option<&ExprLocation>,
 	tailstrict: bool,
 ) -> Result<Val> {
 	let value = evaluate(context.clone(), value)?;
@@ -430,7 +430,7 @@
 		BinaryOp(v1, o, v2) => evaluate_binary_op_special(context, v1, *o, v2)?,
 		UnaryOp(o, v) => evaluate_unary_op(*o, &evaluate(context, v)?)?,
 		Var(name) => push(
-			loc,
+			loc.as_ref(),
 			|| format!("variable <{}>", name),
 			|| Ok(context.binding(name.clone())?.evaluate()?),
 		)?,
@@ -448,7 +448,7 @@
 				(Val::Obj(v), Val::Str(s)) => {
 					let sn = s.clone();
 					push(
-						loc,
+						loc.as_ref(),
 						|| format!("field <{}> access", sn),
 						|| {
 							if let Some(v) = v.get(s.clone())? {
@@ -540,14 +540,14 @@
 			&evaluate(context.clone(), s)?,
 			&Val::Obj(evaluate_object(context, t)?),
 		)?,
-		Apply(value, args, tailstrict) => evaluate_apply(context, value, args, loc, *tailstrict)?,
+		Apply(value, args, tailstrict) => evaluate_apply(context, value, args, loc.as_ref(), *tailstrict)?,
 		Function(params, body) => {
 			evaluate_method(context, "anonymous".into(), params.clone(), body.clone())
 		}
 		Intrinsic(name) => Val::Func(Rc::new(FuncVal::Intrinsic(name.clone()))),
 		AssertExpr(AssertStmt(value, msg), returned) => {
 			let assertion_result = push(
-				&value.1,
+				value.1.as_ref(),
 				|| "assertion condition".to_owned(),
 				|| {
 					evaluate(context.clone(), value)?
@@ -558,7 +558,7 @@
 				evaluate(context, returned)?
 			} else {
 				push(
-					&value.1,
+					value.1.as_ref(),
 					|| "assertion failure".to_owned(),
 					|| {
 						if let Some(msg) = msg {
@@ -571,7 +571,7 @@
 			}
 		}
 		ErrorStmt(e) => push(
-			loc,
+			loc.as_ref(),
 			|| "error statement".to_owned(),
 			|| {
 				throw!(RuntimeError(
@@ -585,7 +585,7 @@
 			cond_else,
 		} => {
 			if push(
-				loc,
+				loc.as_ref(),
 				|| "if condition".to_owned(),
 				|| evaluate(context.clone(), &cond.0)?.try_cast_bool("in if condition"),
 			)? {
@@ -605,7 +605,7 @@
 			let import_location = Rc::make_mut(&mut tmp);
 			import_location.pop();
 			push(
-				loc,
+				loc.as_ref(),
 				|| format!("import {:?}", path),
 				|| with_state(|s| s.import_file(import_location, path)),
 			)?
modifiedcrates/jrsonnet-evaluator/src/function.rsdiffbeforeafterboth
--- a/crates/jrsonnet-evaluator/src/function.rs
+++ b/crates/jrsonnet-evaluator/src/function.rs
@@ -160,7 +160,7 @@
 					throw!(IntrinsicArgumentReorderingIsNotSupportedYet);
 				}
 			}
-			let $name = push(&None, || format!("evaluating argument"), || {
+			let $name = push(None, || format!("evaluating argument"), || {
 				let value = evaluate($ctx.clone(), &$name.1)?;
 				$ty.check(&value)?;
 				Ok(value)
modifiedcrates/jrsonnet-evaluator/src/lib.rsdiffbeforeafterboth
--- a/crates/jrsonnet-evaluator/src/lib.rs
+++ b/crates/jrsonnet-evaluator/src/lib.rs
@@ -128,7 +128,7 @@
 	EVAL_STATE.with(|s| f(s.borrow().as_ref().unwrap()))
 }
 pub(crate) fn push<T>(
-	e: &Option<ExprLocation>,
+	e: Option<&ExprLocation>,
 	frame_desc: impl FnOnce() -> String,
 	f: impl FnOnce() -> Result<T>,
 ) -> Result<T> {
modifiedcrates/jrsonnet-evaluator/src/typed.rsdiffbeforeafterboth
--- a/crates/jrsonnet-evaluator/src/typed.rs
+++ b/crates/jrsonnet-evaluator/src/typed.rs
@@ -78,7 +78,7 @@
 }
 
 fn push_type(
-	location: &Option<ExprLocation>,
+	location: Option<&ExprLocation>,
 	error_reason: impl Fn() -> String,
 	path: impl Fn() -> ValuePathItem,
 	item: impl Fn() -> Result<()>,
@@ -162,7 +162,7 @@
 				Val::Arr(a) => {
 					for (i, item) in a.iter().enumerate() {
 						push_type(
-							&None,
+							None,
 							|| format!("array index {}", i),
 							|| ValuePathItem::Index(i as u64),
 							|| Ok(elem_type.check(&item.clone()?)?),
@@ -176,7 +176,7 @@
 				Val::Arr(a) => {
 					for (i, item) in a.iter().enumerate() {
 						push_type(
-							&None,
+							None,
 							|| format!("array index {}", i),
 							|| ValuePathItem::Index(i as u64),
 							|| Ok(elem_type.check(&item.clone()?)?),
@@ -191,7 +191,7 @@
 					for (k, v) in elems.iter() {
 						if let Some(got_v) = obj.get((*k).into())? {
 							push_type(
-								&None,
+								None,
 								|| format!("property {}", k),
 								|| ValuePathItem::Field((*k).into()),
 								|| v.check(&got_v),
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_interner::IStr;13use jrsonnet_parser::{el, Arg, ArgsDesc, Expr, ExprLocation, LiteralType, LocExpr, ParamsDesc};14use jrsonnet_types::ValType;15use std::{cell::RefCell, collections::HashMap, fmt::Debug, rc::Rc};1617enum LazyValInternals {18	Computed(Val),19	Waiting(Box<dyn Fn() -> Result<Val>>),20}21#[derive(Clone)]22pub struct LazyVal(Rc<RefCell<LazyValInternals>>);23impl LazyVal {24	pub fn new(f: Box<dyn Fn() -> Result<Val>>) -> Self {25		Self(Rc::new(RefCell::new(LazyValInternals::Waiting(f))))26	}27	pub fn new_resolved(val: Val) -> Self {28		Self(Rc::new(RefCell::new(LazyValInternals::Computed(val))))29	}30	pub fn evaluate(&self) -> Result<Val> {31		let new_value = match &*self.0.borrow() {32			LazyValInternals::Computed(v) => return Ok(v.clone()),33			LazyValInternals::Waiting(f) => f()?,34		};35		*self.0.borrow_mut() = LazyValInternals::Computed(new_value.clone());36		Ok(new_value)37	}38}3940#[macro_export]41macro_rules! lazy_val {42	($f: expr) => {43		$crate::LazyVal::new(Box::new($f))44	};45}46#[macro_export]47macro_rules! resolved_lazy_val {48	($f: expr) => {49		$crate::LazyVal::new_resolved($f)50	};51}52impl Debug for LazyVal {53	fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {54		write!(f, "Lazy")55	}56}57impl PartialEq for LazyVal {58	fn eq(&self, other: &Self) -> bool {59		Rc::ptr_eq(&self.0, &other.0)60	}61}6263#[derive(Debug, PartialEq)]64pub struct FuncDesc {65	pub name: IStr,66	pub ctx: Context,67	pub params: ParamsDesc,68	pub body: LocExpr,69}7071#[derive(Debug)]72pub enum FuncVal {73	/// Plain function implemented in jsonnet74	Normal(FuncDesc),75	/// Standard library function76	Intrinsic(IStr),77	/// Library functions implemented in native78	NativeExt(IStr, Rc<NativeCallback>),79}8081impl PartialEq for FuncVal {82	fn eq(&self, other: &Self) -> bool {83		match (self, other) {84			(Self::Normal(a), Self::Normal(b)) => a == b,85			(Self::Intrinsic(an), Self::Intrinsic(bn)) => an == bn,86			(Self::NativeExt(an, _), Self::NativeExt(bn, _)) => an == bn,87			(..) => false,88		}89	}90}91impl FuncVal {92	pub fn is_ident(&self) -> bool {93		matches!(&self, Self::Intrinsic(n) if n as &str == "id")94	}95	pub fn name(&self) -> IStr {96		match self {97			Self::Normal(normal) => normal.name.clone(),98			Self::Intrinsic(name) => format!("std.{}", name).into(),99			Self::NativeExt(n, _) => format!("native.{}", n).into(),100		}101	}102	pub fn evaluate(103		&self,104		call_ctx: Context,105		loc: &Option<ExprLocation>,106		args: &ArgsDesc,107		tailstrict: bool,108	) -> Result<Val> {109		match self {110			Self::Normal(func) => {111				let ctx = parse_function_call(112					call_ctx,113					Some(func.ctx.clone()),114					&func.params,115					args,116					tailstrict,117				)?;118				evaluate(ctx, &func.body)119			}120			Self::Intrinsic(name) => call_builtin(call_ctx, loc, name, args),121			Self::NativeExt(_name, handler) => {122				let args = parse_function_call(call_ctx, None, &handler.params, args, true)?;123				let mut out_args = Vec::with_capacity(handler.params.len());124				for p in handler.params.0.iter() {125					out_args.push(args.binding(p.0.clone())?.evaluate()?);126				}127				Ok(handler.call(&out_args)?)128			}129		}130	}131132	pub fn evaluate_map(133		&self,134		call_ctx: Context,135		args: &HashMap<IStr, Val>,136		tailstrict: bool,137	) -> Result<Val> {138		match self {139			Self::Normal(func) => {140				let ctx = parse_function_call_map(141					call_ctx,142					Some(func.ctx.clone()),143					&func.params,144					args,145					tailstrict,146				)?;147				evaluate(ctx, &func.body)148			}149			Self::Intrinsic(_) => todo!(),150			Self::NativeExt(_, _) => todo!(),151		}152	}153154	pub fn evaluate_values(&self, call_ctx: Context, args: &[Val]) -> Result<Val> {155		match self {156			Self::Normal(func) => {157				let ctx = place_args(call_ctx, Some(func.ctx.clone()), &func.params, args)?;158				evaluate(ctx, &func.body)159			}160			Self::Intrinsic(_) => todo!(),161			Self::NativeExt(_, _) => todo!(),162		}163	}164}165166#[derive(Clone)]167pub enum ManifestFormat {168	YamlStream(Box<ManifestFormat>),169	Yaml(usize),170	Json(usize),171	ToString,172	String,173}174175#[derive(Debug, Clone)]176pub enum ArrValue {177	Lazy(Rc<Vec<LazyVal>>),178	Eager(Rc<Vec<Val>>),179}180impl ArrValue {181	pub fn len(&self) -> usize {182		match self {183			ArrValue::Lazy(l) => l.len(),184			ArrValue::Eager(e) => e.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			ArrValue::Lazy(vec) => {195				if let Some(v) = vec.get(index) {196					Ok(Some(v.evaluate()?))197				} else {198					Ok(None)199				}200			}201			ArrValue::Eager(vec) => Ok(vec.get(index).cloned()),202		}203	}204205	pub fn get_lazy(&self, index: usize) -> Option<LazyVal> {206		match self {207			ArrValue::Lazy(vec) => vec.get(index).cloned(),208			ArrValue::Eager(vec) => vec209				.get(index)210				.cloned()211				.map(|val| LazyVal::new_resolved(val)),212		}213	}214215	pub fn evaluated(&self) -> Result<Rc<Vec<Val>>> {216		Ok(match self {217			ArrValue::Lazy(vec) => {218				let mut out = Vec::with_capacity(vec.len());219				for item in vec.iter() {220					out.push(item.evaluate()?);221				}222				Rc::new(out)223			}224			ArrValue::Eager(vec) => vec.clone(),225		})226	}227228	pub fn iter(&self) -> impl DoubleEndedIterator<Item = Result<Val>> + '_ {229		(0..self.len()).map(move |idx| match self {230			ArrValue::Lazy(l) => l[idx].evaluate(),231			ArrValue::Eager(e) => Ok(e[idx].clone()),232		})233	}234235	pub fn iter_lazy(&self) -> impl DoubleEndedIterator<Item = LazyVal> + '_ {236		(0..self.len()).map(move |idx| match self {237			ArrValue::Lazy(l) => l[idx].clone(),238			ArrValue::Eager(e) => LazyVal::new_resolved(e[idx].clone()),239		})240	}241242	pub fn reversed(self) -> Self {243		match self {244			ArrValue::Lazy(vec) => {245				let mut out = (&vec as &Vec<_>).clone();246				out.reverse();247				Self::Lazy(Rc::new(out))248			}249			ArrValue::Eager(vec) => {250				let mut out = (&vec as &Vec<_>).clone();251				out.reverse();252				Self::Eager(Rc::new(out))253			}254		}255	}256257	pub fn ptr_eq(a: &ArrValue, b: &ArrValue) -> bool {258		match (a, b) {259			(ArrValue::Lazy(a), ArrValue::Lazy(b)) => Rc::ptr_eq(a, b),260			(ArrValue::Eager(a), ArrValue::Eager(b)) => Rc::ptr_eq(a, b),261			_ => false,262		}263	}264}265266impl From<Vec<LazyVal>> for ArrValue {267	fn from(v: Vec<LazyVal>) -> Self {268		Self::Lazy(Rc::new(v))269	}270}271272impl From<Vec<Val>> for ArrValue {273	fn from(v: Vec<Val>) -> Self {274		Self::Eager(Rc::new(v))275	}276}277278#[derive(Debug, Clone)]279pub enum Val {280	Bool(bool),281	Null,282	Str(IStr),283	Num(f64),284	Arr(ArrValue),285	Obj(ObjValue),286	Func(Rc<FuncVal>),287}288289macro_rules! matches_unwrap {290	($e: expr, $p: pat, $r: expr) => {291		match $e {292			$p => $r,293			_ => panic!("no match"),294			}295	};296}297impl Val {298	/// Creates `Val::Num` after checking for numeric overflow.299	/// As numbers are `f64`, we can just check for their finity.300	pub fn new_checked_num(num: f64) -> Result<Self> {301		if num.is_finite() {302			Ok(Self::Num(num))303		} else {304			throw!(RuntimeError("overflow".into()))305		}306	}307308	pub fn assert_type(&self, context: &'static str, val_type: ValType) -> Result<()> {309		let this_type = self.value_type();310		if this_type != val_type {311			throw!(TypeMismatch(context, vec![val_type], this_type))312		} else {313			Ok(())314		}315	}316	pub fn unwrap_num(self) -> Result<f64> {317		Ok(matches_unwrap!(self, Self::Num(v), v))318	}319	pub fn unwrap_func(self) -> Result<Rc<FuncVal>> {320		Ok(matches_unwrap!(self, Self::Func(v), v))321	}322	pub fn try_cast_bool(self, context: &'static str) -> Result<bool> {323		self.assert_type(context, ValType::Bool)?;324		Ok(matches_unwrap!(self, Self::Bool(v), v))325	}326	pub fn try_cast_str(self, context: &'static str) -> Result<IStr> {327		self.assert_type(context, ValType::Str)?;328		Ok(matches_unwrap!(self, Self::Str(v), v))329	}330	pub fn try_cast_num(self, context: &'static str) -> Result<f64> {331		self.assert_type(context, ValType::Num)?;332		self.unwrap_num()333	}334	pub fn value_type(&self) -> ValType {335		match self {336			Self::Str(..) => ValType::Str,337			Self::Num(..) => ValType::Num,338			Self::Arr(..) => ValType::Arr,339			Self::Obj(..) => ValType::Obj,340			Self::Bool(_) => ValType::Bool,341			Self::Null => ValType::Null,342			Self::Func(..) => ValType::Func,343		}344	}345346	pub fn to_string(&self) -> Result<IStr> {347		Ok(match self {348			Self::Bool(true) => "true".into(),349			Self::Bool(false) => "false".into(),350			Self::Null => "null".into(),351			Self::Str(s) => s.clone(),352			v => manifest_json_ex(353				&v,354				&ManifestJsonOptions {355					padding: "",356					mtype: ManifestType::ToString,357				},358			)?359			.into(),360		})361	}362363	/// Expects value to be object, outputs (key, manifested value) pairs364	pub fn manifest_multi(&self, ty: &ManifestFormat) -> Result<Vec<(IStr, IStr)>> {365		let obj = match self {366			Self::Obj(obj) => obj,367			_ => throw!(MultiManifestOutputIsNotAObject),368		};369		let keys = obj.visible_fields();370		let mut out = Vec::with_capacity(keys.len());371		for key in keys {372			let value = obj373				.get(key.clone())?374				.expect("item in object")375				.manifest(ty)?;376			out.push((key, value));377		}378		Ok(out)379	}380381	/// Expects value to be array, outputs manifested values382	pub fn manifest_stream(&self, ty: &ManifestFormat) -> Result<Vec<IStr>> {383		let arr = match self {384			Self::Arr(a) => a,385			_ => throw!(StreamManifestOutputIsNotAArray),386		};387		let mut out = Vec::with_capacity(arr.len());388		for i in arr.iter() {389			out.push(i?.manifest(ty)?);390		}391		Ok(out)392	}393394	pub fn manifest(&self, ty: &ManifestFormat) -> Result<IStr> {395		Ok(match ty {396			ManifestFormat::YamlStream(format) => {397				let arr = match self {398					Self::Arr(a) => a,399					_ => throw!(StreamManifestOutputIsNotAArray),400				};401				let mut out = String::new();402403				match format as &ManifestFormat {404					ManifestFormat::YamlStream(_) => throw!(StreamManifestOutputCannotBeRecursed),405					ManifestFormat::String => throw!(StreamManifestCannotNestString),406					_ => {}407				};408409				if !arr.is_empty() {410					for v in arr.iter() {411						out.push_str("---\n");412						out.push_str(&v?.manifest(format)?);413						out.push('\n');414					}415					out.push_str("...");416				}417418				out.into()419			}420			ManifestFormat::Yaml(padding) => self.to_yaml(*padding)?,421			ManifestFormat::Json(padding) => self.to_json(*padding)?,422			ManifestFormat::ToString => self.to_string()?,423			ManifestFormat::String => match self {424				Self::Str(s) => s.clone(),425				_ => throw!(StringManifestOutputIsNotAString),426			},427		})428	}429430	/// For manifestification431	pub fn to_json(&self, padding: usize) -> Result<IStr> {432		manifest_json_ex(433			self,434			&ManifestJsonOptions {435				padding: &" ".repeat(padding),436				mtype: if padding == 0 {437					ManifestType::Minify438				} else {439					ManifestType::Manifest440				},441			},442		)443		.map(|s| s.into())444	}445446	/// Calls `std.manifestJson`447	#[cfg(feature = "faster")]448	pub fn to_std_json(&self, padding: usize) -> Result<Rc<str>> {449		manifest_json_ex(450			self,451			&ManifestJsonOptions {452				padding: &" ".repeat(padding),453				mtype: ManifestType::Std,454			},455		)456		.map(|s| s.into())457	}458459	/// Calls `std.manifestJson`460	#[cfg(not(feature = "faster"))]461	pub fn to_std_json(&self, padding: usize) -> Result<Rc<str>> {462		with_state(|s| {463			let ctx = s464				.create_default_context()?465				.with_var("__tmp__to_json__".into(), self.clone())?;466			Ok(evaluate(467				ctx,468				&el!(Expr::Apply(469					el!(Expr::Index(470						el!(Expr::Var("std".into())),471						el!(Expr::Str("manifestJsonEx".into()))472					)),473					ArgsDesc(vec![474						Arg(None, el!(Expr::Var("__tmp__to_json__".into()))),475						Arg(None, el!(Expr::Str(" ".repeat(padding).into())))476					]),477					false478				)),479			)?480			.try_cast_str("to json")?)481		})482	}483	pub fn to_yaml(&self, padding: usize) -> Result<IStr> {484		with_state(|s| {485			let ctx = s486				.create_default_context()?487				.with_var("__tmp__to_json__".into(), self.clone());488			Ok(evaluate(489				ctx,490				&el!(Expr::Apply(491					el!(Expr::Index(492						el!(Expr::Var("std".into())),493						el!(Expr::Str("manifestYamlDoc".into()))494					)),495					ArgsDesc(vec![496						Arg(None, el!(Expr::Var("__tmp__to_json__".into()))),497						Arg(498							None,499							el!(Expr::Literal(if padding != 0 {500								LiteralType::True501							} else {502								LiteralType::False503							}))504						)505					]),506					false507				)),508			)?509			.try_cast_str("to json")?)510		})511	}512}513514const fn is_function_like(val: &Val) -> bool {515	matches!(val, Val::Func(_))516}517518/// Native implementation of `std.primitiveEquals`519pub fn primitive_equals(val_a: &Val, val_b: &Val) -> Result<bool> {520	Ok(match (val_a, val_b) {521		(Val::Bool(a), Val::Bool(b)) => a == b,522		(Val::Null, Val::Null) => true,523		(Val::Str(a), Val::Str(b)) => a == b,524		(Val::Num(a), Val::Num(b)) => (a - b).abs() <= f64::EPSILON,525		(Val::Arr(_), Val::Arr(_)) => throw!(RuntimeError(526			"primitiveEquals operates on primitive types, got array".into(),527		)),528		(Val::Obj(_), Val::Obj(_)) => throw!(RuntimeError(529			"primitiveEquals operates on primitive types, got object".into(),530		)),531		(a, b) if is_function_like(&a) && is_function_like(&b) => {532			throw!(RuntimeError("cannot test equality of functions".into()))533		}534		(_, _) => false,535	})536}537538/// Native implementation of `std.equals`539pub fn equals(val_a: &Val, val_b: &Val) -> Result<bool> {540	if val_a.value_type() != val_b.value_type() {541		return Ok(false);542	}543	match (val_a, val_b) {544		(Val::Arr(a), Val::Arr(b)) => {545			if ArrValue::ptr_eq(a, b) {546				return Ok(true);547			}548			if a.len() != b.len() {549				return Ok(false);550			}551			for (a, b) in a.iter().zip(b.iter()) {552				if !equals(&a?, &b?)? {553					return Ok(false);554				}555			}556			Ok(true)557		}558		(Val::Obj(a), Val::Obj(b)) => {559			if ObjValue::ptr_eq(a, b) {560				return Ok(true);561			}562			let fields = a.visible_fields();563			if fields != b.visible_fields() {564				return Ok(false);565			}566			for field in fields {567				if !equals(&a.get(field.clone())?.unwrap(), &b.get(field)?.unwrap())? {568					return Ok(false);569				}570			}571			Ok(true)572		}573		(a, b) => Ok(primitive_equals(&a, &b)?),574	}575}
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_interner::IStr;13use jrsonnet_parser::{el, Arg, ArgsDesc, Expr, ExprLocation, LiteralType, LocExpr, ParamsDesc};14use jrsonnet_types::ValType;15use std::{cell::RefCell, collections::HashMap, fmt::Debug, rc::Rc};1617enum LazyValInternals {18	Computed(Val),19	Waiting(Box<dyn Fn() -> Result<Val>>),20}21#[derive(Clone)]22pub struct LazyVal(Rc<RefCell<LazyValInternals>>);23impl LazyVal {24	pub fn new(f: Box<dyn Fn() -> Result<Val>>) -> Self {25		Self(Rc::new(RefCell::new(LazyValInternals::Waiting(f))))26	}27	pub fn new_resolved(val: Val) -> Self {28		Self(Rc::new(RefCell::new(LazyValInternals::Computed(val))))29	}30	pub fn evaluate(&self) -> Result<Val> {31		let new_value = match &*self.0.borrow() {32			LazyValInternals::Computed(v) => return Ok(v.clone()),33			LazyValInternals::Waiting(f) => f()?,34		};35		*self.0.borrow_mut() = LazyValInternals::Computed(new_value.clone());36		Ok(new_value)37	}38}3940#[macro_export]41macro_rules! lazy_val {42	($f: expr) => {43		$crate::LazyVal::new(Box::new($f))44	};45}46#[macro_export]47macro_rules! resolved_lazy_val {48	($f: expr) => {49		$crate::LazyVal::new_resolved($f)50	};51}52impl Debug for LazyVal {53	fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {54		write!(f, "Lazy")55	}56}57impl PartialEq for LazyVal {58	fn eq(&self, other: &Self) -> bool {59		Rc::ptr_eq(&self.0, &other.0)60	}61}6263#[derive(Debug, PartialEq)]64pub struct FuncDesc {65	pub name: IStr,66	pub ctx: Context,67	pub params: ParamsDesc,68	pub body: LocExpr,69}7071#[derive(Debug)]72pub enum FuncVal {73	/// Plain function implemented in jsonnet74	Normal(FuncDesc),75	/// Standard library function76	Intrinsic(IStr),77	/// Library functions implemented in native78	NativeExt(IStr, Rc<NativeCallback>),79}8081impl PartialEq for FuncVal {82	fn eq(&self, other: &Self) -> bool {83		match (self, other) {84			(Self::Normal(a), Self::Normal(b)) => a == b,85			(Self::Intrinsic(an), Self::Intrinsic(bn)) => an == bn,86			(Self::NativeExt(an, _), Self::NativeExt(bn, _)) => an == bn,87			(..) => false,88		}89	}90}91impl FuncVal {92	pub fn is_ident(&self) -> bool {93		matches!(&self, Self::Intrinsic(n) if n as &str == "id")94	}95	pub fn name(&self) -> IStr {96		match self {97			Self::Normal(normal) => normal.name.clone(),98			Self::Intrinsic(name) => format!("std.{}", name).into(),99			Self::NativeExt(n, _) => format!("native.{}", n).into(),100		}101	}102	pub fn evaluate(103		&self,104		call_ctx: Context,105		loc: Option<&ExprLocation>,106		args: &ArgsDesc,107		tailstrict: bool,108	) -> Result<Val> {109		match self {110			Self::Normal(func) => {111				let ctx = parse_function_call(112					call_ctx,113					Some(func.ctx.clone()),114					&func.params,115					args,116					tailstrict,117				)?;118				evaluate(ctx, &func.body)119			}120			Self::Intrinsic(name) => call_builtin(call_ctx, loc, name, args),121			Self::NativeExt(_name, handler) => {122				let args = parse_function_call(call_ctx, None, &handler.params, args, true)?;123				let mut out_args = Vec::with_capacity(handler.params.len());124				for p in handler.params.0.iter() {125					out_args.push(args.binding(p.0.clone())?.evaluate()?);126				}127				Ok(handler.call(&out_args)?)128			}129		}130	}131132	pub fn evaluate_map(133		&self,134		call_ctx: Context,135		args: &HashMap<IStr, Val>,136		tailstrict: bool,137	) -> Result<Val> {138		match self {139			Self::Normal(func) => {140				let ctx = parse_function_call_map(141					call_ctx,142					Some(func.ctx.clone()),143					&func.params,144					args,145					tailstrict,146				)?;147				evaluate(ctx, &func.body)148			}149			Self::Intrinsic(_) => todo!(),150			Self::NativeExt(_, _) => todo!(),151		}152	}153154	pub fn evaluate_values(&self, call_ctx: Context, args: &[Val]) -> Result<Val> {155		match self {156			Self::Normal(func) => {157				let ctx = place_args(call_ctx, Some(func.ctx.clone()), &func.params, args)?;158				evaluate(ctx, &func.body)159			}160			Self::Intrinsic(_) => todo!(),161			Self::NativeExt(_, _) => todo!(),162		}163	}164}165166#[derive(Clone)]167pub enum ManifestFormat {168	YamlStream(Box<ManifestFormat>),169	Yaml(usize),170	Json(usize),171	ToString,172	String,173}174175#[derive(Debug, Clone)]176pub enum ArrValue {177	Lazy(Rc<Vec<LazyVal>>),178	Eager(Rc<Vec<Val>>),179}180impl ArrValue {181	pub fn len(&self) -> usize {182		match self {183			ArrValue::Lazy(l) => l.len(),184			ArrValue::Eager(e) => e.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			ArrValue::Lazy(vec) => {195				if let Some(v) = vec.get(index) {196					Ok(Some(v.evaluate()?))197				} else {198					Ok(None)199				}200			}201			ArrValue::Eager(vec) => Ok(vec.get(index).cloned()),202		}203	}204205	pub fn get_lazy(&self, index: usize) -> Option<LazyVal> {206		match self {207			ArrValue::Lazy(vec) => vec.get(index).cloned(),208			ArrValue::Eager(vec) => vec209				.get(index)210				.cloned()211				.map(|val| LazyVal::new_resolved(val)),212		}213	}214215	pub fn evaluated(&self) -> Result<Rc<Vec<Val>>> {216		Ok(match self {217			ArrValue::Lazy(vec) => {218				let mut out = Vec::with_capacity(vec.len());219				for item in vec.iter() {220					out.push(item.evaluate()?);221				}222				Rc::new(out)223			}224			ArrValue::Eager(vec) => vec.clone(),225		})226	}227228	pub fn iter(&self) -> impl DoubleEndedIterator<Item = Result<Val>> + '_ {229		(0..self.len()).map(move |idx| match self {230			ArrValue::Lazy(l) => l[idx].evaluate(),231			ArrValue::Eager(e) => Ok(e[idx].clone()),232		})233	}234235	pub fn iter_lazy(&self) -> impl DoubleEndedIterator<Item = LazyVal> + '_ {236		(0..self.len()).map(move |idx| match self {237			ArrValue::Lazy(l) => l[idx].clone(),238			ArrValue::Eager(e) => LazyVal::new_resolved(e[idx].clone()),239		})240	}241242	pub fn reversed(self) -> Self {243		match self {244			ArrValue::Lazy(vec) => {245				let mut out = (&vec as &Vec<_>).clone();246				out.reverse();247				Self::Lazy(Rc::new(out))248			}249			ArrValue::Eager(vec) => {250				let mut out = (&vec as &Vec<_>).clone();251				out.reverse();252				Self::Eager(Rc::new(out))253			}254		}255	}256257	pub fn ptr_eq(a: &ArrValue, b: &ArrValue) -> bool {258		match (a, b) {259			(ArrValue::Lazy(a), ArrValue::Lazy(b)) => Rc::ptr_eq(a, b),260			(ArrValue::Eager(a), ArrValue::Eager(b)) => Rc::ptr_eq(a, b),261			_ => false,262		}263	}264}265266impl From<Vec<LazyVal>> for ArrValue {267	fn from(v: Vec<LazyVal>) -> Self {268		Self::Lazy(Rc::new(v))269	}270}271272impl From<Vec<Val>> for ArrValue {273	fn from(v: Vec<Val>) -> Self {274		Self::Eager(Rc::new(v))275	}276}277278#[derive(Debug, Clone)]279pub enum Val {280	Bool(bool),281	Null,282	Str(IStr),283	Num(f64),284	Arr(ArrValue),285	Obj(ObjValue),286	Func(Rc<FuncVal>),287}288289macro_rules! matches_unwrap {290	($e: expr, $p: pat, $r: expr) => {291		match $e {292			$p => $r,293			_ => panic!("no match"),294			}295	};296}297impl Val {298	/// Creates `Val::Num` after checking for numeric overflow.299	/// As numbers are `f64`, we can just check for their finity.300	pub fn new_checked_num(num: f64) -> Result<Self> {301		if num.is_finite() {302			Ok(Self::Num(num))303		} else {304			throw!(RuntimeError("overflow".into()))305		}306	}307308	pub fn assert_type(&self, context: &'static str, val_type: ValType) -> Result<()> {309		let this_type = self.value_type();310		if this_type != val_type {311			throw!(TypeMismatch(context, vec![val_type], this_type))312		} else {313			Ok(())314		}315	}316	pub fn unwrap_num(self) -> Result<f64> {317		Ok(matches_unwrap!(self, Self::Num(v), v))318	}319	pub fn unwrap_func(self) -> Result<Rc<FuncVal>> {320		Ok(matches_unwrap!(self, Self::Func(v), v))321	}322	pub fn try_cast_bool(self, context: &'static str) -> Result<bool> {323		self.assert_type(context, ValType::Bool)?;324		Ok(matches_unwrap!(self, Self::Bool(v), v))325	}326	pub fn try_cast_str(self, context: &'static str) -> Result<IStr> {327		self.assert_type(context, ValType::Str)?;328		Ok(matches_unwrap!(self, Self::Str(v), v))329	}330	pub fn try_cast_num(self, context: &'static str) -> Result<f64> {331		self.assert_type(context, ValType::Num)?;332		self.unwrap_num()333	}334	pub fn value_type(&self) -> ValType {335		match self {336			Self::Str(..) => ValType::Str,337			Self::Num(..) => ValType::Num,338			Self::Arr(..) => ValType::Arr,339			Self::Obj(..) => ValType::Obj,340			Self::Bool(_) => ValType::Bool,341			Self::Null => ValType::Null,342			Self::Func(..) => ValType::Func,343		}344	}345346	pub fn to_string(&self) -> Result<IStr> {347		Ok(match self {348			Self::Bool(true) => "true".into(),349			Self::Bool(false) => "false".into(),350			Self::Null => "null".into(),351			Self::Str(s) => s.clone(),352			v => manifest_json_ex(353				&v,354				&ManifestJsonOptions {355					padding: "",356					mtype: ManifestType::ToString,357				},358			)?359			.into(),360		})361	}362363	/// Expects value to be object, outputs (key, manifested value) pairs364	pub fn manifest_multi(&self, ty: &ManifestFormat) -> Result<Vec<(IStr, IStr)>> {365		let obj = match self {366			Self::Obj(obj) => obj,367			_ => throw!(MultiManifestOutputIsNotAObject),368		};369		let keys = obj.visible_fields();370		let mut out = Vec::with_capacity(keys.len());371		for key in keys {372			let value = obj373				.get(key.clone())?374				.expect("item in object")375				.manifest(ty)?;376			out.push((key, value));377		}378		Ok(out)379	}380381	/// Expects value to be array, outputs manifested values382	pub fn manifest_stream(&self, ty: &ManifestFormat) -> Result<Vec<IStr>> {383		let arr = match self {384			Self::Arr(a) => a,385			_ => throw!(StreamManifestOutputIsNotAArray),386		};387		let mut out = Vec::with_capacity(arr.len());388		for i in arr.iter() {389			out.push(i?.manifest(ty)?);390		}391		Ok(out)392	}393394	pub fn manifest(&self, ty: &ManifestFormat) -> Result<IStr> {395		Ok(match ty {396			ManifestFormat::YamlStream(format) => {397				let arr = match self {398					Self::Arr(a) => a,399					_ => throw!(StreamManifestOutputIsNotAArray),400				};401				let mut out = String::new();402403				match format as &ManifestFormat {404					ManifestFormat::YamlStream(_) => throw!(StreamManifestOutputCannotBeRecursed),405					ManifestFormat::String => throw!(StreamManifestCannotNestString),406					_ => {}407				};408409				if !arr.is_empty() {410					for v in arr.iter() {411						out.push_str("---\n");412						out.push_str(&v?.manifest(format)?);413						out.push('\n');414					}415					out.push_str("...");416				}417418				out.into()419			}420			ManifestFormat::Yaml(padding) => self.to_yaml(*padding)?,421			ManifestFormat::Json(padding) => self.to_json(*padding)?,422			ManifestFormat::ToString => self.to_string()?,423			ManifestFormat::String => match self {424				Self::Str(s) => s.clone(),425				_ => throw!(StringManifestOutputIsNotAString),426			},427		})428	}429430	/// For manifestification431	pub fn to_json(&self, padding: usize) -> Result<IStr> {432		manifest_json_ex(433			self,434			&ManifestJsonOptions {435				padding: &" ".repeat(padding),436				mtype: if padding == 0 {437					ManifestType::Minify438				} else {439					ManifestType::Manifest440				},441			},442		)443		.map(|s| s.into())444	}445446	/// Calls `std.manifestJson`447	#[cfg(feature = "faster")]448	pub fn to_std_json(&self, padding: usize) -> Result<Rc<str>> {449		manifest_json_ex(450			self,451			&ManifestJsonOptions {452				padding: &" ".repeat(padding),453				mtype: ManifestType::Std,454			},455		)456		.map(|s| s.into())457	}458459	/// Calls `std.manifestJson`460	#[cfg(not(feature = "faster"))]461	pub fn to_std_json(&self, padding: usize) -> Result<Rc<str>> {462		with_state(|s| {463			let ctx = s464				.create_default_context()?465				.with_var("__tmp__to_json__".into(), self.clone())?;466			Ok(evaluate(467				ctx,468				&el!(Expr::Apply(469					el!(Expr::Index(470						el!(Expr::Var("std".into())),471						el!(Expr::Str("manifestJsonEx".into()))472					)),473					ArgsDesc(vec![474						Arg(None, el!(Expr::Var("__tmp__to_json__".into()))),475						Arg(None, el!(Expr::Str(" ".repeat(padding).into())))476					]),477					false478				)),479			)?480			.try_cast_str("to json")?)481		})482	}483	pub fn to_yaml(&self, padding: usize) -> Result<IStr> {484		with_state(|s| {485			let ctx = s486				.create_default_context()?487				.with_var("__tmp__to_json__".into(), self.clone());488			Ok(evaluate(489				ctx,490				&el!(Expr::Apply(491					el!(Expr::Index(492						el!(Expr::Var("std".into())),493						el!(Expr::Str("manifestYamlDoc".into()))494					)),495					ArgsDesc(vec![496						Arg(None, el!(Expr::Var("__tmp__to_json__".into()))),497						Arg(498							None,499							el!(Expr::Literal(if padding != 0 {500								LiteralType::True501							} else {502								LiteralType::False503							}))504						)505					]),506					false507				)),508			)?509			.try_cast_str("to json")?)510		})511	}512}513514const fn is_function_like(val: &Val) -> bool {515	matches!(val, Val::Func(_))516}517518/// Native implementation of `std.primitiveEquals`519pub fn primitive_equals(val_a: &Val, val_b: &Val) -> Result<bool> {520	Ok(match (val_a, val_b) {521		(Val::Bool(a), Val::Bool(b)) => a == b,522		(Val::Null, Val::Null) => true,523		(Val::Str(a), Val::Str(b)) => a == b,524		(Val::Num(a), Val::Num(b)) => (a - b).abs() <= f64::EPSILON,525		(Val::Arr(_), Val::Arr(_)) => throw!(RuntimeError(526			"primitiveEquals operates on primitive types, got array".into(),527		)),528		(Val::Obj(_), Val::Obj(_)) => throw!(RuntimeError(529			"primitiveEquals operates on primitive types, got object".into(),530		)),531		(a, b) if is_function_like(&a) && is_function_like(&b) => {532			throw!(RuntimeError("cannot test equality of functions".into()))533		}534		(_, _) => false,535	})536}537538/// Native implementation of `std.equals`539pub fn equals(val_a: &Val, val_b: &Val) -> Result<bool> {540	if val_a.value_type() != val_b.value_type() {541		return Ok(false);542	}543	match (val_a, val_b) {544		(Val::Arr(a), Val::Arr(b)) => {545			if ArrValue::ptr_eq(a, b) {546				return Ok(true);547			}548			if a.len() != b.len() {549				return Ok(false);550			}551			for (a, b) in a.iter().zip(b.iter()) {552				if !equals(&a?, &b?)? {553					return Ok(false);554				}555			}556			Ok(true)557		}558		(Val::Obj(a), Val::Obj(b)) => {559			if ObjValue::ptr_eq(a, b) {560				return Ok(true);561			}562			let fields = a.visible_fields();563			if fields != b.visible_fields() {564				return Ok(false);565			}566			for field in fields {567				if !equals(&a.get(field.clone())?.unwrap(), &b.get(field)?.unwrap())? {568					return Ok(false);569				}570			}571			Ok(true)572		}573		(a, b) => Ok(primitive_equals(&a, &b)?),574	}575}