git.delta.rocks / jrsonnet / refs/commits / 3f8fb69418f4

difftreelog

style increase clippy linting level

Lach2020-08-25parent: #d13245a.patch.diff
in: master

15 files changed

modifiedcrates/jrsonnet-evaluator/src/builtin/format.rsdiffbeforeafterboth
--- a/crates/jrsonnet-evaluator/src/builtin/format.rs
+++ b/crates/jrsonnet-evaluator/src/builtin/format.rs
@@ -314,7 +314,7 @@
 	for _ in 0..zp2 {
 		out.push('0');
 	}
-	out.push_str(&prefix);
+	out.push_str(prefix);
 
 	for digit in digits.into_iter().rev() {
 		let ch = NUMBERS[digit as usize] as char;
@@ -399,7 +399,10 @@
 		}
 		return;
 	}
-	let frac = (n.fract() * 10.0_f64.powf(precision as f64) + 0.5).floor();
+	let frac = n
+		.fract()
+		.mul_add(10.0_f64.powf(precision as f64), 0.5)
+		.floor();
 	if trailing || frac > 0.0 {
 		out.push('.');
 		let mut frac_str = String::new();
@@ -605,7 +608,7 @@
 }
 
 pub fn format_arr(str: &str, mut values: &[Val]) -> Result<String> {
-	let codes = parse_codes(&str)?;
+	let codes = parse_codes(str)?;
 	let mut out = String::new();
 
 	for code in codes {
@@ -659,7 +662,7 @@
 }
 
 pub fn format_obj(str: &str, values: &ObjValue) -> Result<String> {
-	let codes = parse_codes(&str)?;
+	let codes = parse_codes(str)?;
 	let mut out = String::new();
 
 	for code in codes {
modifiedcrates/jrsonnet-evaluator/src/builtin/manifest.rsdiffbeforeafterboth
--- a/crates/jrsonnet-evaluator/src/builtin/manifest.rs
+++ b/crates/jrsonnet-evaluator/src/builtin/manifest.rs
@@ -20,7 +20,7 @@
 	pub mtype: ManifestType,
 }
 
-pub(crate) fn manifest_json_ex(val: &Val, options: &ManifestJsonOptions<'_>) -> Result<String> {
+pub fn manifest_json_ex(val: &Val, options: &ManifestJsonOptions<'_>) -> Result<String> {
 	let mut out = String::new();
 	manifest_json_ex_buf(val, &mut out, &mut String::new(), options)?;
 	Ok(out)
modifiedcrates/jrsonnet-evaluator/src/builtin/mod.rsdiffbeforeafterboth
--- a/crates/jrsonnet-evaluator/src/builtin/mod.rs
+++ b/crates/jrsonnet-evaluator/src/builtin/mod.rs
@@ -16,6 +16,7 @@
 pub mod manifest;
 pub mod sort;
 
+#[allow(clippy::cognitive_complexity)]
 pub fn call_builtin(
 	context: Context,
 	loc: &Option<ExprLocation>,
@@ -23,7 +24,7 @@
 	name: &str,
 	args: &ArgsDesc,
 ) -> Result<Val> {
-	Ok(match (ns, &name as &str) {
+	Ok(match (ns, name as &str) {
 		// arr/string/function
 		("std", "length") => parse_args!(context, "std.length", args, 1, [
 			0, x: [Val::Str|Val::Arr|Val::Obj], vec![ValType::Str, ValType::Arr, ValType::Obj];
modifiedcrates/jrsonnet-evaluator/src/builtin/stdlib.rsdiffbeforeafterboth
--- a/crates/jrsonnet-evaluator/src/builtin/stdlib.rs
+++ b/crates/jrsonnet-evaluator/src/builtin/stdlib.rs
@@ -22,7 +22,7 @@
 		}
 
 		jrsonnet_parser::parse(
-			&jrsonnet_stdlib::STDLIB_STR,
+			jrsonnet_stdlib::STDLIB_STR,
 			&ParserSettings {
 				loc_data: true,
 				file_name: Rc::new(PathBuf::from("std.jsonnet")),
modifiedcrates/jrsonnet-evaluator/src/ctx.rsdiffbeforeafterboth
--- a/crates/jrsonnet-evaluator/src/ctx.rs
+++ b/crates/jrsonnet-evaluator/src/ctx.rs
@@ -48,8 +48,8 @@
 		&self.0.super_obj
 	}
 
-	pub fn new() -> Context {
-		Context(Rc::new(ContextInternals {
+	pub fn new() -> Self {
+		Self(Rc::new(ContextInternals {
 			dollar: None,
 			this: None,
 			super_obj: None,
@@ -65,14 +65,14 @@
 			.cloned()
 			.ok_or_else(|| UnknownVariable(name))?)
 	}
-	pub fn into_future(self, ctx: FutureContext) -> Context {
+	pub fn into_future(self, ctx: FutureContext) -> Self {
 		{
 			ctx.0.borrow_mut().replace(self);
 		}
 		ctx.unwrap()
 	}
 
-	pub fn with_var(self, name: Rc<str>, value: Val) -> Context {
+	pub fn with_var(self, name: Rc<str>, value: Val) -> Self {
 		let mut new_bindings =
 			FxHashMap::with_capacity_and_hasher(1, BuildHasherDefault::default());
 		new_bindings.insert(name, resolved_lazy_val!(value));
@@ -85,7 +85,7 @@
 		new_dollar: Option<ObjValue>,
 		new_this: Option<ObjValue>,
 		new_super_obj: Option<ObjValue>,
-	) -> Context {
+	) -> Self {
 		match Rc::try_unwrap(self.0) {
 			Ok(mut ctx) => {
 				// Extended context aren't used by anything else, we can freely mutate it without cloning
@@ -101,7 +101,7 @@
 				if !new_bindings.is_empty() {
 					ctx.bindings = ctx.bindings.extend(new_bindings);
 				}
-				Context(Rc::new(ctx))
+				Self(Rc::new(ctx))
 			}
 			Err(ctx) => {
 				let dollar = new_dollar.or_else(|| ctx.dollar.clone());
@@ -112,7 +112,7 @@
 				} else {
 					ctx.bindings.clone().extend(new_bindings)
 				};
-				Context(Rc::new(ContextInternals {
+				Self(Rc::new(ContextInternals {
 					dollar,
 					this,
 					super_obj,
@@ -127,7 +127,7 @@
 		new_dollar: Option<ObjValue>,
 		new_this: Option<ObjValue>,
 		new_super_obj: Option<ObjValue>,
-	) -> Result<Context> {
+	) -> Result<Self> {
 		let this = new_this.or_else(|| self.0.this.clone());
 		let super_obj = new_super_obj.or_else(|| self.0.super_obj.clone());
 		let mut new =
modifiedcrates/jrsonnet-evaluator/src/error.rsdiffbeforeafterboth
--- a/crates/jrsonnet-evaluator/src/error.rs
+++ b/crates/jrsonnet-evaluator/src/error.rs
@@ -95,10 +95,10 @@
 		Self(Box::new((e, StackTrace(vec![]))))
 	}
 
-	pub fn error(&self) -> &Error {
+	pub const fn error(&self) -> &Error {
 		&(self.0).0
 	}
-	pub fn trace(&self) -> &StackTrace {
+	pub const fn trace(&self) -> &StackTrace {
 		&(self.0).1
 	}
 	pub fn trace_mut(&mut self) -> &mut StackTrace {
modifiedcrates/jrsonnet-evaluator/src/evaluate.rsdiffbeforeafterboth
--- a/crates/jrsonnet-evaluator/src/evaluate.rs
+++ b/crates/jrsonnet-evaluator/src/evaluate.rs
@@ -82,9 +82,9 @@
 	})
 }
 
-pub(crate) fn evaluate_add_op(a: &Val, b: &Val) -> Result<Val> {
+pub fn evaluate_add_op(a: &Val, b: &Val) -> Result<Val> {
 	Ok(match (a, b) {
-		(Val::Str(v1), Val::Str(v2)) => Val::Str(((**v1).to_owned() + &v2).into()),
+		(Val::Str(v1), Val::Str(v2)) => Val::Str(((**v1).to_owned() + v2).into()),
 
 		// Can't use generic json serialization way, because it depends on number to string concatenation (std.jsonnet:890)
 		(Val::Num(n), Val::Str(o)) => Val::Str(format!("{}{}", n, o).into()),
@@ -111,7 +111,7 @@
 	b: &LocExpr,
 ) -> Result<Val> {
 	Ok(
-		match (evaluate(context.clone(), &a)?.unwrap_if_lazy()?, op, b) {
+		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) => {
@@ -194,14 +194,14 @@
 	Ok(match specs.get(0) {
 		None => Some(vec![value(context)?]),
 		Some(CompSpec::IfSpec(IfSpecData(cond))) => {
-			if evaluate(context.clone(), &cond)?.try_cast_bool("if spec")? {
+			if evaluate(context.clone(), cond)?.try_cast_bool("if spec")? {
 				evaluate_comp(context, value, &specs[1..])?
 			} else {
 				None
 			}
 		}
 		Some(CompSpec::ForSpec(ForSpecData(var, expr))) => {
-			match evaluate(context.clone(), &expr)?.unwrap_if_lazy()? {
+			match evaluate(context.clone(), expr)?.unwrap_if_lazy()? {
 				Val::Arr(list) => {
 					let mut out = Vec::new();
 					for item in list.iter() {
@@ -258,7 +258,7 @@
 				visibility,
 				value,
 			}) => {
-				let name = evaluate_field_name(context.clone(), &name)?;
+				let name = evaluate_field_name(context.clone(), name)?;
 				if name.is_none() {
 					continue;
 				}
@@ -286,7 +286,7 @@
 				value,
 				..
 			}) => {
-				let name = evaluate_field_name(context.clone(), &name)?;
+				let name = evaluate_field_name(context.clone(), name)?;
 				if name.is_none() {
 					continue;
 				}
@@ -320,7 +320,7 @@
 
 pub fn evaluate_object(context: Context, object: &ObjBody) -> Result<ObjValue> {
 	Ok(match object {
-		ObjBody::MemberList(members) => evaluate_member_list_object(context, &members)?,
+		ObjBody::MemberList(members) => evaluate_member_list_object(context, members)?,
 		ObjBody::ObjComp(obj) => {
 			let future_this = FutureObjValue::new();
 			let mut new_members = HashMap::new();
@@ -437,7 +437,7 @@
 		Parened(e) => evaluate(context, e)?,
 		Str(v) => Val::Str(v.clone()),
 		Num(v) => Val::new_checked_num(*v)?,
-		BinaryOp(v1, o, v2) => evaluate_binary_op_special(context, &v1, *o, &v2)?,
+		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,
@@ -461,7 +461,7 @@
 				(Val::Obj(v), Val::Str(s)) => {
 					let sn = s.clone();
 					push(
-						&loc,
+						loc,
 						|| format!("field <{}> access", sn),
 						|| {
 							if let Some(v) = v.get(s.clone())? {
@@ -563,7 +563,7 @@
 				&value.1,
 				|| "assertion condition".to_owned(),
 				|| {
-					evaluate(context.clone(), &value)?
+					evaluate(context.clone(), value)?
 						.try_cast_bool("assertion condition should be of type `boolean`")
 				},
 			)?;
@@ -576,7 +576,7 @@
 			}
 		}
 		ErrorStmt(e) => push(
-			&loc,
+			loc,
 			|| "error statement".to_owned(),
 			|| {
 				throw!(RuntimeError(
@@ -610,7 +610,7 @@
 			push(
 				loc,
 				|| format!("import {:?}", path),
-				|| with_state(|s| s.import_file(&import_location, path)),
+				|| with_state(|s| s.import_file(import_location, path)),
 			)?
 		}
 		ImportStr(path) => {
@@ -620,7 +620,7 @@
 				.0;
 			let import_location = Rc::make_mut(&mut tmp);
 			import_location.pop();
-			Val::Str(with_state(|s| s.import_file_str(&import_location, path))?)
+			Val::Str(with_state(|s| s.import_file_str(import_location, path))?)
 		}
 		Literal(LiteralType::Super) => throw!(StandaloneSuper),
 	})
modifiedcrates/jrsonnet-evaluator/src/function.rsdiffbeforeafterboth
--- a/crates/jrsonnet-evaluator/src/function.rs
+++ b/crates/jrsonnet-evaluator/src/function.rs
@@ -75,7 +75,7 @@
 		let idx = params
 			.iter()
 			.position(|p| *p.0 == **name)
-			.ok_or_else(|| UnknownFunctionParameter((&name as &str).to_owned()))?;
+			.ok_or_else(|| UnknownFunctionParameter((name as &str).to_owned()))?;
 
 		if idx >= params.len() {
 			throw!(TooManyArgsFunctionHas(params.len()));
@@ -111,7 +111,7 @@
 	Ok(body_ctx.unwrap_or(ctx).extend(out, None, None, None))
 }
 
-pub(crate) fn place_args(
+pub fn place_args(
 	ctx: Context,
 	body_ctx: Option<Context>,
 	params: &ParamsDesc,
modifiedcrates/jrsonnet-evaluator/src/import.rsdiffbeforeafterboth
--- a/crates/jrsonnet-evaluator/src/import.rs
+++ b/crates/jrsonnet-evaluator/src/import.rs
@@ -41,6 +41,7 @@
 		panic!("`as_any($self)` is not supported by dummy resolver")
 	}
 }
+#[allow(clippy::use_self)]
 impl Default for Box<dyn ImportResolver> {
 	fn default() -> Self {
 		Box::new(DummyImportResolver)
modifiedcrates/jrsonnet-evaluator/src/integrations/serde.rsdiffbeforeafterboth
--- a/crates/jrsonnet-evaluator/src/integrations/serde.rs
+++ b/crates/jrsonnet-evaluator/src/integrations/serde.rs
@@ -14,10 +14,10 @@
 	type Error = LocError;
 	fn try_from(v: &Val) -> Result<Self> {
 		Ok(match v {
-			Val::Bool(b) => Value::Bool(*b),
-			Val::Null => Value::Null,
-			Val::Str(s) => Value::String((&s as &str).into()),
-			Val::Num(n) => Value::Number(if n.fract() <= f64::EPSILON {
+			Val::Bool(b) => Self::Bool(*b),
+			Val::Null => Self::Null,
+			Val::Str(s) => Self::String((s as &str).into()),
+			Val::Num(n) => Self::Number(if n.fract() <= f64::EPSILON {
 				(*n as i64).into()
 			} else {
 				Number::from_f64(*n).expect("to json number")
@@ -28,7 +28,7 @@
 				for item in a.iter() {
 					out.push(item.try_into()?);
 				}
-				Value::Array(out)
+				Self::Array(out)
 			}
 			Val::Obj(o) => {
 				let mut out = Map::new();
@@ -38,7 +38,7 @@
 						(&o.get(key)?.expect("field exists")).try_into()?,
 					);
 				}
-				Value::Object(out)
+				Self::Object(out)
 			}
 			Val::Func(_) => throw!(RuntimeError("tried to manifest function".into())),
 		})
@@ -48,16 +48,16 @@
 impl From<&Value> for Val {
 	fn from(v: &Value) -> Self {
 		match v {
-			Value::Null => Val::Null,
-			Value::Bool(v) => Val::Bool(*v),
-			Value::Number(n) => Val::Num(n.as_f64().expect("as f64")),
-			Value::String(s) => Val::Str((s as &str).into()),
+			Value::Null => Self::Null,
+			Value::Bool(v) => Self::Bool(*v),
+			Value::Number(n) => Self::Num(n.as_f64().expect("as f64")),
+			Value::String(s) => Self::Str((s as &str).into()),
 			Value::Array(a) => {
 				let mut out = Vec::with_capacity(a.len());
 				for v in a {
 					out.push(v.into());
 				}
-				Val::Arr(Rc::new(out))
+				Self::Arr(Rc::new(out))
 			}
 			Value::Object(o) => {
 				let mut entries = HashMap::with_capacity(o.len());
@@ -72,7 +72,7 @@
 						},
 					);
 				}
-				Val::Obj(ObjValue::new(None, Rc::new(entries)))
+				Self::Obj(ObjValue::new(None, Rc::new(entries)))
 			}
 		}
 	}
modifiedcrates/jrsonnet-evaluator/src/lib.rsdiffbeforeafterboth
--- a/crates/jrsonnet-evaluator/src/lib.rs
+++ b/crates/jrsonnet-evaluator/src/lib.rs
@@ -1,5 +1,6 @@
 #![cfg_attr(feature = "unstable", feature(stmt_expr_attributes))]
 #![allow(macro_expanded_macro_exports_accessed_by_absolute_paths)]
+#![warn(clippy::all, clippy::nursery)]
 
 mod builtin;
 mod ctx;
@@ -49,8 +50,8 @@
 impl LazyBinding {
 	pub fn evaluate(&self, this: Option<ObjValue>, super_obj: Option<ObjValue>) -> Result<LazyVal> {
 		match self {
-			LazyBinding::Bindable(v) => v(this, super_obj),
-			LazyBinding::Bound(v) => Ok(v.clone()),
+			Self::Bindable(v) => v(this, super_obj),
+			Self::Bound(v) => Ok(v.clone()),
 		}
 	}
 }
@@ -77,7 +78,7 @@
 }
 impl Default for EvaluationSettings {
 	fn default() -> Self {
-		EvaluationSettings {
+		Self {
 			max_stack: 200,
 			max_trace: 20,
 			globals: Default::default(),
@@ -130,7 +131,7 @@
 	f: impl FnOnce() -> Result<T>,
 ) -> Result<T> {
 	if let Some(v) = e {
-		with_state(|s| s.push(&v, frame_desc, f))
+		with_state(|s| s.push(v, frame_desc, f))
 	} else {
 		f()
 	}
@@ -359,10 +360,10 @@
 /// Raw methods evaluate passed values but don't perform TLA execution
 impl EvaluationState {
 	pub fn evaluate_file_raw(&self, name: &PathBuf) -> Result<Val> {
-		self.run_in_state(|| self.import_file(&std::env::current_dir().expect("cwd"), &name))
+		self.run_in_state(|| self.import_file(&std::env::current_dir().expect("cwd"), name))
 	}
 	pub fn evaluate_file_raw_nocwd(&self, name: &PathBuf) -> Result<Val> {
-		self.run_in_state(|| self.import_file(&PathBuf::from("."), &name))
+		self.run_in_state(|| self.import_file(&PathBuf::from("."), name))
 	}
 	/// Parses and evaluates the given snippet
 	pub fn evaluate_snippet_raw(&self, source: Rc<PathBuf>, code: Rc<str>) -> Result<Val> {
modifiedcrates/jrsonnet-evaluator/src/map.rsdiffbeforeafterboth
--- a/crates/jrsonnet-evaluator/src/map.rs
+++ b/crates/jrsonnet-evaluator/src/map.rs
@@ -15,10 +15,10 @@
 		match Rc::try_unwrap(self.0) {
 			Ok(mut map) => {
 				map.current.extend(new_layer);
-				LayeredHashMap(Rc::new(map))
+				Self(Rc::new(map))
 			}
-			Err(this) => LayeredHashMap(Rc::new(LayeredHashMapInternals {
-				parent: Some(LayeredHashMap(this)),
+			Err(this) => Self(Rc::new(LayeredHashMapInternals {
+				parent: Some(Self(this)),
 				current: new_layer,
 			})),
 		}
@@ -31,20 +31,20 @@
 	{
 		(self.0)
 			.current
-			.get(&key)
+			.get(key)
 			.or_else(|| self.0.parent.as_ref().and_then(|p| p.get(key)))
 	}
 }
 
 impl<K: Hash, V> Clone for LayeredHashMap<K, V> {
 	fn clone(&self) -> Self {
-		LayeredHashMap(self.0.clone())
+		Self(self.0.clone())
 	}
 }
 
 impl<K: Hash + Eq, V> Default for LayeredHashMap<K, V> {
 	fn default() -> Self {
-		LayeredHashMap(Rc::new(LayeredHashMapInternals {
+		Self(Rc::new(LayeredHashMapInternals {
 			parent: None,
 			current: FxHashMap::default(),
 		}))
modifiedcrates/jrsonnet-evaluator/src/obj.rsdiffbeforeafterboth
--- a/crates/jrsonnet-evaluator/src/obj.rs
+++ b/crates/jrsonnet-evaluator/src/obj.rs
@@ -47,23 +47,20 @@
 }
 
 impl ObjValue {
-	pub fn new(
-		super_obj: Option<ObjValue>,
-		this_entries: Rc<HashMap<Rc<str>, ObjMember>>,
-	) -> ObjValue {
-		ObjValue(Rc::new(ObjValueInternals {
+	pub fn new(super_obj: Option<Self>, this_entries: Rc<HashMap<Rc<str>, ObjMember>>) -> Self {
+		Self(Rc::new(ObjValueInternals {
 			super_obj,
 			this_entries,
 			value_cache: RefCell::new(HashMap::new()),
 		}))
 	}
-	pub fn new_empty() -> ObjValue {
+	pub fn new_empty() -> Self {
 		Self::new(None, Rc::new(HashMap::new()))
 	}
-	pub fn with_super(&self, super_obj: ObjValue) -> ObjValue {
+	pub fn with_super(&self, super_obj: Self) -> Self {
 		match &self.0.super_obj {
-			None => ObjValue::new(Some(super_obj), self.0.this_entries.clone()),
-			Some(v) => ObjValue::new(Some(v.with_super(super_obj)), self.0.this_entries.clone()),
+			None => Self::new(Some(super_obj), self.0.this_entries.clone()),
+			Some(v) => Self::new(Some(v.with_super(super_obj)), self.0.this_entries.clone()),
 		}
 	}
 	pub fn enum_fields(&self, handler: &impl Fn(&Rc<str>, &Visibility)) {
@@ -71,7 +68,7 @@
 			s.enum_fields(handler);
 		}
 		for (name, member) in self.0.this_entries.iter() {
-			handler(&name, &member.visibility);
+			handler(name, &member.visibility);
 		}
 	}
 	pub fn fields_visibility(&self) -> IndexMap<Rc<str>, bool> {
@@ -107,7 +104,7 @@
 	pub fn get(&self, key: Rc<str>) -> Result<Option<Val>> {
 		Ok(self.get_raw(key, self)?)
 	}
-	pub(crate) fn get_raw(&self, key: Rc<str>, real_this: &ObjValue) -> Result<Option<Val>> {
+	pub(crate) fn get_raw(&self, key: Rc<str>, real_this: &Self) -> Result<Option<Val>> {
 		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) {
@@ -135,7 +132,7 @@
 			.insert(cache_key, value.clone());
 		Ok(value)
 	}
-	fn evaluate_this(&self, v: &ObjMember, real_this: &ObjValue) -> Result<Val> {
+	fn evaluate_this(&self, v: &ObjMember, real_this: &Self) -> Result<Val> {
 		Ok(v.invoke
 			.evaluate(Some(real_this.clone()), self.0.super_obj.clone())?
 			.evaluate()?)
modifiedcrates/jrsonnet-evaluator/src/trace/mod.rsdiffbeforeafterboth
--- a/crates/jrsonnet-evaluator/src/trace/mod.rs
+++ b/crates/jrsonnet-evaluator/src/trace/mod.rs
@@ -17,9 +17,9 @@
 impl PathResolver {
 	pub fn resolve(&self, from: &PathBuf) -> String {
 		match self {
-			PathResolver::FileName => from.file_name().unwrap().to_string_lossy().into_owned(),
-			PathResolver::Absolute => from.to_string_lossy().into_owned(),
-			PathResolver::Relative(base) => {
+			Self::FileName => from.file_name().unwrap().to_string_lossy().into_owned(),
+			Self::Absolute => from.to_string_lossy().into_owned(),
+			Self::Relative(base) => {
 				if from.is_relative() {
 					return from.to_string_lossy().into_owned();
 				}
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, 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		LazyVal(Rc::new(RefCell::new(LazyValInternals::Waiting(f))))29	}30	pub fn new_resolved(val: Val) -> Self {31		LazyVal(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>, 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			(FuncVal::Normal(a), FuncVal::Normal(b)) => a == b,88			(FuncVal::Intrinsic(ans, an), FuncVal::Intrinsic(bns, bn)) => ans == bns && an == bn,89			(FuncVal::NativeExt(an, _), FuncVal::NativeExt(bn, _)) => an == bn,90			(..) => false,91		}92	}93}94impl FuncVal {95	pub fn is_ident(&self) -> bool {96		matches!(&self, FuncVal::Intrinsic(ns, n) if ns as &str == "std" && n as &str == "id")97	}98	pub fn name(&self) -> Rc<str> {99		match self {100			FuncVal::Normal(normal) => normal.name.clone(),101			FuncVal::Intrinsic(ns, name) => format!("intrinsic.{}.{}", ns, name).into(),102			FuncVal::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			FuncVal::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			FuncVal::Intrinsic(ns, name) => call_builtin(call_ctx, loc, &ns, &name, args),124			FuncVal::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			FuncVal::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			FuncVal::Intrinsic(_, _) => todo!(),153			FuncVal::NativeExt(_, _) => todo!(),154		}155	}156157	pub fn evaluate_values(&self, call_ctx: Context, args: &[Val]) -> Result<Val> {158		match self {159			FuncVal::Normal(func) => {160				let ctx = place_args(call_ctx, Some(func.ctx.clone()), &func.params, args)?;161				evaluate(ctx, &func.body)162			}163			FuncVal::Intrinsic(_, _) => todo!(),164			FuncVal::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 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	String,205}206207#[derive(Debug, Clone)]208pub enum Val {209	Bool(bool),210	Null,211	Str(Rc<str>),212	Num(f64),213	Lazy(LazyVal),214	Arr(Rc<Vec<Val>>),215	Obj(ObjValue),216	Func(Rc<FuncVal>),217}218219macro_rules! matches_unwrap {220	($e: expr, $p: pat, $r: expr) => {221		match $e {222			$p => $r,223			_ => panic!("no match"),224			}225	};226}227impl Val {228	/// Creates `Val::Num` after checking for numeric overflow.229	/// As numbers are `f64`, we can just check for their finity.230	pub fn new_checked_num(num: f64) -> Result<Val> {231		if num.is_finite() {232			Ok(Val::Num(num))233		} else {234			throw!(RuntimeError("overflow".into()))235		}236	}237238	pub fn assert_type(&self, context: &'static str, val_type: ValType) -> Result<()> {239		let this_type = self.value_type()?;240		if this_type != val_type {241			throw!(TypeMismatch(context, vec![val_type], this_type))242		} else {243			Ok(())244		}245	}246	pub fn try_cast_bool(self, context: &'static str) -> Result<bool> {247		self.assert_type(context, ValType::Bool)?;248		Ok(matches_unwrap!(self.unwrap_if_lazy()?, Val::Bool(v), v))249	}250	pub fn try_cast_str(self, context: &'static str) -> Result<Rc<str>> {251		self.assert_type(context, ValType::Str)?;252		Ok(matches_unwrap!(self.unwrap_if_lazy()?, Val::Str(v), v))253	}254	pub fn try_cast_num(self, context: &'static str) -> Result<f64> {255		self.assert_type(context, ValType::Num)?;256		Ok(matches_unwrap!(self.unwrap_if_lazy()?, Val::Num(v), v))257	}258	pub fn inplace_unwrap(&mut self) -> Result<()> {259		while let Val::Lazy(lazy) = self {260			*self = lazy.evaluate()?;261		}262		Ok(())263	}264	pub fn unwrap_if_lazy(&self) -> Result<Self> {265		Ok(if let Val::Lazy(v) = self {266			v.evaluate()?.unwrap_if_lazy()?267		} else {268			self.clone()269		})270	}271	pub fn value_type(&self) -> Result<ValType> {272		Ok(match self {273			Val::Str(..) => ValType::Str,274			Val::Num(..) => ValType::Num,275			Val::Arr(..) => ValType::Arr,276			Val::Obj(..) => ValType::Obj,277			Val::Bool(_) => ValType::Bool,278			Val::Null => ValType::Null,279			Val::Func(..) => ValType::Func,280			Val::Lazy(_) => self.clone().unwrap_if_lazy()?.value_type()?,281		})282	}283284	pub fn to_string(&self) -> Result<Rc<str>> {285		Ok(match self.unwrap_if_lazy()? {286			Val::Bool(true) => "true".into(),287			Val::Bool(false) => "false".into(),288			Val::Null => "null".into(),289			Val::Str(s) => s,290			v => manifest_json_ex(291				&v,292				&ManifestJsonOptions {293					padding: &"",294					mtype: ManifestType::ToString,295				},296			)?297			.into(),298		})299	}300301	/// Expects value to be object, outputs (key, manifested value) pairs302	pub fn manifest_multi(&self, ty: &ManifestFormat) -> Result<Vec<(Rc<str>, Rc<str>)>> {303		let obj = match self {304			Val::Obj(obj) => obj,305			_ => throw!(MultiManifestOutputIsNotAObject),306		};307		let keys = obj.visible_fields();308		let mut out = Vec::with_capacity(keys.len());309		for key in keys {310			let value = obj311				.get(key.clone())?312				.expect("item in object")313				.manifest(ty)?;314			out.push((key, value));315		}316		Ok(out)317	}318319	/// Expects value to be array, outputs manifested values320	pub fn manifest_stream(&self, ty: &ManifestFormat) -> Result<Vec<Rc<str>>> {321		let arr = match self {322			Val::Arr(a) => a,323			_ => throw!(StreamManifestOutputIsNotAArray),324		};325		let mut out = Vec::with_capacity(arr.len());326		for i in arr.iter() {327			out.push(i.manifest(ty)?);328		}329		Ok(out)330	}331332	pub fn manifest(&self, ty: &ManifestFormat) -> Result<Rc<str>> {333		Ok(match ty {334			ManifestFormat::YamlStream(format) => {335				let arr = match self {336					Val::Arr(a) => a,337					_ => throw!(StreamManifestOutputIsNotAArray),338				};339				let mut out = String::new();340341				match format as &ManifestFormat {342					ManifestFormat::YamlStream(_) => throw!(StreamManifestOutputCannotBeRecursed),343					ManifestFormat::String => throw!(StreamManifestCannotNestString),344					_ => {}345				};346347				if !arr.is_empty() {348					for v in arr.iter() {349						out.push_str("---\n");350						out.push_str(&v.manifest(format)?);351						out.push_str("\n");352					}353					out.push_str("...");354				}355356				out.into()357			}358			ManifestFormat::Yaml(padding) => self.to_yaml(*padding)?,359			ManifestFormat::Json(padding) => self.to_json(*padding)?,360			ManifestFormat::String => match self {361				Val::Str(s) => s.clone(),362				_ => throw!(StringManifestOutputIsNotAString),363			},364		})365	}366367	/// For manifestification368	pub fn to_json(&self, padding: usize) -> Result<Rc<str>> {369		manifest_json_ex(370			self,371			&ManifestJsonOptions {372				padding: &" ".repeat(padding),373				mtype: if padding == 0 {374					ManifestType::Minify375				} else {376					ManifestType::Manifest377				},378			},379		)380		.map(|s| s.into())381	}382383	/// Calls `std.manifestJson`384	#[cfg(feature = "faster")]385	pub fn to_std_json(&self, padding: usize) -> Result<Rc<str>> {386		manifest_json_ex(387			&self,388			&ManifestJsonOptions {389				padding: &" ".repeat(padding),390				mtype: ManifestType::Std,391			},392		)393		.map(|s| s.into())394	}395396	/// Calls `std.manifestJson`397	#[cfg(not(feature = "faster"))]398	pub fn to_std_json(&self, padding: usize) -> Result<Rc<str>> {399		with_state(|s| {400			let ctx = s401				.create_default_context()?402				.with_var("__tmp__to_json__".into(), self.clone())?;403			Ok(evaluate(404				ctx,405				&el!(Expr::Apply(406					el!(Expr::Index(407						el!(Expr::Var("std".into())),408						el!(Expr::Str("manifestJsonEx".into()))409					)),410					ArgsDesc(vec![411						Arg(None, el!(Expr::Var("__tmp__to_json__".into()))),412						Arg(None, el!(Expr::Str(" ".repeat(padding).into())))413					]),414					false415				)),416			)?417			.try_cast_str("to json")?)418		})419	}420	pub fn to_yaml(&self, padding: usize) -> Result<Rc<str>> {421		with_state(|s| {422			let ctx = s423				.create_default_context()?424				.with_var("__tmp__to_json__".into(), self.clone());425			Ok(evaluate(426				ctx,427				&el!(Expr::Apply(428					el!(Expr::Index(429						el!(Expr::Var("std".into())),430						el!(Expr::Str("manifestYamlDoc".into()))431					)),432					ArgsDesc(vec![433						Arg(None, el!(Expr::Var("__tmp__to_json__".into()))),434						Arg(None, el!(Expr::Str(" ".repeat(padding).into())))435					]),436					false437				)),438			)?439			.try_cast_str("to json")?)440		})441	}442}443444fn is_function_like(val: &Val) -> bool {445	matches!(val, Val::Func(_))446}447448/// Native implementation of `std.primitiveEquals`449pub fn primitive_equals(val_a: &Val, val_b: &Val) -> Result<bool> {450	Ok(match (val_a.unwrap_if_lazy()?, val_b.unwrap_if_lazy()?) {451		(Val::Bool(a), Val::Bool(b)) => a == b,452		(Val::Null, Val::Null) => true,453		(Val::Str(a), Val::Str(b)) => a == b,454		(Val::Num(a), Val::Num(b)) => (a - b).abs() <= f64::EPSILON,455		(Val::Arr(_), Val::Arr(_)) => throw!(RuntimeError(456			"primitiveEquals operates on primitive types, got array".into(),457		)),458		(Val::Obj(_), Val::Obj(_)) => throw!(RuntimeError(459			"primitiveEquals operates on primitive types, got object".into(),460		)),461		(a, b) if is_function_like(&a) && is_function_like(&b) => {462			throw!(RuntimeError("cannot test equality of functions".into()))463		}464		(_, _) => false,465	})466}467468/// Native implementation of `std.equals`469pub fn equals(val_a: &Val, val_b: &Val) -> Result<bool> {470	let val_a = val_a.unwrap_if_lazy()?;471	let val_b = val_b.unwrap_if_lazy()?;472473	if val_a.value_type()? != val_b.value_type()? {474		return Ok(false);475	}476	match (val_a, val_b) {477		// Cant test for ptr equality, because all fields needs to be evaluated478		(Val::Arr(a), Val::Arr(b)) => {479			if a.len() != b.len() {480				return Ok(false);481			}482			for (a, b) in a.iter().zip(b.iter()) {483				if !equals(&a.unwrap_if_lazy()?, &b.unwrap_if_lazy()?)? {484					return Ok(false);485				}486			}487			Ok(true)488		}489		(Val::Obj(a), Val::Obj(b)) => {490			let fields = a.visible_fields();491			if fields != b.visible_fields() {492				return Ok(false);493			}494			for field in fields {495				if !equals(&a.get(field.clone())?.unwrap(), &b.get(field)?.unwrap())? {496					return Ok(false);497				}498			}499			Ok(true)500		}501		(a, b) => Ok(primitive_equals(&a, &b)?),502	}503}
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, 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>, 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(ans, an), Self::Intrinsic(bns, bn)) => ans == bns && 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(ns, n) if ns as &str == "std" && 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(ns, name) => format!("intrinsic.{}.{}", ns, 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(ns, name) => call_builtin(call_ctx, loc, ns, 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	String,205}206207#[derive(Debug, Clone)]208pub enum Val {209	Bool(bool),210	Null,211	Str(Rc<str>),212	Num(f64),213	Lazy(LazyVal),214	Arr(Rc<Vec<Val>>),215	Obj(ObjValue),216	Func(Rc<FuncVal>),217}218219macro_rules! matches_unwrap {220	($e: expr, $p: pat, $r: expr) => {221		match $e {222			$p => $r,223			_ => panic!("no match"),224			}225	};226}227impl Val {228	/// Creates `Val::Num` after checking for numeric overflow.229	/// As numbers are `f64`, we can just check for their finity.230	pub fn new_checked_num(num: f64) -> Result<Self> {231		if num.is_finite() {232			Ok(Self::Num(num))233		} else {234			throw!(RuntimeError("overflow".into()))235		}236	}237238	pub fn assert_type(&self, context: &'static str, val_type: ValType) -> Result<()> {239		let this_type = self.value_type()?;240		if this_type != val_type {241			throw!(TypeMismatch(context, vec![val_type], this_type))242		} else {243			Ok(())244		}245	}246	pub fn try_cast_bool(self, context: &'static str) -> Result<bool> {247		self.assert_type(context, ValType::Bool)?;248		Ok(matches_unwrap!(self.unwrap_if_lazy()?, Self::Bool(v), v))249	}250	pub fn try_cast_str(self, context: &'static str) -> Result<Rc<str>> {251		self.assert_type(context, ValType::Str)?;252		Ok(matches_unwrap!(self.unwrap_if_lazy()?, Self::Str(v), v))253	}254	pub fn try_cast_num(self, context: &'static str) -> Result<f64> {255		self.assert_type(context, ValType::Num)?;256		Ok(matches_unwrap!(self.unwrap_if_lazy()?, Self::Num(v), v))257	}258	pub fn inplace_unwrap(&mut self) -> Result<()> {259		while let Self::Lazy(lazy) = self {260			*self = lazy.evaluate()?;261		}262		Ok(())263	}264	pub fn unwrap_if_lazy(&self) -> Result<Self> {265		Ok(if let Self::Lazy(v) = self {266			v.evaluate()?.unwrap_if_lazy()?267		} else {268			self.clone()269		})270	}271	pub fn value_type(&self) -> Result<ValType> {272		Ok(match self {273			Self::Str(..) => ValType::Str,274			Self::Num(..) => ValType::Num,275			Self::Arr(..) => ValType::Arr,276			Self::Obj(..) => ValType::Obj,277			Self::Bool(_) => ValType::Bool,278			Self::Null => ValType::Null,279			Self::Func(..) => ValType::Func,280			Self::Lazy(_) => self.clone().unwrap_if_lazy()?.value_type()?,281		})282	}283284	pub fn to_string(&self) -> Result<Rc<str>> {285		Ok(match self.unwrap_if_lazy()? {286			Self::Bool(true) => "true".into(),287			Self::Bool(false) => "false".into(),288			Self::Null => "null".into(),289			Self::Str(s) => s,290			v => manifest_json_ex(291				&v,292				&ManifestJsonOptions {293					padding: "",294					mtype: ManifestType::ToString,295				},296			)?297			.into(),298		})299	}300301	/// Expects value to be object, outputs (key, manifested value) pairs302	pub fn manifest_multi(&self, ty: &ManifestFormat) -> Result<Vec<(Rc<str>, Rc<str>)>> {303		let obj = match self {304			Self::Obj(obj) => obj,305			_ => throw!(MultiManifestOutputIsNotAObject),306		};307		let keys = obj.visible_fields();308		let mut out = Vec::with_capacity(keys.len());309		for key in keys {310			let value = obj311				.get(key.clone())?312				.expect("item in object")313				.manifest(ty)?;314			out.push((key, value));315		}316		Ok(out)317	}318319	/// Expects value to be array, outputs manifested values320	pub fn manifest_stream(&self, ty: &ManifestFormat) -> Result<Vec<Rc<str>>> {321		let arr = match self {322			Self::Arr(a) => a,323			_ => throw!(StreamManifestOutputIsNotAArray),324		};325		let mut out = Vec::with_capacity(arr.len());326		for i in arr.iter() {327			out.push(i.manifest(ty)?);328		}329		Ok(out)330	}331332	pub fn manifest(&self, ty: &ManifestFormat) -> Result<Rc<str>> {333		Ok(match ty {334			ManifestFormat::YamlStream(format) => {335				let arr = match self {336					Self::Arr(a) => a,337					_ => throw!(StreamManifestOutputIsNotAArray),338				};339				let mut out = String::new();340341				match format as &ManifestFormat {342					ManifestFormat::YamlStream(_) => throw!(StreamManifestOutputCannotBeRecursed),343					ManifestFormat::String => throw!(StreamManifestCannotNestString),344					_ => {}345				};346347				if !arr.is_empty() {348					for v in arr.iter() {349						out.push_str("---\n");350						out.push_str(&v.manifest(format)?);351						out.push_str("\n");352					}353					out.push_str("...");354				}355356				out.into()357			}358			ManifestFormat::Yaml(padding) => self.to_yaml(*padding)?,359			ManifestFormat::Json(padding) => self.to_json(*padding)?,360			ManifestFormat::String => match self {361				Self::Str(s) => s.clone(),362				_ => throw!(StringManifestOutputIsNotAString),363			},364		})365	}366367	/// For manifestification368	pub fn to_json(&self, padding: usize) -> Result<Rc<str>> {369		manifest_json_ex(370			self,371			&ManifestJsonOptions {372				padding: &" ".repeat(padding),373				mtype: if padding == 0 {374					ManifestType::Minify375				} else {376					ManifestType::Manifest377				},378			},379		)380		.map(|s| s.into())381	}382383	/// Calls `std.manifestJson`384	#[cfg(feature = "faster")]385	pub fn to_std_json(&self, padding: usize) -> Result<Rc<str>> {386		manifest_json_ex(387			self,388			&ManifestJsonOptions {389				padding: &" ".repeat(padding),390				mtype: ManifestType::Std,391			},392		)393		.map(|s| s.into())394	}395396	/// Calls `std.manifestJson`397	#[cfg(not(feature = "faster"))]398	pub fn to_std_json(&self, padding: usize) -> Result<Rc<str>> {399		with_state(|s| {400			let ctx = s401				.create_default_context()?402				.with_var("__tmp__to_json__".into(), self.clone())?;403			Ok(evaluate(404				ctx,405				&el!(Expr::Apply(406					el!(Expr::Index(407						el!(Expr::Var("std".into())),408						el!(Expr::Str("manifestJsonEx".into()))409					)),410					ArgsDesc(vec![411						Arg(None, el!(Expr::Var("__tmp__to_json__".into()))),412						Arg(None, el!(Expr::Str(" ".repeat(padding).into())))413					]),414					false415				)),416			)?417			.try_cast_str("to json")?)418		})419	}420	pub fn to_yaml(&self, padding: usize) -> Result<Rc<str>> {421		with_state(|s| {422			let ctx = s423				.create_default_context()?424				.with_var("__tmp__to_json__".into(), self.clone());425			Ok(evaluate(426				ctx,427				&el!(Expr::Apply(428					el!(Expr::Index(429						el!(Expr::Var("std".into())),430						el!(Expr::Str("manifestYamlDoc".into()))431					)),432					ArgsDesc(vec![433						Arg(None, el!(Expr::Var("__tmp__to_json__".into()))),434						Arg(None, el!(Expr::Str(" ".repeat(padding).into())))435					]),436					false437				)),438			)?439			.try_cast_str("to json")?)440		})441	}442}443444const fn is_function_like(val: &Val) -> bool {445	matches!(val, Val::Func(_))446}447448/// Native implementation of `std.primitiveEquals`449pub fn primitive_equals(val_a: &Val, val_b: &Val) -> Result<bool> {450	Ok(match (val_a.unwrap_if_lazy()?, val_b.unwrap_if_lazy()?) {451		(Val::Bool(a), Val::Bool(b)) => a == b,452		(Val::Null, Val::Null) => true,453		(Val::Str(a), Val::Str(b)) => a == b,454		(Val::Num(a), Val::Num(b)) => (a - b).abs() <= f64::EPSILON,455		(Val::Arr(_), Val::Arr(_)) => throw!(RuntimeError(456			"primitiveEquals operates on primitive types, got array".into(),457		)),458		(Val::Obj(_), Val::Obj(_)) => throw!(RuntimeError(459			"primitiveEquals operates on primitive types, got object".into(),460		)),461		(a, b) if is_function_like(&a) && is_function_like(&b) => {462			throw!(RuntimeError("cannot test equality of functions".into()))463		}464		(_, _) => false,465	})466}467468/// Native implementation of `std.equals`469pub fn equals(val_a: &Val, val_b: &Val) -> Result<bool> {470	let val_a = val_a.unwrap_if_lazy()?;471	let val_b = val_b.unwrap_if_lazy()?;472473	if val_a.value_type()? != val_b.value_type()? {474		return Ok(false);475	}476	match (val_a, val_b) {477		// Cant test for ptr equality, because all fields needs to be evaluated478		(Val::Arr(a), Val::Arr(b)) => {479			if a.len() != b.len() {480				return Ok(false);481			}482			for (a, b) in a.iter().zip(b.iter()) {483				if !equals(&a.unwrap_if_lazy()?, &b.unwrap_if_lazy()?)? {484					return Ok(false);485				}486			}487			Ok(true)488		}489		(Val::Obj(a), Val::Obj(b)) => {490			let fields = a.visible_fields();491			if fields != b.visible_fields() {492				return Ok(false);493			}494			for field in fields {495				if !equals(&a.get(field.clone())?.unwrap(), &b.get(field)?.unwrap())? {496					return Ok(false);497				}498			}499			Ok(true)500		}501		(a, b) => Ok(primitive_equals(&a, &b)?),502	}503}