git.delta.rocks / jrsonnet / refs/commits / 11643ec5f009

difftreelog

style switch clippy to pedantic

Yaroslav Bolyukin2022-04-22parent: #b4a4398.patch.diff
in: master

25 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
@@ -86,6 +86,7 @@
 	}
 }
 
+#[allow(clippy::struct_excessive_bools)]
 #[derive(Default, Debug)]
 pub struct CFlags {
 	pub alt: bool,
@@ -270,12 +271,12 @@
 			return Ok(out);
 		}
 		str = &str[offset + 1..];
-		let (code, nstr) = parse_code(str)?;
-		str = nstr;
+		let code;
+		(code, str) = parse_code(str)?;
 		bytes = str.as_bytes();
 		offset = 0;
 
-		out.push(Element::Code(code))
+		out.push(Element::Code(code));
 	}
 }
 
@@ -313,7 +314,7 @@
 		.saturating_sub(prefix.len() + digits.len());
 
 	if neg {
-		out.push('-')
+		out.push('-');
 	} else if sign {
 		out.push('+');
 	} else if blank {
@@ -340,7 +341,7 @@
 	blank: bool,
 	sign: bool,
 ) {
-	render_integer(out, iv, padding, precision, blank, sign, 10, "", false)
+	render_integer(out, iv, padding, precision, blank, sign, 10, "", false);
 }
 pub fn render_octal(
 	out: &mut String,
@@ -361,8 +362,10 @@
 		8,
 		if alt && iv != 0 { "0" } else { "" },
 		false,
-	)
+	);
 }
+
+#[allow(clippy::fn_params_excessive_bools)]
 pub fn render_hexadecimal(
 	out: &mut String,
 	iv: i64,
@@ -387,9 +390,10 @@
 			(false, _) => "",
 		},
 		caps,
-	)
+	);
 }
 
+#[allow(clippy::fn_params_excessive_bools)]
 pub fn render_float(
 	out: &mut String,
 	n: f64,
@@ -431,6 +435,7 @@
 	}
 }
 
+#[allow(clippy::fn_params_excessive_bools)]
 pub fn render_float_sci(
 	out: &mut String,
 	n: f64,
@@ -461,6 +466,7 @@
 	out.push_str(&exponent_str);
 }
 
+#[allow(clippy::too_many_lines)]
 pub fn format_code(
 	s: State,
 	out: &mut String,
modifiedcrates/jrsonnet-evaluator/src/builtin/manifest.rsdiffbeforeafterboth
--- a/crates/jrsonnet-evaluator/src/builtin/manifest.rs
+++ b/crates/jrsonnet-evaluator/src/builtin/manifest.rs
@@ -158,7 +158,7 @@
 			'\r' => buf.push_str("\\r"),
 			'\t' => buf.push_str("\\t"),
 			c if c < 32 as char || (c >= 127 as char && c <= 159 as char) => {
-				write!(buf, "\\u{:04x}", c as u32).unwrap()
+				write!(buf, "\\u{:04x}", c as u32).unwrap();
 			}
 			c => buf.push(c),
 		}
@@ -194,7 +194,7 @@
 	pub preserve_order: bool,
 }
 
-/// From https://github.com/chyh1990/yaml-rust/blob/da52a68615f2ecdd6b7e4567019f280c433c1521/src/emitter.rs#L289
+/// From <https://github.com/chyh1990/yaml-rust/blob/da52a68615f2ecdd6b7e4567019f280c433c1521/src/emitter.rs#L289>
 /// With added date check
 fn yaml_needs_quotes(string: &str) -> bool {
 	fn need_quotes_spaces(string: &str) -> bool {
@@ -227,6 +227,8 @@
 	manifest_yaml_ex_buf(s, val, &mut out, &mut String::new(), options)?;
 	Ok(out)
 }
+
+#[allow(clippy::too_many_lines)]
 fn manifest_yaml_ex_buf(
 	s: State,
 	val: &Val,
@@ -238,9 +240,9 @@
 	match val {
 		Val::Bool(v) => {
 			if *v {
-				buf.push_str("true")
+				buf.push_str("true");
 			} else {
-				buf.push_str("false")
+				buf.push_str("false");
 			}
 		}
 		Val::Null => buf.push_str("null"),
modifiedcrates/jrsonnet-evaluator/src/builtin/mod.rsdiffbeforeafterboth
--- a/crates/jrsonnet-evaluator/src/builtin/mod.rs
+++ b/crates/jrsonnet-evaluator/src/builtin/mod.rs
@@ -1,3 +1,6 @@
+// All builtins should return results
+#![allow(clippy::unnecessary_wraps)]
+
 use std::collections::HashMap;
 
 use format::{format_arr, format_obj};
@@ -173,7 +176,7 @@
 fn builtin_make_array(s: State, sz: usize, func: FuncVal) -> Result<VecVal> {
 	let mut out = Vec::with_capacity(sz);
 	for i in 0..sz {
-		out.push(func.evaluate_simple(s.clone(), &[i as f64].as_slice())?)
+		out.push(func.evaluate_simple(s.clone(), &[i as f64].as_slice())?);
 	}
 	Ok(VecVal(Cc::new(out)))
 }
@@ -420,7 +423,7 @@
 				match func.evaluate_simple(s.clone(), &[Any(el)].as_slice())? {
 					Val::Arr(o) => {
 						for oe in o.iter(s.clone()) {
-							out.push(oe?)
+							out.push(oe?);
 						}
 					}
 					_ => throw!(RuntimeError(
@@ -707,7 +710,7 @@
 #[jrsonnet_macros::builtin]
 fn builtin_count(s: State, arr: Vec<Any>, v: Any) -> Result<usize> {
 	let mut count = 0;
-	for item in arr.iter() {
+	for item in &arr {
 		if equals(s.clone(), &item.0, &v.0)? {
 			count += 1;
 		}
modifiedcrates/jrsonnet-evaluator/src/builtin/sort.rsdiffbeforeafterboth
--- a/crates/jrsonnet-evaluator/src/builtin/sort.rs
+++ b/crates/jrsonnet-evaluator/src/builtin/sort.rs
@@ -53,10 +53,10 @@
 		match (i, sort_type) {
 			(Val::Str(_), SortKeyType::Unknown) => sort_type = SortKeyType::String,
 			(Val::Num(_), SortKeyType::Unknown) => sort_type = SortKeyType::Number,
-			(Val::Str(_), SortKeyType::String) => {}
-			(Val::Str(_), _) => throw!(SortError::SortElementsShouldHaveEqualType),
-			(Val::Num(_), SortKeyType::Number) => {}
-			(Val::Num(_), _) => throw!(SortError::SortElementsShouldHaveEqualType),
+			(Val::Str(_), SortKeyType::String) | (Val::Num(_), SortKeyType::Number) => {}
+			(Val::Str(_) | Val::Num(_), _) => {
+				throw!(SortError::SortElementsShouldHaveEqualType)
+			}
 			_ => throw!(SortError::SortKeyShouldBeStringOrNumber),
 		}
 	}
@@ -91,19 +91,19 @@
 		Ok(Cc::new(vk.into_iter().map(|v| v.0).collect()))
 	} else {
 		// Fast path, identity key getter
-		let mut mvalues = (*values).clone();
-		let sort_type = get_sort_type(&mut mvalues, |k| k)?;
+		let mut values = (*values).clone();
+		let sort_type = get_sort_type(&mut values, |k| k)?;
 		match sort_type {
-			SortKeyType::Number => mvalues.sort_unstable_by_key(|v| match v {
+			SortKeyType::Number => values.sort_unstable_by_key(|v| match v {
 				Val::Num(n) => NonNaNf64(*n),
 				_ => unreachable!(),
 			}),
-			SortKeyType::String => mvalues.sort_unstable_by_key(|v| match v {
+			SortKeyType::String => values.sort_unstable_by_key(|v| match v {
 				Val::Str(s) => s.clone(),
 				_ => unreachable!(),
 			}),
 			SortKeyType::Unknown => unreachable!(),
 		};
-		Ok(Cc::new(mvalues))
+		Ok(Cc::new(values))
 	}
 }
modifiedcrates/jrsonnet-evaluator/src/builtin/stdlib.rsdiffbeforeafterboth
--- a/crates/jrsonnet-evaluator/src/builtin/stdlib.rs
+++ b/crates/jrsonnet-evaluator/src/builtin/stdlib.rs
@@ -24,5 +24,5 @@
 }
 
 pub fn get_parsed_stdlib() -> LocExpr {
-	PARSED_STDLIB.with(|t| t.clone())
+	PARSED_STDLIB.with(Clone::clone)
 }
modifiedcrates/jrsonnet-evaluator/src/ctx.rsdiffbeforeafterboth
--- a/crates/jrsonnet-evaluator/src/ctx.rs
+++ b/crates/jrsonnet-evaluator/src/ctx.rs
@@ -79,6 +79,7 @@
 	pub fn contains_binding(&self, name: IStr) -> bool {
 		self.0.bindings.contains_key(&name)
 	}
+	#[must_use]
 	pub fn into_future(self, ctx: FutureWrapper<Self>) -> Self {
 		{
 			ctx.0.borrow_mut().replace(self);
@@ -86,16 +87,19 @@
 		ctx.unwrap()
 	}
 
+	#[must_use]
 	pub fn with_var(self, name: IStr, value: Val) -> Self {
 		let mut new_bindings = GcHashMap::with_capacity(1);
 		new_bindings.insert(name, LazyVal::new_resolved(value));
 		self.extend(new_bindings, None, None, None)
 	}
 
+	#[must_use]
 	pub fn with_this_super(self, new_this: ObjValue, new_super_obj: Option<ObjValue>) -> Self {
 		self.extend(GcHashMap::new(), None, Some(new_this), new_super_obj)
 	}
 
+	#[must_use]
 	pub fn extend(
 		self,
 		new_bindings: GcHashMap<IStr, LazyVal>,
@@ -119,6 +123,7 @@
 			bindings,
 		}))
 	}
+	#[must_use]
 	pub fn extend_bound(self, new_bindings: GcHashMap<IStr, LazyVal>) -> Self {
 		let new_this = self.0.this.clone();
 		let new_super_obj = self.0.super_obj.clone();
@@ -135,7 +140,7 @@
 		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 = GcHashMap::with_capacity(new_bindings.len());
-		for (k, v) in new_bindings.0.into_iter() {
+		for (k, v) in new_bindings.0 {
 			new.insert(k, v.evaluate(s.clone(), this.clone(), super_obj.clone())?);
 		}
 		Ok(self.extend(new, new_dollar, this, super_obj))
modifiedcrates/jrsonnet-evaluator/src/dynamic.rsdiffbeforeafterboth
--- a/crates/jrsonnet-evaluator/src/dynamic.rs
+++ b/crates/jrsonnet-evaluator/src/dynamic.rs
@@ -8,12 +8,16 @@
 	pub fn new() -> Self {
 		Self(Cc::new(RefCell::new(None)))
 	}
+	/// # Panics
+	/// If wrapper is filled already
 	pub fn fill(self, value: T) {
 		assert!(self.0.borrow().is_none(), "wrapper is filled already");
 		self.0.borrow_mut().replace(value);
 	}
 }
 impl<T: Clone + Trace + 'static> FutureWrapper<T> {
+	/// # Panics
+	/// If wrapper is not yet filled
 	pub fn unwrap(&self) -> T {
 		self.0.borrow().as_ref().cloned().unwrap()
 	}
modifiedcrates/jrsonnet-evaluator/src/error.rsdiffbeforeafterboth
--- a/crates/jrsonnet-evaluator/src/error.rs
+++ b/crates/jrsonnet-evaluator/src/error.rs
@@ -96,7 +96,8 @@
 	#[error(
 		"syntax error: expected {}, got {:?}",
 		.error.expected,
-		.source_code.chars().nth(error.location.offset).map(|c| c.to_string()).unwrap_or_else(|| "EOF".into())
+		.source_code.chars().nth(error.location.offset)
+		.map_or_else(|| "EOF".into(), |c| c.to_string())
 	)]
 	ImportSyntaxError {
 		#[skip_trace]
@@ -190,7 +191,7 @@
 impl Debug for LocError {
 	fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
 		writeln!(f, "{}", self.0 .0)?;
-		for el in self.0 .1 .0.iter() {
+		for el in &self.0 .1 .0 {
 			writeln!(f, "\t{:?}", el)?;
 		}
 		Ok(())
modifiedcrates/jrsonnet-evaluator/src/evaluate/mod.rsdiffbeforeafterboth
--- a/crates/jrsonnet-evaluator/src/evaluate/mod.rs
+++ b/crates/jrsonnet-evaluator/src/evaluate/mod.rs
@@ -23,8 +23,6 @@
 pub fn evaluate_binding_in_future(b: &BindSpec, fctx: FutureWrapper<Context>) -> LazyVal {
 	let b = b.clone();
 	if let Some(params) = &b.params {
-		let params = params.clone();
-
 		#[derive(Trace)]
 		struct LazyMethodBinding {
 			fctx: FutureWrapper<Context>,
@@ -43,6 +41,8 @@
 			}
 		}
 
+		let params = params.clone();
+
 		LazyVal::new(TraceBox(Box::new(LazyMethodBinding {
 			fctx,
 			name: b.name.clone(),
@@ -69,11 +69,10 @@
 	}
 }
 
+#[allow(clippy::too_many_lines)]
 pub fn evaluate_binding(b: &BindSpec, cctx: ContextCreator) -> (IStr, LazyBinding) {
 	let b = b.clone();
 	if let Some(params) = &b.params {
-		let params = params.clone();
-
 		#[derive(Trace)]
 		struct BindableMethodLazyVal {
 			this: Option<ObjValue>,
@@ -121,6 +120,8 @@
 			}
 		}
 
+		let params = params.clone();
+
 		(
 			b.name.clone(),
 			LazyBinding::Bindable(Cc::new(TraceBox(Box::new(BindableMethod {
@@ -227,7 +228,7 @@
 		None => callback(ctx)?,
 		Some(CompSpec::IfSpec(IfSpecData(cond))) => {
 			if bool::from_untyped(evaluate(s.clone(), ctx.clone(), cond)?, s.clone())? {
-				evaluate_comp(s, ctx, &specs[1..], callback)?
+				evaluate_comp(s, ctx, &specs[1..], callback)?;
 			}
 		}
 		Some(CompSpec::ForSpec(ForSpecData(var, expr))) => {
@@ -239,7 +240,7 @@
 							ctx.clone().with_var(var.clone(), item?.clone()),
 							&specs[1..],
 							callback,
-						)?
+						)?;
 					}
 				}
 				_ => throw!(InComprehensionCanOnlyIterateOverArray),
@@ -249,6 +250,7 @@
 	Ok(())
 }
 
+#[allow(clippy::too_many_lines)]
 pub fn evaluate_member_list_object(s: State, ctx: Context, members: &[Member]) -> Result<ObjValue> {
 	let new_bindings = FutureWrapper::new();
 	let future_this = FutureWrapper::new();
@@ -278,12 +280,6 @@
 				visibility,
 				value,
 			}) => {
-				let name = evaluate_field_name(s.clone(), ctx.clone(), name)?;
-				if name.is_none() {
-					continue;
-				}
-				let name = name.unwrap();
-
 				#[derive(Trace)]
 				struct ObjMemberBinding {
 					cctx: ContextCreator,
@@ -305,6 +301,14 @@
 						)?))
 					}
 				}
+
+				let name = evaluate_field_name(s.clone(), ctx.clone(), name)?;
+				let name = if let Some(name) = name {
+					name
+				} else {
+					continue;
+				};
+
 				builder
 					.member(name.clone())
 					.with_add(*plus)
@@ -325,11 +329,6 @@
 				value,
 				..
 			}) => {
-				let name = evaluate_field_name(s.clone(), ctx.clone(), name)?;
-				if name.is_none() {
-					continue;
-				}
-				let name = name.unwrap();
 				#[derive(Trace)]
 				struct ObjMemberBinding {
 					cctx: ContextCreator,
@@ -352,6 +351,13 @@
 						)))
 					}
 				}
+
+				let name = if let Some(name) = evaluate_field_name(s.clone(), ctx.clone(), name)? {
+					name
+				} else {
+					continue;
+				};
+
 				builder
 					.member(name.clone())
 					.hide()
@@ -505,24 +511,24 @@
 					throw!(AssertionFailed(
 						evaluate(s.clone(), ctx, msg)?.to_string(s.clone())?
 					));
-				} else {
-					throw!(AssertionFailed(Val::Null.to_string(s.clone())?));
 				}
+				throw!(AssertionFailed(Val::Null.to_string(s.clone())?));
 			},
-		)?
+		)?;
 	}
 	Ok(())
 }
 
-pub fn evaluate_named(s: State, ctx: Context, lexpr: &LocExpr, name: IStr) -> Result<Val> {
+pub fn evaluate_named(s: State, ctx: Context, expr: &LocExpr, name: IStr) -> Result<Val> {
 	use Expr::*;
-	let LocExpr(expr, _loc) = lexpr;
-	Ok(match &**expr {
+	let LocExpr(raw_expr, _loc) = expr;
+	Ok(match &**raw_expr {
 		Function(params, body) => evaluate_method(ctx, name, params.clone(), body.clone()),
-		_ => evaluate(s, ctx, lexpr)?,
+		_ => evaluate(s, ctx, expr)?,
 	})
 }
 
+#[allow(clippy::too_many_lines)]
 pub fn evaluate(s: State, ctx: Context, expr: &LocExpr) -> Result<Val> {
 	use Expr::*;
 	let LocExpr(expr, loc) = expr;
@@ -532,10 +538,11 @@
 			Val::Obj(ctx.this().clone().ok_or(CantUseSelfOutsideOfObject)?)
 		}
 		Literal(LiteralType::Super) => Val::Obj(
-			ctx.super_obj()
-				.clone()
-				.ok_or(NoSuperFound)?
-				.with_this(ctx.this().clone().unwrap()),
+			ctx.super_obj().clone().ok_or(NoSuperFound)?.with_this(
+				ctx.this()
+					.clone()
+					.expect("if super exists - then this should to"),
+			),
 		),
 		Literal(LiteralType::Dollar) => {
 			Val::Obj(ctx.dollar().clone().ok_or(NoTopLevelObjectFound)?)
@@ -699,9 +706,6 @@
 			}
 		}
 		Slice(value, desc) => {
-			let indexable = evaluate(s.clone(), ctx.clone(), value)?;
-			let loc = CallLocation::new(loc);
-
 			fn parse_idx<T: Typed>(
 				loc: CallLocation,
 				s: State,
@@ -720,6 +724,9 @@
 				}
 			}
 
+			let indexable = evaluate(s.clone(), ctx.clone(), value)?;
+			let loc = CallLocation::new(loc);
+
 			let start = parse_idx(loc, s.clone(), &ctx, &desc.start, "start")?;
 			let end = parse_idx(loc, s.clone(), &ctx, &desc.end, "end")?;
 			let step = parse_idx(loc, s, &ctx, &desc.step, "step")?;
modifiedcrates/jrsonnet-evaluator/src/evaluate/operator.rsdiffbeforeafterboth
--- a/crates/jrsonnet-evaluator/src/evaluate/operator.rs
+++ b/crates/jrsonnet-evaluator/src/evaluate/operator.rs
@@ -1,3 +1,5 @@
+use std::cmp::Ordering;
+
 use jrsonnet_parser::{BinaryOpType, LocExpr, UnaryOpType};
 
 use crate::{
@@ -11,7 +13,7 @@
 	Ok(match (op, b) {
 		(Not, Bool(v)) => Bool(!v),
 		(Minus, Num(n)) => Num(-*n),
-		(BitNot, Num(n)) => Num(!(*n as i32) as f64),
+		(BitNot, Num(n)) => Num(f64::from(!(*n as i32))),
 		(op, o) => throw!(UnaryOperatorDoesNotOperateOnType(op, o.value_type())),
 	})
 }
@@ -22,8 +24,8 @@
 		(Str(v1), Str(v2)) => Str(((**v1).to_owned() + v2).into()),
 
 		// Can't use generic json serialization way, because it depends on number to string concatenation (std.jsonnet:890)
-		(Num(n), Str(o)) => Str(format!("{}{}", n, o).into()),
-		(Str(o), Num(n)) => Str(format!("{}{}", o, n).into()),
+		(Num(a), Str(b)) => Str(format!("{a}{b}").into()),
+		(Str(a), Num(b)) => Str(format!("{a}{b}").into()),
 
 		(Str(a), o) => Str(format!("{}{}", a, o.clone().to_string(s)?).into()),
 		(o, Str(a)) => Str(format!("{}{}", o.clone().to_string(s)?, a).into()),
@@ -47,7 +49,12 @@
 pub fn evaluate_mod_op(s: State, a: &Val, b: &Val) -> Result<Val> {
 	use Val::*;
 	match (a, b) {
-		(Num(a), Num(b)) => Ok(Num(a % b)),
+		(Num(a), Num(b)) => {
+			if *b == 0.0 {
+				throw!(DivisionByZero)
+			}
+			Ok(Num(a % b))
+		}
 		(Str(str), vals) => {
 			String::into_untyped(std_format(s.clone(), str.clone(), vals.clone())?, s)
 		}
@@ -75,6 +82,32 @@
 	})
 }
 
+pub fn evaluate_compare_op(s: State, a: &Val, op: BinaryOpType, b: &Val) -> Result<Ordering> {
+	use Val::*;
+	Ok(match (a, b) {
+		(Str(a), Str(b)) => a.cmp(b),
+		(Num(a), Num(b)) => a.partial_cmp(b).expect("jsonnet numbers are non NaN"),
+		(Arr(a), Arr(b)) => {
+			let ai = a.iter(s.clone());
+			let bi = b.iter(s.clone());
+
+			for (a, b) in ai.zip(bi) {
+				let ord = evaluate_compare_op(s.clone(), &a?, op, &b?)?;
+				if !ord.is_eq() {
+					return Ok(ord);
+				}
+			}
+
+			a.len().cmp(&b.len())
+		}
+		(_, _) => throw!(BinaryOperatorDoesNotOperateOnValues(
+			op,
+			a.value_type(),
+			b.value_type()
+		)),
+	})
+}
+
 pub fn evaluate_binary_op_normal(s: State, a: &Val, op: BinaryOpType, b: &Val) -> Result<Val> {
 	use BinaryOpType::*;
 	use Val::*;
@@ -84,6 +117,11 @@
 		(a, Eq, b) => Bool(equals(s, a, b)?),
 		(a, Neq, b) => Bool(!equals(s, a, b)?),
 
+		(a, Lt, b) => Bool(evaluate_compare_op(s, a, Lt, b)?.is_lt()),
+		(a, Gt, b) => Bool(evaluate_compare_op(s, a, Gt, b)?.is_gt()),
+		(a, Lte, b) => Bool(evaluate_compare_op(s, a, Lte, b)?.is_le()),
+		(a, Gte, b) => Bool(evaluate_compare_op(s, a, Gte, b)?.is_ge()),
+
 		(Str(a), In, Obj(obj)) => Bool(obj.has_field_ex(a.clone(), true)),
 		(a, Mod, b) => evaluate_mod_op(s, a, b)?,
 
@@ -92,17 +130,11 @@
 		// Bool X Bool
 		(Bool(a), And, Bool(b)) => Bool(*a && *b),
 		(Bool(a), Or, Bool(b)) => Bool(*a || *b),
-
-		// Str X Str
-		(Str(v1), Lt, Str(v2)) => Bool(v1 < v2),
-		(Str(v1), Gt, Str(v2)) => Bool(v1 > v2),
-		(Str(v1), Lte, Str(v2)) => Bool(v1 <= v2),
-		(Str(v1), Gte, Str(v2)) => Bool(v1 >= v2),
 
 		// Num X Num
 		(Num(v1), Mul, Num(v2)) => Val::new_checked_num(v1 * v2)?,
 		(Num(v1), Div, Num(v2)) => {
-			if *v2 <= f64::EPSILON {
+			if *v2 == 0.0 {
 				throw!(DivisionByZero)
 			}
 			Val::new_checked_num(v1 / v2)?
@@ -110,25 +142,20 @@
 
 		(Num(v1), Sub, Num(v2)) => Val::new_checked_num(v1 - v2)?,
 
-		(Num(v1), Lt, Num(v2)) => Bool(v1 < v2),
-		(Num(v1), Gt, Num(v2)) => Bool(v1 > v2),
-		(Num(v1), Lte, Num(v2)) => Bool(v1 <= v2),
-		(Num(v1), Gte, Num(v2)) => Bool(v1 >= v2),
-
-		(Num(v1), BitAnd, Num(v2)) => Num(((*v1 as i32) & (*v2 as i32)) as f64),
-		(Num(v1), BitOr, Num(v2)) => Num(((*v1 as i32) | (*v2 as i32)) as f64),
-		(Num(v1), BitXor, Num(v2)) => Num(((*v1 as i32) ^ (*v2 as i32)) as f64),
+		(Num(v1), BitAnd, Num(v2)) => Num(f64::from((*v1 as i32) & (*v2 as i32))),
+		(Num(v1), BitOr, Num(v2)) => Num(f64::from((*v1 as i32) | (*v2 as i32))),
+		(Num(v1), BitXor, Num(v2)) => Num(f64::from((*v1 as i32) ^ (*v2 as i32))),
 		(Num(v1), Lhs, Num(v2)) => {
 			if *v2 < 0.0 {
 				throw!(RuntimeError("shift by negative exponent".into()))
 			}
-			Num(((*v1 as i32) << (*v2 as i32)) as f64)
+			Num(f64::from((*v1 as i32) << (*v2 as i32)))
 		}
 		(Num(v1), Rhs, Num(v2)) => {
 			if *v2 < 0.0 {
 				throw!(RuntimeError("shift by negative exponent".into()))
 			}
-			Num(((*v1 as i32) >> (*v2 as i32)) as f64)
+			Num(f64::from((*v1 as i32) >> (*v2 as i32)))
 		}
 
 		_ => throw!(BinaryOperatorDoesNotOperateOnValues(
modifiedcrates/jrsonnet-evaluator/src/function.rsdiffbeforeafterboth
--- a/crates/jrsonnet-evaluator/src/function.rs
+++ b/crates/jrsonnet-evaluator/src/function.rs
@@ -145,7 +145,7 @@
 		tailstrict: bool,
 		handler: &mut dyn FnMut(&IStr, LazyVal) -> Result<()>,
 	) -> Result<()> {
-		for (name, arg) in self.named.iter() {
+		for (name, arg) in &self.named {
 			handler(
 				name,
 				if tailstrict {
@@ -162,8 +162,8 @@
 	}
 
 	fn named_names(&self, handler: &mut dyn FnMut(&IStr)) {
-		for (name, _) in self.named.iter() {
-			handler(name)
+		for (name, _) in &self.named {
+			handler(name);
 		}
 	}
 }
@@ -231,7 +231,7 @@
 	}
 }
 
-impl<A: ArgLike> ArgsLike for HashMap<IStr, A> {
+impl<A: ArgLike, S> ArgsLike for HashMap<IStr, A, S> {
 	fn unnamed_len(&self) -> usize {
 		0
 	}
@@ -325,7 +325,7 @@
 	}
 
 	fn named_names(&self, handler: &mut dyn FnMut(&IStr)) {
-		(*self).named_names(handler)
+		(*self).named_names(handler);
 	}
 }
 
@@ -381,18 +381,13 @@
 			if passed_args.contains_key(&param.0.clone()) {
 				continue;
 			}
-			LazyVal::new(TraceBox(Box::new(EvaluateNamedLazyVal {
-				ctx: fctx.clone(),
-				name: param.0.clone(),
-				value: param.1.clone().unwrap(),
-			})));
 
 			defaults.insert(
 				param.0.clone(),
 				LazyVal::new(TraceBox(Box::new(EvaluateNamedLazyVal {
 					ctx: fctx.clone(),
 					name: param.0.clone(),
-					value: param.1.clone().unwrap(),
+					value: param.1.clone().expect("default exists"),
 				}))),
 			);
 			filled_args += 1;
@@ -447,7 +442,7 @@
 	// const INST: &'static Self;
 }
 
-/// You shouldn't probally use this function, use jrsonnet_macros::builtin instead
+/// You shouldn't probally use this function, use `jrsonnet_macros::builtin` instead
 ///
 /// ## Parameters
 /// * `ctx`: used for passed argument expressions' execution and for body execution (if `body_ctx` is not set)
@@ -518,10 +513,6 @@
 /// Creates Context, which has all argument default values applied
 /// and with unbound values causing error to be returned
 pub fn parse_default_function_call(body_ctx: Context, params: &ParamsDesc) -> Context {
-	let fctx = Context::new_future();
-
-	let mut bindings = GcHashMap::new();
-
 	#[derive(Trace)]
 	struct DependsOnUnbound(IStr);
 	impl LazyValValue for DependsOnUnbound {
@@ -530,6 +521,10 @@
 		}
 	}
 
+	let fctx = Context::new_future();
+
+	let mut bindings = GcHashMap::new();
+
 	for param in params.iter() {
 		if let Some(v) = &param.1 {
 			bindings.insert(
modifiedcrates/jrsonnet-evaluator/src/gc.rsdiffbeforeafterboth
--- a/crates/jrsonnet-evaluator/src/gc.rs
+++ b/crates/jrsonnet-evaluator/src/gc.rs
@@ -1,6 +1,7 @@
 /// Macros to help deal with Gc
 use std::{
 	borrow::{Borrow, BorrowMut},
+	collections::{HashMap, HashSet},
 	hash::BuildHasherDefault,
 	ops::{Deref, DerefMut},
 };
@@ -14,7 +15,7 @@
 
 impl<T: ?Sized + Trace> Trace for TraceBox<T> {
 	fn trace(&self, tracer: &mut Tracer) {
-		self.0.trace(tracer)
+		self.0.trace(tracer);
 	}
 
 	fn is_type_tracked() -> bool {
@@ -70,7 +71,7 @@
 pub struct GcHashSet<V>(pub FxHashSet<V>);
 impl<V> GcHashSet<V> {
 	pub fn new() -> Self {
-		Self(Default::default())
+		Self(HashSet::default())
 	}
 	pub fn with_capacity(capacity: usize) -> Self {
 		Self(FxHashSet::with_capacity_and_hasher(
@@ -111,7 +112,7 @@
 pub struct GcHashMap<K, V>(pub FxHashMap<K, V>);
 impl<K, V> GcHashMap<K, V> {
 	pub fn new() -> Self {
-		Self(Default::default())
+		Self(HashMap::default())
 	}
 	pub fn with_capacity(capacity: usize) -> Self {
 		Self(FxHashMap::with_capacity_and_hasher(
modifiedcrates/jrsonnet-evaluator/src/import.rsdiffbeforeafterboth
--- a/crates/jrsonnet-evaluator/src/import.rs
+++ b/crates/jrsonnet-evaluator/src/import.rs
@@ -79,7 +79,7 @@
 		if direct.exists() {
 			Ok(direct.into())
 		} else {
-			for library_path in self.library_paths.iter() {
+			for library_path in &self.library_paths {
 				let mut cloned = library_path.clone();
 				cloned.push(path);
 				if cloned.exists() {
modifiedcrates/jrsonnet-evaluator/src/lib.rsdiffbeforeafterboth
--- a/crates/jrsonnet-evaluator/src/lib.rs
+++ b/crates/jrsonnet-evaluator/src/lib.rs
@@ -1,7 +1,22 @@
-#![warn(clippy::all, clippy::nursery)]
+#![warn(clippy::all, clippy::nursery, clippy::pedantic)]
 #![allow(
 	macro_expanded_macro_exports_accessed_by_absolute_paths,
-	clippy::ptr_arg
+	clippy::ptr_arg,
+	// Too verbose
+	clippy::must_use_candidate,
+	// A lot of functions pass around errors thrown by code
+	clippy::missing_errors_doc,
+	// A lot of pointers have interior Rc
+	clippy::needless_pass_by_value,
+	// Its fine
+	clippy::wildcard_imports,
+	clippy::enum_glob_use,
+	clippy::module_name_repetitions,
+	// TODO: fix individual issues, however this works as intended almost everywhere
+	clippy::cast_precision_loss,
+	clippy::cast_possible_wrap,
+	clippy::cast_possible_truncation,
+	clippy::cast_sign_loss,
 )]
 
 // For jrsonnet-macros
@@ -105,10 +120,10 @@
 		Self {
 			max_stack: 200,
 			max_trace: 20,
-			globals: Default::default(),
-			ext_vars: Default::default(),
-			ext_natives: Default::default(),
-			tla_vars: Default::default(),
+			globals: HashMap::default(),
+			ext_vars: HashMap::default(),
+			ext_natives: HashMap::default(),
+			tla_vars: HashMap::default(),
 			import_resolver: Box::new(DummyImportResolver),
 			manifest_format: ManifestFormat::Json {
 				padding: 4,
@@ -161,7 +176,7 @@
 		if self.0.is_empty() {
 			return result;
 		}
-		for item in self.0.iter() {
+		for item in &self.0 {
 			if item.loc.belongs_to(loc) {
 				let mut collected = item.collected.borrow_mut();
 				let (depth, vals) = collected.entry(stack_generation).or_default();
@@ -198,7 +213,7 @@
 		)
 		.map_err(|error| ImportSyntaxError {
 			error: Box::new(error),
-			path: path.to_owned(),
+			path: path.clone(),
 			source_code: source_code.clone(),
 		})?;
 		self.add_parsed_file(path, source_code, parsed.clone())?;
@@ -210,7 +225,7 @@
 		self.data_mut()
 			.files
 			.get_mut(name)
-			.unwrap()
+			.expect("file not found")
 			.evaluated
 			.take();
 	}
@@ -246,7 +261,11 @@
 		line: usize,
 		column: usize,
 	) -> Option<usize> {
-		location_to_offset(&self.get_source(file).unwrap(), line, column)
+		location_to_offset(
+			&self.get_source(file).expect("file not found"),
+			line,
+			column,
+		)
 	}
 	pub fn import_file(&self, from: &Path, path: &Path) -> Result<Val> {
 		let file_path = self.resolve_file(from, path)?;
@@ -312,8 +331,10 @@
 			STDLIB_STR.to_owned().into(),
 			builtin::get_parsed_stdlib(),
 		)
-		.unwrap();
-		let val = self.evaluate_loaded_file_raw(&std_path).unwrap();
+		.expect("stdlib is correct");
+		let val = self
+			.evaluate_loaded_file_raw(&std_path)
+			.expect("stdlib is correct");
 		self.settings_mut().globals.insert("std".into(), val);
 		self
 	}
@@ -342,9 +363,8 @@
 				// Error creation uses data, so i drop guard here
 				drop(data);
 				throw!(StackOverflow);
-			} else {
-				*stack_depth += 1;
 			}
+			*stack_depth += 1;
 		}
 		let result = f();
 		{
@@ -376,9 +396,8 @@
 				// Error creation uses data, so i drop guard here
 				drop(data);
 				throw!(StackOverflow);
-			} else {
-				*stack_depth += 1;
 			}
+			*stack_depth += 1;
 		}
 		let mut result = f();
 		{
@@ -411,9 +430,8 @@
 				// Error creation uses data, so i drop guard here
 				drop(data);
 				throw!(StackOverflow);
-			} else {
-				*stack_depth += 1;
 			}
+			*stack_depth += 1;
 		}
 		let result = f();
 		{
@@ -431,6 +449,8 @@
 		result
 	}
 
+	/// # Panics
+	/// In case of formatting failure
 	pub fn stringify_err(&self, e: &LocError) -> String {
 		let mut out = String::new();
 		self.settings()
@@ -1232,49 +1252,5 @@
 		assert_eval!(r#"std.assertEqual(std.count([], ""), 0)"#);
 		assert_eval!(r#"std.assertEqual(std.count(["a", "b", "a"], "d"), 0)"#);
 		assert_eval!(r#"std.assertEqual(std.count(["a", "b", "a"], "a"), 2)"#);
-	}
-
-	mod derive_typed {
-		use std::path::PathBuf;
-
-		use crate::{typed::Typed, State};
-
-		#[derive(PartialEq, Debug, Typed)]
-		struct MyTyped {
-			a: u32,
-			#[typed(rename = "b")]
-			c: String,
-		}
-
-		#[test]
-		fn test() {
-			let es = State::default();
-			let val = eval!("{a: 14, b: 'Hello, world!'}");
-			let typed = MyTyped::try_from(val).unwrap();
-
-			assert_eq!(
-				typed,
-				MyTyped {
-					a: 14,
-					c: "Hello, world!".to_string()
-				}
-			);
-			es.settings_mut()
-				.globals
-				.insert("mytyped".into(), typed.try_into().unwrap());
-
-			let v = es
-				.evaluate_snippet_raw(
-					PathBuf::from("raw.jsonnet").into(),
-					"
-				mytyped == {a: 14, b: 'Hello, world!'}
-			"
-					.into(),
-				)
-				.unwrap()
-				.as_bool()
-				.unwrap();
-			assert!(v)
-		}
 	}
 }
modifiedcrates/jrsonnet-evaluator/src/map.rsdiffbeforeafterboth
--- a/crates/jrsonnet-evaluator/src/map.rs
+++ b/crates/jrsonnet-evaluator/src/map.rs
@@ -34,8 +34,7 @@
 				.0
 				.parent
 				.as_ref()
-				.map(|p| p.contains_key(key))
-				.unwrap_or(false)
+				.map_or(false, |p| p.contains_key(key))
 	}
 }
 
modifiedcrates/jrsonnet-evaluator/src/native.rsdiffbeforeafterboth
--- a/crates/jrsonnet-evaluator/src/native.rs
+++ b/crates/jrsonnet-evaluator/src/native.rs
@@ -37,7 +37,7 @@
 	fn call(&self, s: State, ctx: Context, loc: CallLocation, args: &dyn ArgsLike) -> Result<Val> {
 		let args = parse_builtin_call(s.clone(), ctx, &self.params, args, true)?;
 		let mut out_args = Vec::with_capacity(self.params.len());
-		for p in self.params.iter() {
+		for p in &self.params {
 			out_args.push(args[&p.name].evaluate(s.clone())?);
 		}
 		self.handler.call(s, loc.0.map(|l| l.0.clone()), &out_args)
modifiedcrates/jrsonnet-evaluator/src/obj.rsdiffbeforeafterboth
--- a/crates/jrsonnet-evaluator/src/obj.rs
+++ b/crates/jrsonnet-evaluator/src/obj.rs
@@ -2,6 +2,7 @@
 	cell::RefCell,
 	fmt::Debug,
 	hash::{Hash, Hasher},
+	ptr::addr_of,
 };
 
 use gcmodule::{Cc, Trace, Weak};
@@ -20,6 +21,11 @@
 
 #[cfg(not(feature = "exp-preserve-order"))]
 mod ordering {
+	#![allow(
+		// This module works as stub for preserve-order feature
+		clippy::unused_self,
+	)]
+
 	use gcmodule::Trace;
 
 	#[derive(Clone, Copy, Default, Debug, Trace)]
@@ -89,6 +95,7 @@
 
 use ordering::*;
 
+#[allow(clippy::module_name_repetitions)]
 #[derive(Debug, Trace)]
 pub struct ObjMember {
 	pub add: bool,
@@ -113,6 +120,7 @@
 	Errored(LocError),
 }
 
+#[allow(clippy::module_name_repetitions)]
 #[derive(Trace)]
 #[force_tracking]
 pub struct ObjValueInternals {
@@ -136,10 +144,11 @@
 impl Eq for WeakObjValue {}
 impl Hash for WeakObjValue {
 	fn hash<H: Hasher>(&self, hasher: &mut H) {
-		hasher.write_usize(weak_raw(self.0.clone()) as usize)
+		hasher.write_usize(weak_raw(self.0.clone()) as usize);
 	}
 }
 
+#[allow(clippy::module_name_repetitions)]
 #[derive(Clone, Trace)]
 pub struct ObjValue(pub(crate) Cc<ObjValueInternals>);
 impl Debug for ObjValue {
@@ -178,6 +187,7 @@
 	pub fn new_empty() -> Self {
 		Self::new(None, Cc::new(GcHashMap::new()), Cc::new(Vec::new()))
 	}
+	#[must_use]
 	pub fn extend_from(&self, super_obj: Self) -> Self {
 		match &self.0.super_obj {
 			None => Self::new(
@@ -200,6 +210,8 @@
 	pub fn extend_field(&mut self, name: IStr) -> ObjMemberBuilder<ExtendBuilder> {
 		ObjMemberBuilder::new(ExtendBuilder(self), name, FieldIndex::default())
 	}
+
+	#[must_use]
 	pub fn with_this(&self, this_obj: Self) -> Self {
 		Self(Cc::new(ObjValueInternals {
 			super_obj: self.0.super_obj.clone(),
@@ -222,11 +234,7 @@
 		if !self.0.this_entries.is_empty() {
 			return false;
 		}
-		self.0
-			.super_obj
-			.as_ref()
-			.map(|s| s.is_empty())
-			.unwrap_or(true)
+		self.0.super_obj.as_ref().map_or(true, Self::is_empty)
 	}
 
 	/// Run callback for every field found in object
@@ -254,15 +262,15 @@
 			let new_sort_key = FieldSortKey::new(depth, member.original_index);
 			match member.visibility {
 				Visibility::Normal => {
-					let entry = out.entry(name.to_owned());
+					let entry = out.entry(name.clone());
 					let v = entry.or_insert((true, new_sort_key));
 					v.1 = new_sort_key;
 				}
 				Visibility::Hidden => {
-					out.insert(name.to_owned(), (false, new_sort_key));
+					out.insert(name.clone(), (false, new_sort_key));
 				}
 				Visibility::Unhide => {
-					out.insert(name.to_owned(), (true, new_sort_key));
+					out.insert(name.clone(), (true, new_sort_key));
 				}
 			};
 			false
@@ -356,8 +364,7 @@
 	}
 	pub fn has_field(&self, name: IStr) -> bool {
 		self.field_visibility(name)
-			.map(|v| v.is_visible())
-			.unwrap_or(false)
+			.map_or(false, |v| v.is_visible())
 	}
 
 	pub fn get(&self, s: State, key: IStr) -> Result<Option<Val>> {
@@ -459,10 +466,11 @@
 impl Eq for ObjValue {}
 impl Hash for ObjValue {
 	fn hash<H: Hasher>(&self, hasher: &mut H) {
-		hasher.write_usize(&*self.0 as *const _ as usize)
+		hasher.write_usize(addr_of!(*self.0) as usize);
 	}
 }
 
+#[allow(clippy::module_name_repetitions)]
 pub struct ObjValueBuilder {
 	super_obj: Option<ObjValue>,
 	map: GcHashMap<IStr, ObjMember>,
@@ -510,6 +518,7 @@
 	}
 }
 
+#[allow(clippy::module_name_repetitions)]
 #[must_use = "value not added unless binding() was called"]
 pub struct ObjMemberBuilder<Kind> {
 	kind: Kind,
@@ -583,7 +592,7 @@
 				CallLocation(location.as_ref()),
 				|| format!("field <{}> initializtion", name.clone()),
 				|| throw!(DuplicateFieldName(name.clone())),
-			)?
+			)?;
 		}
 		Ok(())
 	}
@@ -592,14 +601,14 @@
 pub struct ExtendBuilder<'v>(&'v mut ObjValue);
 impl<'v> ObjMemberBuilder<ExtendBuilder<'v>> {
 	pub fn value(self, value: Val) {
-		self.binding(LazyBinding::Bound(LazyVal::new_resolved(value)))
+		self.binding(LazyBinding::Bound(LazyVal::new_resolved(value)));
 	}
 	pub fn bindable(self, bindable: TraceBox<dyn Bindable>) {
-		self.binding(LazyBinding::Bindable(Cc::new(bindable)))
+		self.binding(LazyBinding::Bindable(Cc::new(bindable)));
 	}
 	pub fn binding(self, binding: LazyBinding) {
 		let (receiver, name, member) = self.build_member(binding);
 		let new = receiver.0.clone();
-		*receiver.0 = new.extend_with_raw_member(name, member)
+		*receiver.0 = new.extend_with_raw_member(name, member);
 	}
 }
modifiedcrates/jrsonnet-evaluator/src/trace/location.rsdiffbeforeafterboth
--- a/crates/jrsonnet-evaluator/src/trace/location.rs
+++ b/crates/jrsonnet-evaluator/src/trace/location.rs
@@ -1,3 +1,4 @@
+#[allow(clippy::module_name_repetitions)]
 #[derive(Clone, PartialEq, Debug)]
 pub struct CodeLocation {
 	pub offset: usize,
@@ -9,6 +10,7 @@
 	pub line_end_offset: usize,
 }
 
+#[allow(clippy::module_name_repetitions)]
 pub fn location_to_offset(mut file: &str, mut line: usize, column: usize) -> Option<usize> {
 	let mut offset = 0;
 	while line > 1 {
@@ -21,13 +23,14 @@
 	Some(offset)
 }
 
+#[allow(clippy::module_name_repetitions)]
 pub fn offset_to_location(file: &str, offsets: &[usize]) -> Vec<CodeLocation> {
 	if offsets.is_empty() {
 		return vec![];
 	}
 	let mut line = 1;
 	let mut column = 1;
-	let max_offset = *offsets.iter().max().unwrap();
+	let max_offset = *offsets.iter().max().expect("offsets is not empty");
 
 	let mut offset_map = offsets
 		.iter()
modifiedcrates/jrsonnet-evaluator/src/trace/mod.rsdiffbeforeafterboth
--- a/crates/jrsonnet-evaluator/src/trace/mod.rs
+++ b/crates/jrsonnet-evaluator/src/trace/mod.rs
@@ -19,14 +19,18 @@
 impl PathResolver {
 	pub fn resolve(&self, from: &Path) -> String {
 		match self {
-			Self::FileName => from.file_name().unwrap().to_string_lossy().into_owned(),
+			Self::FileName => from
+				.file_name()
+				.expect("file name exists")
+				.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();
 				}
 				pathdiff::diff_paths(from, base)
-					.unwrap()
+					.expect("base is absolute")
 					.to_string_lossy()
 					.into_owned()
 			}
@@ -35,6 +39,7 @@
 }
 
 /// Implements pretty-printing of traces
+#[allow(clippy::module_name_repetitions)]
 pub trait TraceFormat {
 	fn write_trace(
 		&self,
@@ -88,8 +93,9 @@
 			error,
 		} = error.error()
 		{
+			use std::fmt::Write;
+
 			writeln!(out)?;
-			use std::fmt::Write;
 			let mut n = self.resolver.resolve(path);
 			let mut offset = error.location.offset;
 			let is_eof = if offset >= source_code.len() {
@@ -134,7 +140,7 @@
 		let align = file_names
 			.iter()
 			.flatten()
-			.map(|e| e.len())
+			.map(String::len)
 			.max()
 			.unwrap_or(0);
 		for (el, file) in error.trace().0.iter().zip(file_names) {
@@ -166,7 +172,7 @@
 		error: &LocError,
 	) -> Result<(), std::fmt::Error> {
 		write!(out, "{}", error.error())?;
-		for item in error.trace().0.iter() {
+		for item in &error.trace().0 {
 			writeln!(out)?;
 			let desc = &item.desc;
 			if let Some(source) = &item.location {
@@ -227,7 +233,7 @@
 			)?;
 		}
 		let trace = &error.trace();
-		for item in trace.0.iter() {
+		for item in &trace.0 {
 			writeln!(out)?;
 			let desc = &item.desc;
 			if let Some(source) = &item.location {
@@ -273,7 +279,7 @@
 		let snippet = Snippet {
 			opt: FormatOptions {
 				color: true,
-				..Default::default()
+				..FormatOptions::default()
 			},
 			title: None,
 			footer: vec![],
modifiedcrates/jrsonnet-evaluator/src/typed/conversions.rsdiffbeforeafterboth
--- a/crates/jrsonnet-evaluator/src/typed/conversions.rs
+++ b/crates/jrsonnet-evaluator/src/typed/conversions.rs
@@ -38,6 +38,7 @@
 				<Self as Typed>::TYPE.check(s, &value)?;
 				match value {
 					Val::Num(n) => {
+						#[allow(clippy::float_cmp)]
 						if n.trunc() != n {
 							throw!(RuntimeError(
 								format!(
@@ -95,6 +96,7 @@
 				<Self as Typed>::TYPE.check(s, &value)?;
 				match value {
 					Val::Num(n) => {
+						#[allow(clippy::float_cmp)]
 						if n.trunc() != n {
 							throw!(RuntimeError(
 								format!(
@@ -160,7 +162,7 @@
 impl Typed for usize {
 	// It is possible to store 54 bits of precision in f64, but leaving u32::MAX here for compatibility
 	const TYPE: &'static ComplexValType =
-		&ComplexValType::BoundedNumber(Some(0.0), Some(4294967295.0));
+		&ComplexValType::BoundedNumber(Some(0.0), Some(u32::MAX as f64));
 
 	fn into_untyped(value: Self, _: State) -> Result<Val> {
 		if value > u32::MAX as Self {
@@ -173,6 +175,7 @@
 		<Self as Typed>::TYPE.check(s, &value)?;
 		match value {
 			Val::Num(n) => {
+				#[allow(clippy::float_cmp)]
 				if n.trunc() != n {
 					throw!(RuntimeError(
 						"cannot convert number with fractional part to usize".into()
@@ -263,7 +266,7 @@
 }
 
 /// To be used in Vec<Any>
-/// Regular Val can't be used here, because it has wrong TryFrom::Error type
+/// Regular Val can't be used here, because it has wrong `TryFrom::Error` type
 #[derive(Clone)]
 pub struct Any(pub Val);
 
@@ -279,7 +282,7 @@
 	}
 }
 
-/// Specialization, provides faster TryFrom<VecVal> for Val
+/// Specialization, provides faster `TryFrom<VecVal>` for Val
 pub struct VecVal(pub Cc<Vec<Val>>);
 
 impl Typed for VecVal {
@@ -310,22 +313,20 @@
 	}
 
 	fn from_untyped(value: Val, s: State) -> Result<Self> {
+		if let Val::Arr(ArrValue::Bytes(bytes)) = value {
+			return Ok(Self(bytes));
+		}
+		<Self as Typed>::TYPE.check(s.clone(), &value)?;
 		match value {
-			Val::Arr(ArrValue::Bytes(bytes)) => Ok(Self(bytes)),
-			_ => {
-				<Self as Typed>::TYPE.check(s.clone(), &value)?;
-				match value {
-					Val::Arr(a) => {
-						let mut out = Vec::with_capacity(a.len());
-						for e in a.iter(s.clone()) {
-							let r = e?;
-							out.push(u8::from_untyped(r, s.clone())?);
-						}
-						Ok(Self(out.into()))
-					}
-					_ => unreachable!(),
+			Val::Arr(a) => {
+				let mut out = Vec::with_capacity(a.len());
+				for e in a.iter(s.clone()) {
+					let r = e?;
+					out.push(u8::from_untyped(r, s.clone())?);
 				}
+				Ok(Self(out.into()))
 			}
+			_ => unreachable!(),
 		}
 	}
 }
modifiedcrates/jrsonnet-evaluator/src/typed/mod.rsdiffbeforeafterboth
--- a/crates/jrsonnet-evaluator/src/typed/mod.rs
+++ b/crates/jrsonnet-evaluator/src/typed/mod.rs
@@ -71,11 +71,11 @@
 				if line.trim().is_empty() {
 					continue;
 				}
-				if i != 0 {
+				if i == 0 {
+					write!(f, "  - ")?;
+				} else {
 					writeln!(f)?;
 					write!(f, "    ")?;
-				} else {
-					write!(f, "  - ")?;
 				}
 				write!(f, "{}", line)?;
 			}
@@ -94,7 +94,7 @@
 		Ok(_) => Ok(()),
 		Err(mut e) => {
 			if let Error::TypeError(e) = &mut e.error_mut() {
-				(e.1).0.push(path())
+				(e.1).0.push(path());
 			}
 			Err(e)
 		}
@@ -145,6 +145,7 @@
 }
 
 impl CheckType for ComplexValType {
+	#[allow(clippy::too_many_lines)]
 	fn check(&self, s: State, value: &Val) -> Result<()> {
 		match self {
 			Self::Any => Ok(()),
@@ -202,7 +203,7 @@
 								|| format!("property {}", k),
 								|| ValuePathItem::Field((*k).into()),
 								|| v.check(s.clone(), &got_v),
-							)?
+							)?;
 						} else {
 							return Err(
 								TypeError::MissingProperty((*k).into(), self.clone()).into()
@@ -245,13 +246,13 @@
 			}
 			Self::Sum(types) => {
 				for ty in types.iter() {
-					ty.check(s.clone(), value)?
+					ty.check(s.clone(), value)?;
 				}
 				Ok(())
 			}
 			Self::SumRef(types) => {
 				for ty in types.iter() {
-					ty.check(s.clone(), value)?
+					ty.check(s.clone(), value)?;
 				}
 				Ok(())
 			}
modifiedcrates/jrsonnet-evaluator/src/val.rsdiffbeforeafterboth
before · crates/jrsonnet-evaluator/src/val.rs
1use std::{cell::RefCell, fmt::Debug, rc::Rc};23use gcmodule::{Cc, Trace};4use jrsonnet_interner::IStr;5use jrsonnet_parser::{LocExpr, ParamsDesc};6use jrsonnet_types::ValType;78use crate::{9	builtin::manifest::{10		manifest_json_ex, manifest_yaml_ex, ManifestJsonOptions, ManifestType, ManifestYamlOptions,11	},12	cc_ptr_eq,13	error::{Error::*, LocError},14	evaluate,15	function::{16		parse_default_function_call, parse_function_call, ArgsLike, Builtin, CallLocation,17		StaticBuiltin,18	},19	gc::TraceBox,20	throw, Context, ObjValue, Result, State,21};2223pub trait LazyValValue: Trace {24	fn get(self: Box<Self>, s: State) -> Result<Val>;25}2627#[derive(Trace)]28enum LazyValInternals {29	Computed(Val),30	Errored(LocError),31	Waiting(TraceBox<dyn LazyValValue>),32	Pending,33}3435#[derive(Clone, Trace)]36pub struct LazyVal(Cc<RefCell<LazyValInternals>>);37impl LazyVal {38	pub fn new(f: TraceBox<dyn LazyValValue>) -> Self {39		Self(Cc::new(RefCell::new(LazyValInternals::Waiting(f))))40	}41	pub fn new_resolved(val: Val) -> Self {42		Self(Cc::new(RefCell::new(LazyValInternals::Computed(val))))43	}44	pub fn force(&self, s: State) -> Result<()> {45		self.evaluate(s)?;46		Ok(())47	}48	pub fn evaluate(&self, s: State) -> Result<Val> {49		match &*self.0.borrow() {50			LazyValInternals::Computed(v) => return Ok(v.clone()),51			LazyValInternals::Errored(e) => return Err(e.clone()),52			LazyValInternals::Pending => return Err(InfiniteRecursionDetected.into()),53			_ => (),54		};55		let value = if let LazyValInternals::Waiting(value) =56			std::mem::replace(&mut *self.0.borrow_mut(), LazyValInternals::Pending)57		{58			value59		} else {60			unreachable!()61		};62		let new_value = match value.0.get(s) {63			Ok(v) => v,64			Err(e) => {65				*self.0.borrow_mut() = LazyValInternals::Errored(e.clone());66				return Err(e);67			}68		};69		*self.0.borrow_mut() = LazyValInternals::Computed(new_value.clone());70		Ok(new_value)71	}72}7374impl Debug for LazyVal {75	fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {76		write!(f, "Lazy")77	}78}79impl PartialEq for LazyVal {80	fn eq(&self, other: &Self) -> bool {81		cc_ptr_eq(&self.0, &other.0)82	}83}8485#[derive(Debug, PartialEq, Trace)]86pub struct FuncDesc {87	pub name: IStr,88	pub ctx: Context,89	pub params: ParamsDesc,90	pub body: LocExpr,91}92impl FuncDesc {93	/// Create body context, but fill arguments without defaults with lazy error94	pub fn default_body_context(&self) -> Context {95		parse_default_function_call(self.ctx.clone(), &self.params)96	}9798	/// Create context, with which body code will run99	pub fn call_body_context(100		&self,101		s: State,102		call_ctx: Context,103		args: &dyn ArgsLike,104		tailstrict: bool,105	) -> Result<Context> {106		parse_function_call(107			s,108			call_ctx,109			self.ctx.clone(),110			&self.params,111			args,112			tailstrict,113		)114	}115}116117#[derive(Trace, Clone)]118pub enum FuncVal {119	/// Plain function implemented in jsonnet120	Normal(Cc<FuncDesc>),121	/// Standard library function122	StaticBuiltin(#[skip_trace] &'static dyn StaticBuiltin),123	/// User-provided function124	Builtin(Cc<TraceBox<dyn Builtin>>),125}126127impl Debug for FuncVal {128	fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {129		match self {130			Self::Normal(arg0) => f.debug_tuple("Normal").field(arg0).finish(),131			Self::StaticBuiltin(arg0) => {132				f.debug_tuple("StaticBuiltin").field(&arg0.name()).finish()133			}134			Self::Builtin(arg0) => f.debug_tuple("Builtin").field(&arg0.name()).finish(),135		}136	}137}138139impl FuncVal {140	pub fn args_len(&self) -> usize {141		match self {142			Self::Normal(n) => n.params.iter().filter(|p| p.1.is_none()).count(),143			Self::StaticBuiltin(i) => i.params().iter().filter(|p| !p.has_default).count(),144			Self::Builtin(i) => i.params().iter().filter(|p| !p.has_default).count(),145		}146	}147	pub fn name(&self) -> IStr {148		match self {149			Self::Normal(normal) => normal.name.clone(),150			Self::StaticBuiltin(builtin) => builtin.name().into(),151			Self::Builtin(builtin) => builtin.name().into(),152		}153	}154	pub fn evaluate(155		&self,156		s: State,157		call_ctx: Context,158		loc: CallLocation,159		args: &dyn ArgsLike,160		tailstrict: bool,161	) -> Result<Val> {162		match self {163			Self::Normal(func) => {164				let body_ctx = func.call_body_context(s.clone(), call_ctx, args, tailstrict)?;165				evaluate(s, body_ctx, &func.body)166			}167			Self::StaticBuiltin(b) => b.call(s, call_ctx, loc, args),168			Self::Builtin(b) => b.call(s, call_ctx, loc, args),169		}170	}171	pub fn evaluate_simple(&self, s: State, args: &dyn ArgsLike) -> Result<Val> {172		self.evaluate(s, Context::default(), CallLocation::native(), args, true)173	}174}175176#[derive(Clone)]177pub enum ManifestFormat {178	YamlStream(Box<ManifestFormat>),179	Yaml {180		padding: usize,181		#[cfg(feature = "exp-preserve-order")]182		preserve_order: bool,183	},184	Json {185		padding: usize,186		#[cfg(feature = "exp-preserve-order")]187		preserve_order: bool,188	},189	ToString,190	String,191}192impl ManifestFormat {193	#[cfg(feature = "exp-preserve-order")]194	fn preserve_order(&self) -> bool {195		match self {196			ManifestFormat::YamlStream(s) => s.preserve_order(),197			ManifestFormat::Yaml { preserve_order, .. } => *preserve_order,198			ManifestFormat::Json { preserve_order, .. } => *preserve_order,199			ManifestFormat::ToString => false,200			ManifestFormat::String => false,201		}202	}203}204205#[derive(Debug, Clone, Trace)]206pub struct Slice {207	pub(crate) inner: ArrValue,208	pub(crate) from: u32,209	pub(crate) to: u32,210	pub(crate) step: u32,211}212impl Slice {213	const fn from(&self) -> usize {214		self.from as usize215	}216	const fn to(&self) -> usize {217		self.to as usize218	}219	const fn step(&self) -> usize {220		self.step as usize221	}222	const fn len(&self) -> usize {223		// TODO: use div_ceil224		let diff = self.to() - self.from();225		let rem = diff % self.step();226		let div = diff / self.step();227228		if rem != 0 {229			div + 1230		} else {231			div232		}233	}234}235236#[derive(Debug, Clone, Trace)]237#[force_tracking]238pub enum ArrValue {239	Bytes(#[skip_trace] Rc<[u8]>),240	Lazy(Cc<Vec<LazyVal>>),241	Eager(Cc<Vec<Val>>),242	Extended(Box<(Self, Self)>),243	Range(i32, i32),244	Slice(Box<Slice>),245	Reversed(Box<Self>),246}247impl ArrValue {248	pub fn new_eager() -> Self {249		Self::Eager(Cc::new(Vec::new()))250	}251	pub fn new_range(a: i32, b: i32) -> Self {252		assert!(a <= b);253		Self::Range(a, b)254	}255256	pub fn slice(self, from: Option<usize>, to: Option<usize>, step: Option<usize>) -> Self {257		let len = self.len();258		let from = from.unwrap_or(0);259		let to = to.unwrap_or(len).min(len);260		let step = step.unwrap_or(1);261		assert!(from < to);262		assert!(step > 0);263264		Self::Slice(Box::new(Slice {265			inner: self,266			from: from as u32,267			to: to as u32,268			step: step as u32,269		}))270	}271272	pub fn len(&self) -> usize {273		match self {274			Self::Bytes(i) => i.len(),275			Self::Lazy(l) => l.len(),276			Self::Eager(e) => e.len(),277			Self::Extended(v) => v.0.len() + v.1.len(),278			Self::Range(a, b) => a.abs_diff(*b) as usize + 1,279			Self::Reversed(i) => i.len(),280			Self::Slice(s) => s.len(),281		}282	}283284	pub fn is_empty(&self) -> bool {285		self.len() == 0286	}287288	pub fn get(&self, s: State, index: usize) -> Result<Option<Val>> {289		match self {290			Self::Bytes(i) => i291				.get(index)292				.map_or(Ok(None), |v| Ok(Some(Val::Num(*v as f64)))),293			Self::Lazy(vec) => {294				if let Some(v) = vec.get(index) {295					Ok(Some(v.evaluate(s)?))296				} else {297					Ok(None)298				}299			}300			Self::Eager(vec) => Ok(vec.get(index).cloned()),301			Self::Extended(v) => {302				let a_len = v.0.len();303				if a_len > index {304					v.0.get(s, index)305				} else {306					v.1.get(s, index - a_len)307				}308			}309			Self::Range(a, _) => {310				if index >= self.len() {311					return Ok(None);312				}313				Ok(Some(Val::Num(((*a as isize) + index as isize) as f64)))314			}315			Self::Reversed(v) => {316				let len = v.len();317				if index >= len {318					return Ok(None);319				}320				v.get(s, len - index - 1)321			}322			Self::Slice(v) => {323				let index = v.from() + index * v.step();324				if index >= v.to() {325					return Ok(None);326				}327				v.inner.get(s, index as usize)328			}329		}330	}331332	pub fn get_lazy(&self, index: usize) -> Option<LazyVal> {333		match self {334			Self::Bytes(i) => i335				.get(index)336				.map(|b| LazyVal::new_resolved(Val::Num(*b as f64))),337			Self::Lazy(vec) => vec.get(index).cloned(),338			Self::Eager(vec) => vec.get(index).cloned().map(LazyVal::new_resolved),339			Self::Extended(v) => {340				let a_len = v.0.len();341				if a_len > index {342					v.0.get_lazy(index)343				} else {344					v.1.get_lazy(index - a_len)345				}346			}347			Self::Range(a, _) => {348				if index >= self.len() {349					return None;350				}351				Some(LazyVal::new_resolved(Val::Num(352					((*a as isize) + index as isize) as f64,353				)))354			}355			Self::Reversed(v) => {356				let len = v.len();357				if index >= len {358					return None;359				}360				v.get_lazy(len - index - 1)361			}362			Self::Slice(s) => {363				let index = s.from() + index * s.step();364				if index >= s.to() {365					return None;366				}367				s.inner.get_lazy(index as usize)368			}369		}370	}371372	pub fn evaluated(&self, s: State) -> Result<Cc<Vec<Val>>> {373		Ok(match self {374			Self::Bytes(i) => {375				let mut out = Vec::with_capacity(i.len());376				for v in i.iter() {377					out.push(Val::Num(*v as f64));378				}379				Cc::new(out)380			}381			Self::Lazy(vec) => {382				let mut out = Vec::with_capacity(vec.len());383				for item in vec.iter() {384					out.push(item.evaluate(s.clone())?);385				}386				Cc::new(out)387			}388			Self::Eager(vec) => vec.clone(),389			Self::Extended(_v) => {390				let mut out = Vec::with_capacity(self.len());391				for item in self.iter(s) {392					out.push(item?);393				}394				Cc::new(out)395			}396			Self::Range(a, b) => {397				let mut out = Vec::with_capacity(self.len());398				for i in *a..*b {399					out.push(Val::Num(i as f64));400				}401				Cc::new(out)402			}403			Self::Reversed(r) => {404				let mut r = r.evaluated(s)?;405				Cc::update_with(&mut r, |v| v.reverse());406				r407			}408			Self::Slice(v) => {409				let mut out = Vec::with_capacity(v.inner.len());410				for v in v411					.inner412					.iter_lazy()413					.skip(v.from())414					.take(v.to() - v.from())415					.step_by(v.step())416				{417					out.push(v.evaluate(s.clone())?)418				}419				Cc::new(out)420			}421		})422	}423424	pub fn iter(&self, s: State) -> impl DoubleEndedIterator<Item = Result<Val>> + '_ {425		(0..self.len()).map(move |idx| match self {426			Self::Bytes(b) => Ok(Val::Num(b[idx] as f64)),427			Self::Lazy(l) => l[idx].evaluate(s.clone()),428			Self::Eager(e) => Ok(e[idx].clone()),429			Self::Extended(_) => self.get(s.clone(), idx).map(|e| e.unwrap()),430			Self::Range(..) => self.get(s.clone(), idx).map(|e| e.unwrap()),431			Self::Reversed(..) => self.get(s.clone(), idx).map(|e| e.unwrap()),432			Self::Slice(..) => self.get(s.clone(), idx).map(|e| e.unwrap()),433		})434	}435436	pub fn iter_lazy(&self) -> impl DoubleEndedIterator<Item = LazyVal> + '_ {437		(0..self.len()).map(move |idx| match self {438			Self::Bytes(b) => LazyVal::new_resolved(Val::Num(b[idx] as f64)),439			Self::Lazy(l) => l[idx].clone(),440			Self::Eager(e) => LazyVal::new_resolved(e[idx].clone()),441			Self::Extended(_) => self.get_lazy(idx).unwrap(),442			Self::Range(..) => self.get_lazy(idx).unwrap(),443			Self::Reversed(..) => self.get_lazy(idx).unwrap(),444			Self::Slice(..) => self.get_lazy(idx).unwrap(),445		})446	}447448	pub fn reversed(self) -> Self {449		Self::Reversed(Box::new(self))450	}451452	pub fn map(self, s: State, mapper: impl Fn(Val) -> Result<Val>) -> Result<Self> {453		let mut out = Vec::with_capacity(self.len());454455		for value in self.iter(s) {456			out.push(mapper(value?)?);457		}458459		Ok(Self::Eager(Cc::new(out)))460	}461462	pub fn filter(self, s: State, filter: impl Fn(&Val) -> Result<bool>) -> Result<Self> {463		let mut out = Vec::with_capacity(self.len());464465		for value in self.iter(s) {466			let value = value?;467			if filter(&value)? {468				out.push(value);469			}470		}471472		Ok(Self::Eager(Cc::new(out)))473	}474475	pub fn ptr_eq(a: &Self, b: &Self) -> bool {476		match (a, b) {477			(Self::Lazy(a), Self::Lazy(b)) => cc_ptr_eq(a, b),478			(Self::Eager(a), Self::Eager(b)) => cc_ptr_eq(a, b),479			_ => false,480		}481	}482}483484impl From<Vec<LazyVal>> for ArrValue {485	fn from(v: Vec<LazyVal>) -> Self {486		Self::Lazy(Cc::new(v))487	}488}489490impl From<Vec<Val>> for ArrValue {491	fn from(v: Vec<Val>) -> Self {492		Self::Eager(Cc::new(v))493	}494}495496pub enum IndexableVal {497	Str(IStr),498	Arr(ArrValue),499}500501#[derive(Debug, Clone, Trace)]502pub enum Val {503	Bool(bool),504	Null,505	Str(IStr),506	Num(f64),507	Arr(ArrValue),508	Obj(ObjValue),509	Func(FuncVal),510}511512impl Val {513	pub const fn as_bool(&self) -> Option<bool> {514		match self {515			Val::Bool(v) => Some(*v),516			_ => None,517		}518	}519	pub const fn as_null(&self) -> Option<()> {520		match self {521			Val::Null => Some(()),522			_ => None,523		}524	}525	pub fn as_str(&self) -> Option<IStr> {526		match self {527			Val::Str(s) => Some(s.clone()),528			_ => None,529		}530	}531	pub const fn as_num(&self) -> Option<f64> {532		match self {533			Val::Num(n) => Some(*n),534			_ => None,535		}536	}537	pub fn as_arr(&self) -> Option<ArrValue> {538		match self {539			Val::Arr(a) => Some(a.clone()),540			_ => None,541		}542	}543	pub fn as_obj(&self) -> Option<ObjValue> {544		match self {545			Val::Obj(o) => Some(o.clone()),546			_ => None,547		}548	}549	pub fn as_func(&self) -> Option<FuncVal> {550		match self {551			Val::Func(f) => Some(f.clone()),552			_ => None,553		}554	}555556	/// Creates `Val::Num` after checking for numeric overflow.557	/// As numbers are `f64`, we can just check for their finity.558	pub fn new_checked_num(num: f64) -> Result<Self> {559		if num.is_finite() {560			Ok(Self::Num(num))561		} else {562			throw!(RuntimeError("overflow".into()))563		}564	}565566	pub const fn value_type(&self) -> ValType {567		match self {568			Self::Str(..) => ValType::Str,569			Self::Num(..) => ValType::Num,570			Self::Arr(..) => ValType::Arr,571			Self::Obj(..) => ValType::Obj,572			Self::Bool(_) => ValType::Bool,573			Self::Null => ValType::Null,574			Self::Func(..) => ValType::Func,575		}576	}577578	pub fn to_string(&self, s: State) -> Result<IStr> {579		Ok(match self {580			Self::Bool(true) => "true".into(),581			Self::Bool(false) => "false".into(),582			Self::Null => "null".into(),583			Self::Str(s) => s.clone(),584			v => manifest_json_ex(585				s,586				v,587				&ManifestJsonOptions {588					padding: "",589					mtype: ManifestType::ToString,590					newline: "\n",591					key_val_sep: ": ",592					#[cfg(feature = "exp-preserve-order")]593					preserve_order: false,594				},595			)?596			.into(),597		})598	}599600	/// Expects value to be object, outputs (key, manifested value) pairs601	pub fn manifest_multi(&self, s: State, ty: &ManifestFormat) -> Result<Vec<(IStr, IStr)>> {602		let obj = match self {603			Self::Obj(obj) => obj,604			_ => throw!(MultiManifestOutputIsNotAObject),605		};606		let keys = obj.fields(607			#[cfg(feature = "exp-preserve-order")]608			ty.preserve_order(),609		);610		let mut out = Vec::with_capacity(keys.len());611		for key in keys {612			let value = obj613				.get(s.clone(), key.clone())?614				.expect("item in object")615				.manifest(s.clone(), ty)?;616			out.push((key, value));617		}618		Ok(out)619	}620621	/// Expects value to be array, outputs manifested values622	pub fn manifest_stream(&self, s: State, ty: &ManifestFormat) -> Result<Vec<IStr>> {623		let arr = match self {624			Self::Arr(a) => a,625			_ => throw!(StreamManifestOutputIsNotAArray),626		};627		let mut out = Vec::with_capacity(arr.len());628		for i in arr.iter(s.clone()) {629			out.push(i?.manifest(s.clone(), ty)?);630		}631		Ok(out)632	}633634	pub fn manifest(&self, s: State, ty: &ManifestFormat) -> Result<IStr> {635		Ok(match ty {636			ManifestFormat::YamlStream(format) => {637				let arr = match self {638					Self::Arr(a) => a,639					_ => throw!(StreamManifestOutputIsNotAArray),640				};641				let mut out = String::new();642643				match format as &ManifestFormat {644					ManifestFormat::YamlStream(_) => throw!(StreamManifestOutputCannotBeRecursed),645					ManifestFormat::String => throw!(StreamManifestCannotNestString),646					_ => {}647				};648649				if !arr.is_empty() {650					for v in arr.iter(s.clone()) {651						out.push_str("---\n");652						out.push_str(&v?.manifest(s.clone(), format)?);653						out.push('\n');654					}655					out.push_str("...");656				}657658				out.into()659			}660			ManifestFormat::Yaml {661				padding,662				#[cfg(feature = "exp-preserve-order")]663				preserve_order,664			} => self.to_yaml(665				s,666				*padding,667				#[cfg(feature = "exp-preserve-order")]668				*preserve_order,669			)?,670			ManifestFormat::Json {671				padding,672				#[cfg(feature = "exp-preserve-order")]673				preserve_order,674			} => self.to_json(675				s,676				*padding,677				#[cfg(feature = "exp-preserve-order")]678				*preserve_order,679			)?,680			ManifestFormat::ToString => self.to_string(s)?,681			ManifestFormat::String => match self {682				Self::Str(s) => s.clone(),683				_ => throw!(StringManifestOutputIsNotAString),684			},685		})686	}687688	/// For manifestification689	pub fn to_json(690		&self,691		s: State,692		padding: usize,693		#[cfg(feature = "exp-preserve-order")] preserve_order: bool,694	) -> Result<IStr> {695		manifest_json_ex(696			s,697			self,698			&ManifestJsonOptions {699				padding: &" ".repeat(padding),700				mtype: if padding == 0 {701					ManifestType::Minify702				} else {703					ManifestType::Manifest704				},705				newline: "\n",706				key_val_sep: ": ",707				#[cfg(feature = "exp-preserve-order")]708				preserve_order,709			},710		)711		.map(|s| s.into())712	}713714	/// Calls `std.manifestJson`715	pub fn to_std_json(716		&self,717		s: State,718		padding: usize,719		#[cfg(feature = "exp-preserve-order")] preserve_order: bool,720	) -> Result<Rc<str>> {721		manifest_json_ex(722			s,723			self,724			&ManifestJsonOptions {725				padding: &" ".repeat(padding),726				mtype: ManifestType::Std,727				newline: "\n",728				key_val_sep: ": ",729				#[cfg(feature = "exp-preserve-order")]730				preserve_order,731			},732		)733		.map(|s| s.into())734	}735736	pub fn to_yaml(737		&self,738		s: State,739		padding: usize,740		#[cfg(feature = "exp-preserve-order")] preserve_order: bool,741	) -> Result<IStr> {742		let padding = &" ".repeat(padding);743		manifest_yaml_ex(744			s,745			self,746			&ManifestYamlOptions {747				padding,748				arr_element_padding: padding,749				quote_keys: false,750				#[cfg(feature = "exp-preserve-order")]751				preserve_order,752			},753		)754		.map(|s| s.into())755	}756	pub fn into_indexable(self) -> Result<IndexableVal> {757		Ok(match self {758			Val::Str(s) => IndexableVal::Str(s),759			Val::Arr(arr) => IndexableVal::Arr(arr),760			_ => throw!(ValueIsNotIndexable(self.value_type())),761		})762	}763}764765const fn is_function_like(val: &Val) -> bool {766	matches!(val, Val::Func(_))767}768769/// Native implementation of `std.primitiveEquals`770pub fn primitive_equals(val_a: &Val, val_b: &Val) -> Result<bool> {771	Ok(match (val_a, val_b) {772		(Val::Bool(a), Val::Bool(b)) => a == b,773		(Val::Null, Val::Null) => true,774		(Val::Str(a), Val::Str(b)) => a == b,775		(Val::Num(a), Val::Num(b)) => (a - b).abs() <= f64::EPSILON,776		(Val::Arr(_), Val::Arr(_)) => throw!(RuntimeError(777			"primitiveEquals operates on primitive types, got array".into(),778		)),779		(Val::Obj(_), Val::Obj(_)) => throw!(RuntimeError(780			"primitiveEquals operates on primitive types, got object".into(),781		)),782		(a, b) if is_function_like(a) && is_function_like(b) => {783			throw!(RuntimeError("cannot test equality of functions".into()))784		}785		(_, _) => false,786	})787}788789/// Native implementation of `std.equals`790pub fn equals(s: State, val_a: &Val, val_b: &Val) -> Result<bool> {791	if val_a.value_type() != val_b.value_type() {792		return Ok(false);793	}794	match (val_a, val_b) {795		(Val::Arr(a), Val::Arr(b)) => {796			if ArrValue::ptr_eq(a, b) {797				return Ok(true);798			}799			if a.len() != b.len() {800				return Ok(false);801			}802			for (a, b) in a.iter(s.clone()).zip(b.iter(s.clone())) {803				if !equals(s.clone(), &a?, &b?)? {804					return Ok(false);805				}806			}807			Ok(true)808		}809		(Val::Obj(a), Val::Obj(b)) => {810			if ObjValue::ptr_eq(a, b) {811				return Ok(true);812			}813			let fields = a.fields(814				#[cfg(feature = "exp-preserve-order")]815				false,816			);817			if fields818				!= b.fields(819					#[cfg(feature = "exp-preserve-order")]820					false,821				) {822				return Ok(false);823			}824			for field in fields {825				if !equals(826					s.clone(),827					&a.get(s.clone(), field.clone())?.unwrap(),828					&b.get(s.clone(), field)?.unwrap(),829				)? {830					return Ok(false);831				}832			}833			Ok(true)834		}835		(a, b) => Ok(primitive_equals(a, b)?),836	}837}
after · crates/jrsonnet-evaluator/src/val.rs
1use std::{cell::RefCell, fmt::Debug, rc::Rc};23use gcmodule::{Cc, Trace};4use jrsonnet_interner::IStr;5use jrsonnet_parser::{LocExpr, ParamsDesc};6use jrsonnet_types::ValType;78use crate::{9	builtin::manifest::{10		manifest_json_ex, manifest_yaml_ex, ManifestJsonOptions, ManifestType, ManifestYamlOptions,11	},12	cc_ptr_eq,13	error::{Error::*, LocError},14	evaluate,15	function::{16		parse_default_function_call, parse_function_call, ArgsLike, Builtin, CallLocation,17		StaticBuiltin,18	},19	gc::TraceBox,20	throw, Context, ObjValue, Result, State,21};2223pub trait LazyValValue: Trace {24	fn get(self: Box<Self>, s: State) -> Result<Val>;25}2627#[derive(Trace)]28enum LazyValInternals {29	Computed(Val),30	Errored(LocError),31	Waiting(TraceBox<dyn LazyValValue>),32	Pending,33}3435#[allow(clippy::module_name_repetitions)]36#[derive(Clone, Trace)]37pub struct LazyVal(Cc<RefCell<LazyValInternals>>);38impl LazyVal {39	pub fn new(f: TraceBox<dyn LazyValValue>) -> Self {40		Self(Cc::new(RefCell::new(LazyValInternals::Waiting(f))))41	}42	pub fn new_resolved(val: Val) -> Self {43		Self(Cc::new(RefCell::new(LazyValInternals::Computed(val))))44	}45	pub fn force(&self, s: State) -> Result<()> {46		self.evaluate(s)?;47		Ok(())48	}49	pub fn evaluate(&self, s: State) -> Result<Val> {50		match &*self.0.borrow() {51			LazyValInternals::Computed(v) => return Ok(v.clone()),52			LazyValInternals::Errored(e) => return Err(e.clone()),53			LazyValInternals::Pending => return Err(InfiniteRecursionDetected.into()),54			LazyValInternals::Waiting(..) => (),55		};56		let value = if let LazyValInternals::Waiting(value) =57			std::mem::replace(&mut *self.0.borrow_mut(), LazyValInternals::Pending)58		{59			value60		} else {61			unreachable!()62		};63		let new_value = match value.0.get(s) {64			Ok(v) => v,65			Err(e) => {66				*self.0.borrow_mut() = LazyValInternals::Errored(e.clone());67				return Err(e);68			}69		};70		*self.0.borrow_mut() = LazyValInternals::Computed(new_value.clone());71		Ok(new_value)72	}73}7475impl Debug for LazyVal {76	fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {77		write!(f, "Lazy")78	}79}80impl PartialEq for LazyVal {81	fn eq(&self, other: &Self) -> bool {82		cc_ptr_eq(&self.0, &other.0)83	}84}8586#[derive(Debug, PartialEq, Trace)]87pub struct FuncDesc {88	pub name: IStr,89	pub ctx: Context,90	pub params: ParamsDesc,91	pub body: LocExpr,92}93impl FuncDesc {94	/// Create body context, but fill arguments without defaults with lazy error95	pub fn default_body_context(&self) -> Context {96		parse_default_function_call(self.ctx.clone(), &self.params)97	}9899	/// Create context, with which body code will run100	pub fn call_body_context(101		&self,102		s: State,103		call_ctx: Context,104		args: &dyn ArgsLike,105		tailstrict: bool,106	) -> Result<Context> {107		parse_function_call(108			s,109			call_ctx,110			self.ctx.clone(),111			&self.params,112			args,113			tailstrict,114		)115	}116}117118#[allow(clippy::module_name_repetitions)]119#[derive(Trace, Clone)]120pub enum FuncVal {121	/// Plain function implemented in jsonnet122	Normal(Cc<FuncDesc>),123	/// Standard library function124	StaticBuiltin(#[skip_trace] &'static dyn StaticBuiltin),125	/// User-provided function126	Builtin(Cc<TraceBox<dyn Builtin>>),127}128129impl Debug for FuncVal {130	fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {131		match self {132			Self::Normal(arg0) => f.debug_tuple("Normal").field(arg0).finish(),133			Self::StaticBuiltin(arg0) => {134				f.debug_tuple("StaticBuiltin").field(&arg0.name()).finish()135			}136			Self::Builtin(arg0) => f.debug_tuple("Builtin").field(&arg0.name()).finish(),137		}138	}139}140141impl FuncVal {142	pub fn args_len(&self) -> usize {143		match self {144			Self::Normal(n) => n.params.iter().filter(|p| p.1.is_none()).count(),145			Self::StaticBuiltin(i) => i.params().iter().filter(|p| !p.has_default).count(),146			Self::Builtin(i) => i.params().iter().filter(|p| !p.has_default).count(),147		}148	}149	pub fn name(&self) -> IStr {150		match self {151			Self::Normal(normal) => normal.name.clone(),152			Self::StaticBuiltin(builtin) => builtin.name().into(),153			Self::Builtin(builtin) => builtin.name().into(),154		}155	}156	pub fn evaluate(157		&self,158		s: State,159		call_ctx: Context,160		loc: CallLocation,161		args: &dyn ArgsLike,162		tailstrict: bool,163	) -> Result<Val> {164		match self {165			Self::Normal(func) => {166				let body_ctx = func.call_body_context(s.clone(), call_ctx, args, tailstrict)?;167				evaluate(s, body_ctx, &func.body)168			}169			Self::StaticBuiltin(b) => b.call(s, call_ctx, loc, args),170			Self::Builtin(b) => b.call(s, call_ctx, loc, args),171		}172	}173	pub fn evaluate_simple(&self, s: State, args: &dyn ArgsLike) -> Result<Val> {174		self.evaluate(s, Context::default(), CallLocation::native(), args, true)175	}176}177178#[derive(Clone)]179pub enum ManifestFormat {180	YamlStream(Box<ManifestFormat>),181	Yaml {182		padding: usize,183		#[cfg(feature = "exp-preserve-order")]184		preserve_order: bool,185	},186	Json {187		padding: usize,188		#[cfg(feature = "exp-preserve-order")]189		preserve_order: bool,190	},191	ToString,192	String,193}194impl ManifestFormat {195	#[cfg(feature = "exp-preserve-order")]196	fn preserve_order(&self) -> bool {197		match self {198			ManifestFormat::YamlStream(s) => s.preserve_order(),199			ManifestFormat::Yaml { preserve_order, .. } => *preserve_order,200			ManifestFormat::Json { preserve_order, .. } => *preserve_order,201			ManifestFormat::ToString => false,202			ManifestFormat::String => false,203		}204	}205}206207#[derive(Debug, Clone, Trace)]208pub struct Slice {209	pub(crate) inner: ArrValue,210	pub(crate) from: u32,211	pub(crate) to: u32,212	pub(crate) step: u32,213}214impl Slice {215	const fn from(&self) -> usize {216		self.from as usize217	}218	const fn to(&self) -> usize {219		self.to as usize220	}221	const fn step(&self) -> usize {222		self.step as usize223	}224	const fn len(&self) -> usize {225		// TODO: use div_ceil226		let diff = self.to() - self.from();227		let rem = diff % self.step();228		let div = diff / self.step();229230		if rem == 0 {231			div232		} else {233			div + 1234		}235	}236}237238#[derive(Debug, Clone, Trace)]239#[force_tracking]240pub enum ArrValue {241	Bytes(#[skip_trace] Rc<[u8]>),242	Lazy(Cc<Vec<LazyVal>>),243	Eager(Cc<Vec<Val>>),244	Extended(Box<(Self, Self)>),245	Range(i32, i32),246	Slice(Box<Slice>),247	Reversed(Box<Self>),248}249impl ArrValue {250	pub fn new_eager() -> Self {251		Self::Eager(Cc::new(Vec::new()))252	}253254	/// # Panics255	/// If a > b256	pub fn new_range(a: i32, b: i32) -> Self {257		assert!(a <= b);258		Self::Range(a, b)259	}260261	/// # Panics262	/// If passed numbers are incorrect263	#[must_use]264	pub fn slice(self, from: Option<usize>, to: Option<usize>, step: Option<usize>) -> Self {265		let len = self.len();266		let from = from.unwrap_or(0);267		let to = to.unwrap_or(len).min(len);268		let step = step.unwrap_or(1);269		assert!(from < to);270		assert!(step > 0);271272		Self::Slice(Box::new(Slice {273			inner: self,274			from: from as u32,275			to: to as u32,276			step: step as u32,277		}))278	}279280	pub fn len(&self) -> usize {281		match self {282			Self::Bytes(i) => i.len(),283			Self::Lazy(l) => l.len(),284			Self::Eager(e) => e.len(),285			Self::Extended(v) => v.0.len() + v.1.len(),286			Self::Range(a, b) => a.abs_diff(*b) as usize + 1,287			Self::Reversed(i) => i.len(),288			Self::Slice(s) => s.len(),289		}290	}291292	pub fn is_empty(&self) -> bool {293		self.len() == 0294	}295296	pub fn get(&self, s: State, index: usize) -> Result<Option<Val>> {297		match self {298			Self::Bytes(i) => i299				.get(index)300				.map_or(Ok(None), |v| Ok(Some(Val::Num(f64::from(*v))))),301			Self::Lazy(vec) => {302				if let Some(v) = vec.get(index) {303					Ok(Some(v.evaluate(s)?))304				} else {305					Ok(None)306				}307			}308			Self::Eager(vec) => Ok(vec.get(index).cloned()),309			Self::Extended(v) => {310				let a_len = v.0.len();311				if a_len > index {312					v.0.get(s, index)313				} else {314					v.1.get(s, index - a_len)315				}316			}317			Self::Range(a, _) => {318				if index >= self.len() {319					return Ok(None);320				}321				Ok(Some(Val::Num(((*a as isize) + index as isize) as f64)))322			}323			Self::Reversed(v) => {324				let len = v.len();325				if index >= len {326					return Ok(None);327				}328				v.get(s, len - index - 1)329			}330			Self::Slice(v) => {331				let index = v.from() + index * v.step();332				if index >= v.to() {333					return Ok(None);334				}335				v.inner.get(s, index as usize)336			}337		}338	}339340	pub fn get_lazy(&self, index: usize) -> Option<LazyVal> {341		match self {342			Self::Bytes(i) => i343				.get(index)344				.map(|b| LazyVal::new_resolved(Val::Num(f64::from(*b)))),345			Self::Lazy(vec) => vec.get(index).cloned(),346			Self::Eager(vec) => vec.get(index).cloned().map(LazyVal::new_resolved),347			Self::Extended(v) => {348				let a_len = v.0.len();349				if a_len > index {350					v.0.get_lazy(index)351				} else {352					v.1.get_lazy(index - a_len)353				}354			}355			Self::Range(a, _) => {356				if index >= self.len() {357					return None;358				}359				Some(LazyVal::new_resolved(Val::Num(360					((*a as isize) + index as isize) as f64,361				)))362			}363			Self::Reversed(v) => {364				let len = v.len();365				if index >= len {366					return None;367				}368				v.get_lazy(len - index - 1)369			}370			Self::Slice(s) => {371				let index = s.from() + index * s.step();372				if index >= s.to() {373					return None;374				}375				s.inner.get_lazy(index as usize)376			}377		}378	}379380	pub fn evaluated(&self, s: State) -> Result<Cc<Vec<Val>>> {381		Ok(match self {382			Self::Bytes(i) => {383				let mut out = Vec::with_capacity(i.len());384				for v in i.iter() {385					out.push(Val::Num(f64::from(*v)));386				}387				Cc::new(out)388			}389			Self::Lazy(vec) => {390				let mut out = Vec::with_capacity(vec.len());391				for item in vec.iter() {392					out.push(item.evaluate(s.clone())?);393				}394				Cc::new(out)395			}396			Self::Eager(vec) => vec.clone(),397			Self::Extended(_v) => {398				let mut out = Vec::with_capacity(self.len());399				for item in self.iter(s) {400					out.push(item?);401				}402				Cc::new(out)403			}404			Self::Range(a, b) => {405				let mut out = Vec::with_capacity(self.len());406				for i in *a..*b {407					out.push(Val::Num(f64::from(i)));408				}409				Cc::new(out)410			}411			Self::Reversed(r) => {412				let mut r = r.evaluated(s)?;413				Cc::update_with(&mut r, |v| v.reverse());414				r415			}416			Self::Slice(v) => {417				let mut out = Vec::with_capacity(v.inner.len());418				for v in v419					.inner420					.iter_lazy()421					.skip(v.from())422					.take(v.to() - v.from())423					.step_by(v.step())424				{425					out.push(v.evaluate(s.clone())?);426				}427				Cc::new(out)428			}429		})430	}431432	pub fn iter(&self, s: State) -> impl DoubleEndedIterator<Item = Result<Val>> + '_ {433		(0..self.len()).map(move |idx| match self {434			Self::Bytes(b) => Ok(Val::Num(f64::from(b[idx]))),435			Self::Lazy(l) => l[idx].evaluate(s.clone()),436			Self::Eager(e) => Ok(e[idx].clone()),437			Self::Extended(..) | Self::Range(..) | Self::Reversed(..) | Self::Slice(..) => {438				self.get(s.clone(), idx).map(|e| e.expect("idx < len"))439			}440		})441	}442443	pub fn iter_lazy(&self) -> impl DoubleEndedIterator<Item = LazyVal> + '_ {444		(0..self.len()).map(move |idx| match self {445			Self::Bytes(b) => LazyVal::new_resolved(Val::Num(f64::from(b[idx]))),446			Self::Lazy(l) => l[idx].clone(),447			Self::Eager(e) => LazyVal::new_resolved(e[idx].clone()),448			Self::Slice(..) | Self::Extended(..) | Self::Range(..) | Self::Reversed(..) => {449				self.get_lazy(idx).expect("idx < len")450			}451		})452	}453454	#[must_use]455	pub fn reversed(self) -> Self {456		Self::Reversed(Box::new(self))457	}458459	pub fn map(self, s: State, mapper: impl Fn(Val) -> Result<Val>) -> Result<Self> {460		let mut out = Vec::with_capacity(self.len());461462		for value in self.iter(s) {463			out.push(mapper(value?)?);464		}465466		Ok(Self::Eager(Cc::new(out)))467	}468469	pub fn filter(self, s: State, filter: impl Fn(&Val) -> Result<bool>) -> Result<Self> {470		let mut out = Vec::with_capacity(self.len());471472		for value in self.iter(s) {473			let value = value?;474			if filter(&value)? {475				out.push(value);476			}477		}478479		Ok(Self::Eager(Cc::new(out)))480	}481482	pub fn ptr_eq(a: &Self, b: &Self) -> bool {483		match (a, b) {484			(Self::Lazy(a), Self::Lazy(b)) => cc_ptr_eq(a, b),485			(Self::Eager(a), Self::Eager(b)) => cc_ptr_eq(a, b),486			_ => false,487		}488	}489}490491impl From<Vec<LazyVal>> for ArrValue {492	fn from(v: Vec<LazyVal>) -> Self {493		Self::Lazy(Cc::new(v))494	}495}496497impl From<Vec<Val>> for ArrValue {498	fn from(v: Vec<Val>) -> Self {499		Self::Eager(Cc::new(v))500	}501}502503#[allow(clippy::module_name_repetitions)]504pub enum IndexableVal {505	Str(IStr),506	Arr(ArrValue),507}508509#[derive(Debug, Clone, Trace)]510pub enum Val {511	Bool(bool),512	Null,513	Str(IStr),514	Num(f64),515	Arr(ArrValue),516	Obj(ObjValue),517	Func(FuncVal),518}519520impl Val {521	pub const fn as_bool(&self) -> Option<bool> {522		match self {523			Val::Bool(v) => Some(*v),524			_ => None,525		}526	}527	pub const fn as_null(&self) -> Option<()> {528		match self {529			Val::Null => Some(()),530			_ => None,531		}532	}533	pub fn as_str(&self) -> Option<IStr> {534		match self {535			Val::Str(s) => Some(s.clone()),536			_ => None,537		}538	}539	pub const fn as_num(&self) -> Option<f64> {540		match self {541			Val::Num(n) => Some(*n),542			_ => None,543		}544	}545	pub fn as_arr(&self) -> Option<ArrValue> {546		match self {547			Val::Arr(a) => Some(a.clone()),548			_ => None,549		}550	}551	pub fn as_obj(&self) -> Option<ObjValue> {552		match self {553			Val::Obj(o) => Some(o.clone()),554			_ => None,555		}556	}557	pub fn as_func(&self) -> Option<FuncVal> {558		match self {559			Val::Func(f) => Some(f.clone()),560			_ => None,561		}562	}563564	/// Creates `Val::Num` after checking for numeric overflow.565	/// As numbers are `f64`, we can just check for their finity.566	pub fn new_checked_num(num: f64) -> Result<Self> {567		if num.is_finite() {568			Ok(Self::Num(num))569		} else {570			throw!(RuntimeError("overflow".into()))571		}572	}573574	pub const fn value_type(&self) -> ValType {575		match self {576			Self::Str(..) => ValType::Str,577			Self::Num(..) => ValType::Num,578			Self::Arr(..) => ValType::Arr,579			Self::Obj(..) => ValType::Obj,580			Self::Bool(_) => ValType::Bool,581			Self::Null => ValType::Null,582			Self::Func(..) => ValType::Func,583		}584	}585586	pub fn to_string(&self, s: State) -> Result<IStr> {587		Ok(match self {588			Self::Bool(true) => "true".into(),589			Self::Bool(false) => "false".into(),590			Self::Null => "null".into(),591			Self::Str(s) => s.clone(),592			v => manifest_json_ex(593				s,594				v,595				&ManifestJsonOptions {596					padding: "",597					mtype: ManifestType::ToString,598					newline: "\n",599					key_val_sep: ": ",600					#[cfg(feature = "exp-preserve-order")]601					preserve_order: false,602				},603			)?604			.into(),605		})606	}607608	/// Expects value to be object, outputs (key, manifested value) pairs609	pub fn manifest_multi(&self, s: State, ty: &ManifestFormat) -> Result<Vec<(IStr, IStr)>> {610		let obj = match self {611			Self::Obj(obj) => obj,612			_ => throw!(MultiManifestOutputIsNotAObject),613		};614		let keys = obj.fields(615			#[cfg(feature = "exp-preserve-order")]616			ty.preserve_order(),617		);618		let mut out = Vec::with_capacity(keys.len());619		for key in keys {620			let value = obj621				.get(s.clone(), key.clone())?622				.expect("item in object")623				.manifest(s.clone(), ty)?;624			out.push((key, value));625		}626		Ok(out)627	}628629	/// Expects value to be array, outputs manifested values630	pub fn manifest_stream(&self, s: State, ty: &ManifestFormat) -> Result<Vec<IStr>> {631		let arr = match self {632			Self::Arr(a) => a,633			_ => throw!(StreamManifestOutputIsNotAArray),634		};635		let mut out = Vec::with_capacity(arr.len());636		for i in arr.iter(s.clone()) {637			out.push(i?.manifest(s.clone(), ty)?);638		}639		Ok(out)640	}641642	pub fn manifest(&self, s: State, ty: &ManifestFormat) -> Result<IStr> {643		Ok(match ty {644			ManifestFormat::YamlStream(format) => {645				let arr = match self {646					Self::Arr(a) => a,647					_ => throw!(StreamManifestOutputIsNotAArray),648				};649				let mut out = String::new();650651				match format as &ManifestFormat {652					ManifestFormat::YamlStream(_) => throw!(StreamManifestOutputCannotBeRecursed),653					ManifestFormat::String => throw!(StreamManifestCannotNestString),654					_ => {}655				};656657				if !arr.is_empty() {658					for v in arr.iter(s.clone()) {659						out.push_str("---\n");660						out.push_str(&v?.manifest(s.clone(), format)?);661						out.push('\n');662					}663					out.push_str("...");664				}665666				out.into()667			}668			ManifestFormat::Yaml {669				padding,670				#[cfg(feature = "exp-preserve-order")]671				preserve_order,672			} => self.to_yaml(673				s,674				*padding,675				#[cfg(feature = "exp-preserve-order")]676				*preserve_order,677			)?,678			ManifestFormat::Json {679				padding,680				#[cfg(feature = "exp-preserve-order")]681				preserve_order,682			} => self.to_json(683				s,684				*padding,685				#[cfg(feature = "exp-preserve-order")]686				*preserve_order,687			)?,688			ManifestFormat::ToString => self.to_string(s)?,689			ManifestFormat::String => match self {690				Self::Str(s) => s.clone(),691				_ => throw!(StringManifestOutputIsNotAString),692			},693		})694	}695696	/// For manifestification697	pub fn to_json(698		&self,699		s: State,700		padding: usize,701		#[cfg(feature = "exp-preserve-order")] preserve_order: bool,702	) -> Result<IStr> {703		manifest_json_ex(704			s,705			self,706			&ManifestJsonOptions {707				padding: &" ".repeat(padding),708				mtype: if padding == 0 {709					ManifestType::Minify710				} else {711					ManifestType::Manifest712				},713				newline: "\n",714				key_val_sep: ": ",715				#[cfg(feature = "exp-preserve-order")]716				preserve_order,717			},718		)719		.map(Into::into)720	}721722	/// Calls `std.manifestJson`723	pub fn to_std_json(724		&self,725		s: State,726		padding: usize,727		#[cfg(feature = "exp-preserve-order")] preserve_order: bool,728	) -> Result<Rc<str>> {729		manifest_json_ex(730			s,731			self,732			&ManifestJsonOptions {733				padding: &" ".repeat(padding),734				mtype: ManifestType::Std,735				newline: "\n",736				key_val_sep: ": ",737				#[cfg(feature = "exp-preserve-order")]738				preserve_order,739			},740		)741		.map(Into::into)742	}743744	pub fn to_yaml(745		&self,746		s: State,747		padding: usize,748		#[cfg(feature = "exp-preserve-order")] preserve_order: bool,749	) -> Result<IStr> {750		let padding = &" ".repeat(padding);751		manifest_yaml_ex(752			s,753			self,754			&ManifestYamlOptions {755				padding,756				arr_element_padding: padding,757				quote_keys: false,758				#[cfg(feature = "exp-preserve-order")]759				preserve_order,760			},761		)762		.map(Into::into)763	}764	pub fn into_indexable(self) -> Result<IndexableVal> {765		Ok(match self {766			Val::Str(s) => IndexableVal::Str(s),767			Val::Arr(arr) => IndexableVal::Arr(arr),768			_ => throw!(ValueIsNotIndexable(self.value_type())),769		})770	}771}772773const fn is_function_like(val: &Val) -> bool {774	matches!(val, Val::Func(_))775}776777/// Native implementation of `std.primitiveEquals`778pub fn primitive_equals(val_a: &Val, val_b: &Val) -> Result<bool> {779	Ok(match (val_a, val_b) {780		(Val::Bool(a), Val::Bool(b)) => a == b,781		(Val::Null, Val::Null) => true,782		(Val::Str(a), Val::Str(b)) => a == b,783		(Val::Num(a), Val::Num(b)) => (a - b).abs() <= f64::EPSILON,784		(Val::Arr(_), Val::Arr(_)) => throw!(RuntimeError(785			"primitiveEquals operates on primitive types, got array".into(),786		)),787		(Val::Obj(_), Val::Obj(_)) => throw!(RuntimeError(788			"primitiveEquals operates on primitive types, got object".into(),789		)),790		(a, b) if is_function_like(a) && is_function_like(b) => {791			throw!(RuntimeError("cannot test equality of functions".into()))792		}793		(_, _) => false,794	})795}796797/// Native implementation of `std.equals`798pub fn equals(s: State, val_a: &Val, val_b: &Val) -> Result<bool> {799	if val_a.value_type() != val_b.value_type() {800		return Ok(false);801	}802	match (val_a, val_b) {803		(Val::Arr(a), Val::Arr(b)) => {804			if ArrValue::ptr_eq(a, b) {805				return Ok(true);806			}807			if a.len() != b.len() {808				return Ok(false);809			}810			for (a, b) in a.iter(s.clone()).zip(b.iter(s.clone())) {811				if !equals(s.clone(), &a?, &b?)? {812					return Ok(false);813				}814			}815			Ok(true)816		}817		(Val::Obj(a), Val::Obj(b)) => {818			if ObjValue::ptr_eq(a, b) {819				return Ok(true);820			}821			let fields = a.fields(822				#[cfg(feature = "exp-preserve-order")]823				false,824			);825			if fields826				!= b.fields(827					#[cfg(feature = "exp-preserve-order")]828					false,829				) {830				return Ok(false);831			}832			for field in fields {833				if !equals(834					s.clone(),835					&a.get(s.clone(), field.clone())?.expect("field exists"),836					&b.get(s.clone(), field)?.expect("field exists"),837				)? {838					return Ok(false);839				}840			}841			Ok(true)842		}843		(a, b) => Ok(primitive_equals(a, b)?),844	}845}
modifiedcrates/jrsonnet-evaluator/tests/common.rsdiffbeforeafterboth
--- a/crates/jrsonnet-evaluator/tests/common.rs
+++ b/crates/jrsonnet-evaluator/tests/common.rs
@@ -12,6 +12,15 @@
 }
 
 #[macro_export]
+macro_rules! ensure {
+	($v:expr $(,)?) => {
+		if !$v {
+			::jrsonnet_evaluator::throw_runtime!("assertion failed: {}", stringify!($v))
+		}
+	};
+}
+
+#[macro_export]
 macro_rules! ensure_val_eq {
 	($s:expr, $a:expr, $b:expr) => {{
 		if !::jrsonnet_evaluator::val::equals($s.clone(), &$a.clone(), &$b.clone())? {
addedcrates/jrsonnet-evaluator/tests/sanity.rsdiffbeforeafterboth
--- /dev/null
+++ b/crates/jrsonnet-evaluator/tests/sanity.rs
@@ -0,0 +1,46 @@
+use std::path::PathBuf;
+
+use jrsonnet_evaluator::{error::Result, throw_runtime, State, Val};
+
+mod common;
+
+#[test]
+fn assert_positive() -> Result<()> {
+	let s = State::default();
+	s.with_stdlib();
+
+	let v = s.evaluate_snippet_raw(PathBuf::new().into(), "assert 1 == 1: 'fail'; null".into())?;
+	ensure_val_eq!(s.clone(), v, Val::Null);
+	let v = s.evaluate_snippet_raw(PathBuf::new().into(), "std.assertEqual(1, 1)".into())?;
+	ensure_val_eq!(s.clone(), v, Val::Bool(true));
+
+	Ok(())
+}
+
+#[test]
+fn assert_negative() -> Result<()> {
+	let s = State::default();
+	s.with_stdlib();
+
+	{
+		let e = match s
+			.evaluate_snippet_raw(PathBuf::new().into(), "assert 1 == 2: 'fail'; null".into())
+		{
+			Ok(_) => throw_runtime!("assertion should fail"),
+			Err(e) => e,
+		};
+		let e = s.stringify_err(&e);
+		ensure!(e.starts_with("assert failed: fail\n"));
+	}
+	{
+		let e = match s.evaluate_snippet_raw(PathBuf::new().into(), "std.assertEqual(1, 2)".into())
+		{
+			Ok(_) => throw_runtime!("assertion should fail"),
+			Err(e) => e,
+		};
+		let e = s.stringify_err(&e);
+		ensure!(e.starts_with("runtime error: Assertion failed. 1 != 2"))
+	}
+
+	Ok(())
+}
modifiedcrates/jrsonnet-macros/src/lib.rsdiffbeforeafterboth
--- a/crates/jrsonnet-macros/src/lib.rs
+++ b/crates/jrsonnet-macros/src/lib.rs
@@ -157,8 +157,8 @@
 			});
 		}
 
-		match &ty as &Type {
-			Type::Reference(r) if type_is_path(&r.elem, &name).is_some() => return Ok(Self::This),
+		match ty as &Type {
+			Type::Reference(r) if type_is_path(&r.elem, name).is_some() => return Ok(Self::This),
 			_ => {}
 		}
 
@@ -465,14 +465,13 @@
 					"strategy should be set when flattening Option",
 				));
 			}
-		} else {
-			if attr.flatten_ok {
-				return Err(Error::new(
-					field.span(),
-					"flatten(ok) is only useable on optional fields",
-				));
-			}
+		} else if attr.flatten_ok {
+			return Err(Error::new(
+				field.span(),
+				"flatten(ok) is only useable on optional fields",
+			));
 		}
+
 		Ok(Self {
 			attr,
 			ident,