git.delta.rocks / jrsonnet / refs/commits / 0e2224254bcf

difftreelog

fix enforce Val::Num finityness at type level

Yaroslav Bolyukin2024-05-19parent: #88907d8.patch.diff
in: master

13 files changed

modifiedcrates/jrsonnet-evaluator/src/arr/spec.rsdiffbeforeafterboth
--- a/crates/jrsonnet-evaluator/src/arr/spec.rs
+++ b/crates/jrsonnet-evaluator/src/arr/spec.rs
@@ -120,7 +120,7 @@
 	}
 
 	fn get_cheap(&self, index: usize) -> Option<Val> {
-		self.0.get(index).map(|v| Val::Num(f64::from(*v)))
+		self.0.get(index).map(|v| Val::Num((*v).into()))
 	}
 	fn is_cheap(&self) -> bool {
 		true
@@ -399,7 +399,7 @@
 	}
 
 	fn get_cheap(&self, index: usize) -> Option<Val> {
-		self.range().nth(index).map(|i| Val::Num(f64::from(i)))
+		self.range().nth(index).map(|i| Val::Num(i.into()))
 	}
 	fn is_cheap(&self) -> bool {
 		true
@@ -430,12 +430,12 @@
 }
 
 #[derive(Trace, Debug, Clone)]
-pub struct MappedArray<const WithIndex: bool> {
+pub struct MappedArray<const WITH_INDEX: bool> {
 	inner: ArrValue,
 	cached: Cc<RefCell<Vec<ArrayThunk<()>>>>,
 	mapper: FuncVal,
 }
-impl<const WithIndex: bool> MappedArray<WithIndex> {
+impl<const WITH_INDEX: bool> MappedArray<WITH_INDEX> {
 	pub fn new(inner: ArrValue, mapper: FuncVal) -> Self {
 		let len = inner.len();
 		Self {
@@ -445,14 +445,14 @@
 		}
 	}
 	fn evaluate(&self, index: usize, value: Val) -> Result<Val> {
-		if WithIndex {
+		if WITH_INDEX {
 			self.mapper.evaluate_simple(&(index, value), false)
 		} else {
 			self.mapper.evaluate_simple(&(value,), false)
 		}
 	}
 }
-impl<const WithIndex: bool> ArrayLike for MappedArray<WithIndex> {
+impl<const WITH_INDEX: bool> ArrayLike for MappedArray<WITH_INDEX> {
 	fn len(&self) -> usize {
 		self.cached.borrow().len()
 	}
@@ -493,12 +493,12 @@
 	}
 	fn get_lazy(&self, index: usize) -> Option<Thunk<Val>> {
 		#[derive(Trace)]
-		struct ArrayElement<const WithIndex: bool> {
-			arr_thunk: MappedArray<WithIndex>,
+		struct ArrayElement<const WITH_INDEX: bool> {
+			arr_thunk: MappedArray<WITH_INDEX>,
 			index: usize,
 		}
 
-		impl<const WithIndex: bool> ThunkValue for ArrayElement<WithIndex> {
+		impl<const WITH_INDEX: bool> ThunkValue for ArrayElement<WITH_INDEX> {
 			type Output = Val;
 
 			fn get(self: Box<Self>) -> Result<Self::Output> {
modifiedcrates/jrsonnet-evaluator/src/error.rsdiffbeforeafterboth
--- a/crates/jrsonnet-evaluator/src/error.rs
+++ b/crates/jrsonnet-evaluator/src/error.rs
@@ -1,7 +1,5 @@
 use std::{
-	cmp::Ordering,
-	fmt::{Debug, Display},
-	path::PathBuf,
+	cmp::Ordering, convert::Infallible, fmt::{Debug, Display}, path::PathBuf
 };
 
 use jrsonnet_gcmodule::Trace;
@@ -14,6 +12,7 @@
 	function::{builtin::ParamDefault, CallLocation},
 	stdlib::format::FormatError,
 	typed::TypeLocError,
+	val::ConvertNumValueError,
 	ObjValue,
 };
 
@@ -236,6 +235,9 @@
 	#[error("invalid unicode codepoint: {0}")]
 	InvalidUnicodeCodepointGot(u32),
 
+	#[error("convert num value: {0}")]
+	ConvertNumValue(#[from] ConvertNumValueError),
+
 	#[error("format error: {0}")]
 	Format(#[from] FormatError),
 	#[error("type error: {0}")]
@@ -259,6 +261,12 @@
 	}
 }
 
+impl From<Infallible> for Error {
+	fn from(_value: Infallible) -> Self {
+		unreachable!()
+	}
+}
+
 /// Single stack trace frame
 #[derive(Clone, Debug, Trace)]
 pub struct StackTraceElement {
modifiedcrates/jrsonnet-evaluator/src/evaluate/mod.rsdiffbeforeafterboth
--- a/crates/jrsonnet-evaluator/src/evaluate/mod.rs
+++ b/crates/jrsonnet-evaluator/src/evaluate/mod.rs
@@ -17,7 +17,7 @@
 	evaluate::operator::{evaluate_add_op, evaluate_binary_op_special, evaluate_unary_op},
 	function::{CallLocation, FuncDesc, FuncVal},
 	typed::Typed,
-	val::{CachedUnbound, IndexableVal, StrValue, Thunk, ThunkValue},
+	val::{CachedUnbound, IndexableVal, NumValue, StrValue, Thunk, ThunkValue},
 	Context, Error, GcHashMap, ObjValue, ObjValueBuilder, ObjectAssertion, Pending, Result,
 	ResultExt, State, Unbound, Val,
 };
@@ -37,7 +37,7 @@
 	}
 	Some(match &*expr.0 {
 		Expr::Str(s) => Val::string(s.clone()),
-		Expr::Num(n) => Val::Num(*n),
+		Expr::Num(n) => Val::Num(NumValue::new(*n).expect("parser will not allow non-finite values")),
 		Expr::Literal(LiteralType::False) => Val::Bool(false),
 		Expr::Literal(LiteralType::True) => Val::Bool(true),
 		Expr::Literal(LiteralType::Null) => Val::Null,
@@ -438,7 +438,7 @@
 		Literal(LiteralType::Null) => Val::Null,
 		Parened(e) => evaluate(ctx, e)?,
 		Str(v) => Val::string(v.clone()),
-		Num(v) => Val::new_checked_num(*v)?,
+		Num(v) => Val::try_num(*v)?,
 		// I have tried to remove special behavior from super by implementing standalone-super
 		// expresion, but looks like this case still needs special treatment.
 		//
@@ -530,6 +530,7 @@
 						n.value_type(),
 					)),
 					(Val::Arr(v), Val::Num(n)) => {
+						let n = n.get();
 						if n.fract() > f64::EPSILON {
 							bail!(FractionalIndex)
 						}
@@ -553,13 +554,13 @@
 							.clone()
 							.into_flat()
 							.chars()
-							.skip(n as usize)
+							.skip(n.get() as usize)
 							.take(1)
 							.collect::<String>()
 							.into();
 						if v.is_empty() {
 							let size = s.into_flat().chars().count();
-							bail!(StringBoundsError(n as usize, size))
+							bail!(StringBoundsError(n.get() as usize, size))
 						}
 						StrValue::Flat(v)
 					}),
modifiedcrates/jrsonnet-evaluator/src/evaluate/operator.rsdiffbeforeafterboth
--- a/crates/jrsonnet-evaluator/src/evaluate/operator.rs
+++ b/crates/jrsonnet-evaluator/src/evaluate/operator.rs
@@ -17,10 +17,10 @@
 	use UnaryOpType::*;
 	use Val::*;
 	Ok(match (op, b) {
-		(Plus, Num(n)) => Num(*n),
-		(Minus, Num(n)) => Num(-*n),
+		(Plus, Num(n)) => Val::Num(*n),
+		(Minus, Num(n)) => Val::try_num(-n.get())?,
 		(Not, Bool(v)) => Bool(!v),
-		(BitNot, Num(n)) => Num(!(*n as i64) as f64),
+		(BitNot, Num(n)) => Val::try_num(!(n.get() as i64) as f64)?,
 		(op, o) => bail!(UnaryOperatorDoesNotOperateOnType(op, o.value_type())),
 	})
 }
@@ -40,7 +40,7 @@
 		(Obj(v1), Obj(v2)) => Obj(v2.extend_from(v1.clone())),
 		(Arr(a), Arr(b)) => Val::Arr(ArrValue::extended(a.clone(), b.clone())),
 
-		(Num(v1), Num(v2)) => Val::new_checked_num(v1 + v2)?,
+		(Num(v1), Num(v2)) => Val::try_num(v1.get() + v2.get())?,
 		#[cfg(feature = "exp-bigint")]
 		(BigInt(a), BigInt(b)) => BigInt(Box::new(&**a + &**b)),
 		_ => bail!(BinaryOperatorDoesNotOperateOnValues(
@@ -55,10 +55,10 @@
 	use Val::*;
 	match (a, b) {
 		(Num(a), Num(b)) => {
-			if *b == 0.0 {
+			if b.get() == 0.0 {
 				bail!(DivisionByZero)
 			}
-			Ok(Num(a % b))
+			Ok(Val::try_num(a.get() % b.get())?)
 		}
 		(Str(str), vals) => {
 			String::into_untyped(std_format(&str.clone().into_flat(), vals.clone())?)
@@ -143,39 +143,39 @@
 		(Str(a), In, Obj(obj)) => Bool(obj.has_field_ex(a.clone().into_flat(), true)),
 		(a, Mod, b) => evaluate_mod_op(a, b)?,
 
-		(Str(v1), Mul, Num(v2)) => Val::string(v1.to_string().repeat(*v2 as usize)),
+		(Str(v1), Mul, Num(v2)) => Val::string(v1.to_string().repeat(v2.get() as usize)),
 
 		// Bool X Bool
 		(Bool(a), And, Bool(b)) => Bool(*a && *b),
 		(Bool(a), Or, Bool(b)) => Bool(*a || *b),
 
 		// Num X Num
-		(Num(v1), Mul, Num(v2)) => Val::new_checked_num(v1 * v2)?,
+		(Num(v1), Mul, Num(v2)) => Val::try_num(v1.get() * v2.get())?,
 		(Num(v1), Div, Num(v2)) => {
-			if *v2 == 0.0 {
+			if v2.get() == 0.0 {
 				bail!(DivisionByZero)
 			}
-			Val::new_checked_num(v1 / v2)?
+			Val::try_num(v1.get() / v2.get())?
 		}
 
-		(Num(v1), Sub, Num(v2)) => Val::new_checked_num(v1 - v2)?,
+		(Num(v1), Sub, Num(v2)) => Val::try_num(v1.get() - v2.get())?,
 
-		(Num(v1), BitAnd, Num(v2)) => Num((*v1 as i64 & *v2 as i64) as f64),
-		(Num(v1), BitOr, Num(v2)) => Num((*v1 as i64 | *v2 as i64) as f64),
-		(Num(v1), BitXor, Num(v2)) => Num((*v1 as i64 ^ *v2 as i64) as f64),
+		(Num(v1), BitAnd, Num(v2)) => Val::try_num((v1.get() as i64 & v2.get() as i64) as f64)?,
+		(Num(v1), BitOr, Num(v2)) => Val::try_num((v1.get() as i64 | v2.get() as i64) as f64)?,
+		(Num(v1), BitXor, Num(v2)) => Val::try_num((v1.get() as i64 ^ v2.get() as i64) as f64)?,
 		(Num(v1), Lhs, Num(v2)) => {
-			if *v2 < 0.0 {
+			if v2.get() < 0.0 {
 				bail!("shift by negative exponent")
 			}
-			let exp = ((*v2 as i64) & 63) as u32;
-			Num((*v1 as i64).wrapping_shl(exp) as f64)
+			let exp = ((v2.get() as i64) & 63) as u32;
+			Val::try_num((v1.get() as i64).wrapping_shl(exp) as f64)?
 		}
 		(Num(v1), Rhs, Num(v2)) => {
-			if *v2 < 0.0 {
+			if v2.get() < 0.0 {
 				bail!("shift by negative exponent")
 			}
-			let exp = ((*v2 as i64) & 63) as u32;
-			Num((*v1 as i64).wrapping_shr(exp) as f64)
+			let exp = ((v2.get() as i64) & 63) as u32;
+			Val::try_num((v1.get() as i64).wrapping_shr(exp) as f64)?
 		}
 
 		// Bigint X Bigint
modifiedcrates/jrsonnet-evaluator/src/integrations/serde.rsdiffbeforeafterboth
--- a/crates/jrsonnet-evaluator/src/integrations/serde.rs
+++ b/crates/jrsonnet-evaluator/src/integrations/serde.rs
@@ -2,7 +2,7 @@
 
 use jrsonnet_interner::IStr;
 use serde::{
-	de::Visitor,
+	de::{self, Visitor},
 	ser::{
 		Error, SerializeMap, SerializeSeq, SerializeStruct, SerializeStructVariant, SerializeTuple,
 		SerializeTupleStruct, SerializeTupleVariant,
@@ -11,7 +11,8 @@
 };
 
 use crate::{
-	arr::ArrValue, runtime_error, Error as JrError, ObjValue, ObjValueBuilder, Result, State, Val,
+	arr::ArrValue, runtime_error, val::NumValue, Error as JrError, ObjValue, ObjValueBuilder,
+	Result, State, Val,
 };
 
 impl<'de> Deserialize<'de> for Val {
@@ -37,22 +38,21 @@
 
 			fn visit_bool<E>(self, v: bool) -> Result<Self::Value, E>
 			where
-				E: serde::de::Error,
+				E: de::Error,
 			{
 				Ok(Val::Bool(v))
 			}
 			fn visit_f64<E>(self, v: f64) -> Result<Self::Value, E>
 			where
-				E: serde::de::Error,
+				E: de::Error,
 			{
-				if !v.is_finite() {
-					return Err(E::custom("only finite numbers are supported"));
-				}
-				Ok(Val::Num(v))
+				Ok(Val::Num(NumValue::new(v).ok_or_else(|| {
+					E::custom("only finite numbers are supported")
+				})?))
 			}
 			fn visit_str<E>(self, v: &str) -> Result<Self::Value, E>
 			where
-				E: serde::de::Error,
+				E: de::Error,
 			{
 				Ok(Val::string(v))
 			}
@@ -67,27 +67,27 @@
 			// }
 			fn visit_i64<E>(self, v: i64) -> Result<Self::Value, E>
 			where
-				E: serde::de::Error,
+				E: de::Error,
 			{
-				Ok(Val::Num(v as f64))
+				Ok(Val::Num(NumValue::new(v as f64).expect("no overflow")))
 			}
 			fn visit_u64<E>(self, v: u64) -> Result<Self::Value, E>
 			where
-				E: serde::de::Error,
+				E: de::Error,
 			{
-				Ok(Val::Num(v as f64))
+				Ok(Val::Num(NumValue::new(v as f64).expect("no overflow")))
 			}
 
 			fn visit_bytes<E>(self, v: &[u8]) -> Result<Self::Value, E>
 			where
-				E: serde::de::Error,
+				E: de::Error,
 			{
 				Ok(Val::Arr(ArrValue::bytes(v.into())))
 			}
 
 			fn visit_none<E>(self) -> Result<Self::Value, E>
 			where
-				E: serde::de::Error,
+				E: de::Error,
 			{
 				Ok(Val::Null)
 			}
@@ -100,7 +100,7 @@
 
 			fn visit_unit<E>(self) -> Result<Self::Value, E>
 			where
-				E: serde::de::Error,
+				E: de::Error,
 			{
 				Ok(Val::Null)
 			}
@@ -114,7 +114,7 @@
 
 			fn visit_seq<A>(self, mut seq: A) -> Result<Self::Value, A::Error>
 			where
-				A: serde::de::SeqAccess<'de>,
+				A: de::SeqAccess<'de>,
 			{
 				let mut out = seq.size_hint().map_or_else(Vec::new, Vec::with_capacity);
 
@@ -127,7 +127,7 @@
 
 			fn visit_map<A>(self, mut map: A) -> Result<Self::Value, A::Error>
 			where
-				A: serde::de::MapAccess<'de>,
+				A: de::MapAccess<'de>,
 			{
 				let mut out = map
 					.size_hint()
@@ -159,11 +159,12 @@
 			Self::Null => serializer.serialize_none(),
 			Self::Str(s) => serializer.serialize_str(&s.clone().into_flat()),
 			Self::Num(n) => {
+				let n = n.get();
 				if n.fract() == 0.0 {
-					let n = *n as i64;
+					let n = n as i64;
 					serializer.serialize_i64(n)
 				} else {
-					serializer.serialize_f64(*n)
+					serializer.serialize_f64(n)
 				}
 			}
 			#[cfg(feature = "exp-bigint")]
@@ -449,15 +450,15 @@
 	}
 
 	fn serialize_i8(self, v: i8) -> Result<Val> {
-		Ok(Val::Num(f64::from(v)))
+		Ok(Val::Num(v.into()))
 	}
 
 	fn serialize_i16(self, v: i16) -> Result<Val> {
-		Ok(Val::Num(f64::from(v)))
+		Ok(Val::Num(v.into()))
 	}
 
 	fn serialize_i32(self, v: i32) -> Result<Val> {
-		Ok(Val::Num(f64::from(v)))
+		Ok(Val::Num(v.into()))
 	}
 
 	fn serialize_i64(self, v: i64) -> Result<Val> {
@@ -465,15 +466,15 @@
 	}
 
 	fn serialize_u8(self, v: u8) -> Result<Val> {
-		Ok(Val::Num(f64::from(v)))
+		Ok(Val::Num(v.into()))
 	}
 
 	fn serialize_u16(self, v: u16) -> Result<Val> {
-		Ok(Val::Num(f64::from(v)))
+		Ok(Val::Num(v.into()))
 	}
 
 	fn serialize_u32(self, v: u32) -> Result<Val> {
-		Ok(Val::Num(f64::from(v)))
+		Ok(Val::Num(v.into()))
 	}
 
 	fn serialize_u64(self, v: u64) -> Result<Val> {
@@ -481,11 +482,11 @@
 	}
 
 	fn serialize_f32(self, v: f32) -> Result<Val> {
-		Ok(Val::Num(f64::from(v)))
+		Ok(Val::try_num(f64::from(v))?)
 	}
 
 	fn serialize_f64(self, v: f64) -> Result<Val> {
-		Ok(Val::Num(v))
+		Ok(Val::try_num(v)?)
 	}
 
 	fn serialize_char(self, v: char) -> Result<Val> {
modifiedcrates/jrsonnet-evaluator/src/stdlib/format.rsdiffbeforeafterboth
--- a/crates/jrsonnet-evaluator/src/stdlib/format.rs
+++ b/crates/jrsonnet-evaluator/src/stdlib/format.rs
@@ -604,10 +604,13 @@
 			}
 		}
 		ConvTypeV::Char => match value.clone() {
-			Val::Num(n) => tmp_out.push(
-				std::char::from_u32(n as u32)
-					.ok_or_else(|| InvalidUnicodeCodepointGot(n as u32))?,
-			),
+			Val::Num(n) => {
+				let n = n.get();
+				tmp_out.push(
+					std::char::from_u32(n as u32)
+						.ok_or_else(|| InvalidUnicodeCodepointGot(n as u32))?,
+				)
+			}
 			Val::Str(s) => {
 				let s = s.into_flat();
 				if s.chars().count() != 1 {
@@ -786,6 +789,7 @@
 #[cfg(test)]
 pub mod test_format {
 	use super::*;
+	use crate::val::NumValue;
 
 	#[test]
 	fn parse() {
@@ -799,17 +803,21 @@
 		);
 	}
 
+	fn num(v: f64) -> Val {
+		Val::Num(NumValue::new(v).expect("finite"))
+	}
+
 	#[test]
 	fn octals() {
-		assert_eq!(format_arr("%#o", &[Val::Num(8.0)]).unwrap(), "010");
-		assert_eq!(format_arr("%#4o", &[Val::Num(8.0)]).unwrap(), " 010");
-		assert_eq!(format_arr("%4o", &[Val::Num(8.0)]).unwrap(), "  10");
-		assert_eq!(format_arr("%04o", &[Val::Num(8.0)]).unwrap(), "0010");
-		assert_eq!(format_arr("%+4o", &[Val::Num(8.0)]).unwrap(), " +10");
-		assert_eq!(format_arr("%+04o", &[Val::Num(8.0)]).unwrap(), "+010");
-		assert_eq!(format_arr("%-4o", &[Val::Num(8.0)]).unwrap(), "10  ");
-		assert_eq!(format_arr("%+-4o", &[Val::Num(8.0)]).unwrap(), "+10 ");
-		assert_eq!(format_arr("%+-04o", &[Val::Num(8.0)]).unwrap(), "+10 ");
+		assert_eq!(format_arr("%#o", &[num(8.0)]).unwrap(), "010");
+		assert_eq!(format_arr("%#4o", &[num(8.0)]).unwrap(), " 010");
+		assert_eq!(format_arr("%4o", &[num(8.0)]).unwrap(), "  10");
+		assert_eq!(format_arr("%04o", &[num(8.0)]).unwrap(), "0010");
+		assert_eq!(format_arr("%+4o", &[num(8.0)]).unwrap(), " +10");
+		assert_eq!(format_arr("%+04o", &[num(8.0)]).unwrap(), "+010");
+		assert_eq!(format_arr("%-4o", &[num(8.0)]).unwrap(), "10  ");
+		assert_eq!(format_arr("%+-4o", &[num(8.0)]).unwrap(), "+10 ");
+		assert_eq!(format_arr("%+-04o", &[num(8.0)]).unwrap(), "+10 ");
 	}
 
 	#[test]
@@ -817,7 +825,7 @@
 		assert_eq!(
 			format_arr(
 				"How much error budget is left looking at our %.3f%% availability gurantees?",
-				&[Val::Num(4.0)]
+				&[num(4.0)]
 			)
 			.unwrap(),
 			"How much error budget is left looking at our 4.000% availability gurantees?"
modifiedcrates/jrsonnet-evaluator/src/typed/conversions.rsdiffbeforeafterboth
--- a/crates/jrsonnet-evaluator/src/typed/conversions.rs
+++ b/crates/jrsonnet-evaluator/src/typed/conversions.rs
@@ -10,7 +10,7 @@
 	bail,
 	function::{native::NativeDesc, FuncDesc, FuncVal},
 	typed::CheckType,
-	val::{IndexableVal, StrValue, ThunkMapper},
+	val::{IndexableVal, NumValue, StrValue, ThunkMapper},
 	ObjValue, ObjValueBuilder, Result, ResultExt, Thunk, Val,
 };
 
@@ -120,7 +120,8 @@
 	}
 }
 
-const MAX_SAFE_INTEGER: f64 = ((1u64 << (f64::MANTISSA_DIGITS + 1)) - 1) as f64;
+pub const MAX_SAFE_INTEGER: f64 = ((1u64 << (f64::MANTISSA_DIGITS + 1)) - 1) as f64;
+pub const MIN_SAFE_INTEGER: f64 = -MAX_SAFE_INTEGER;
 
 macro_rules! impl_int {
 	($($ty:ty)*) => {$(
@@ -131,6 +132,7 @@
 				<Self as Typed>::TYPE.check(&value)?;
 				match value {
 					Val::Num(n) => {
+						let n = n.get();
 						#[allow(clippy::float_cmp)]
 						if n.trunc() != n {
 							bail!(
@@ -143,9 +145,8 @@
 					_ => unreachable!(),
 				}
 			}
-			#[allow(clippy::cast_lossless)]
 			fn into_untyped(value: Self) -> Result<Val> {
-				Ok(Val::Num(value as f64))
+				Ok(Val::Num(value.into()))
 			}
 		}
 	)*};
@@ -187,6 +188,7 @@
 				<Self as Typed>::TYPE.check(&value)?;
 				match value {
 					Val::Num(n) => {
+						let n = n.get();
 						#[allow(clippy::float_cmp)]
 						if n.trunc() != n {
 							bail!(
@@ -202,7 +204,7 @@
 
 			#[allow(clippy::cast_lossless)]
 			fn into_untyped(value: Self) -> Result<Val> {
-				Ok(Val::Num(value.0 as f64))
+				Ok(Val::try_num(value.0)?)
 			}
 		}
 	)*};
@@ -220,13 +222,13 @@
 	const TYPE: &'static ComplexValType = &ComplexValType::Simple(ValType::Num);
 
 	fn into_untyped(value: Self) -> Result<Val> {
-		Ok(Val::Num(value))
+		Ok(Val::try_num(value)?)
 	}
 
 	fn from_untyped(value: Val) -> Result<Self> {
 		<Self as Typed>::TYPE.check(&value)?;
 		match value {
-			Val::Num(n) => Ok(n),
+			Val::Num(n) => Ok(n.get()),
 			_ => unreachable!(),
 		}
 	}
@@ -237,13 +239,13 @@
 	const TYPE: &'static ComplexValType = &ComplexValType::BoundedNumber(Some(0.0), None);
 
 	fn into_untyped(value: Self) -> Result<Val> {
-		Ok(Val::Num(value.0))
+		Ok(Val::try_num(value.0)?)
 	}
 
 	fn from_untyped(value: Val) -> Result<Self> {
 		<Self as Typed>::TYPE.check(&value)?;
 		match value {
-			Val::Num(n) => Ok(Self(n)),
+			Val::Num(n) => Ok(Self(n.get())),
 			_ => unreachable!(),
 		}
 	}
@@ -253,16 +255,14 @@
 		&ComplexValType::BoundedNumber(Some(0.0), Some(MAX_SAFE_INTEGER));
 
 	fn into_untyped(value: Self) -> Result<Val> {
-		if value > MAX_SAFE_INTEGER as Self {
-			bail!("number is too large")
-		}
-		Ok(Val::Num(value as f64))
+		Ok(Val::try_num(value)?)
 	}
 
 	fn from_untyped(value: Val) -> Result<Self> {
 		<Self as Typed>::TYPE.check(&value)?;
 		match value {
 			Val::Num(n) => {
+				let n = n.get();
 				#[allow(clippy::float_cmp)]
 				if n.trunc() != n {
 					bail!("cannot convert number with fractional part to usize")
@@ -479,7 +479,7 @@
 	const TYPE: &'static ComplexValType = &ComplexValType::BoundedNumber(Some(-1.0), Some(-1.0));
 
 	fn into_untyped(_: Self) -> Result<Val> {
-		Ok(Val::Num(-1.0))
+		Ok(Val::Num(NumValue::new(-1.0).expect("finite")))
 	}
 
 	fn from_untyped(value: Val) -> Result<Self> {
@@ -679,3 +679,19 @@
 		))
 	}
 }
+
+impl Typed for NumValue {
+	const TYPE: &'static ComplexValType = &ComplexValType::Simple(ValType::Num);
+
+	fn into_untyped(typed: Self) -> Result<Val> {
+		Ok(Val::Num(typed))
+	}
+
+	fn from_untyped(untyped: Val) -> Result<Self> {
+		Self::TYPE.check(&untyped)?;
+		match untyped {
+			Val::Num(v) => Ok(v),
+			_ => unreachable!(),
+		}
+	}
+}
modifiedcrates/jrsonnet-evaluator/src/typed/mod.rsdiffbeforeafterboth
--- a/crates/jrsonnet-evaluator/src/typed/mod.rs
+++ b/crates/jrsonnet-evaluator/src/typed/mod.rs
@@ -1,6 +1,6 @@
 use std::{fmt::Display, rc::Rc};
 
-mod conversions;
+pub(crate) mod conversions;
 pub use conversions::*;
 use jrsonnet_gcmodule::Trace;
 pub use jrsonnet_types::{ComplexValType, ValType};
@@ -155,10 +155,11 @@
 			},
 			Self::BoundedNumber(from, to) => {
 				if let Val::Num(n) = value {
-					if from.map(|from| from > *n).unwrap_or(false)
-						|| to.map(|to| to < *n).unwrap_or(false)
+					let n = n.get();
+					if from.map(|from| from > n).unwrap_or(false)
+						|| to.map(|to| to < n).unwrap_or(false)
 					{
-						return Err(TypeError::BoundsFailed(*n, *from, *to).into());
+						return Err(TypeError::BoundsFailed(n, *from, *to).into());
 					}
 					Ok(())
 				} else {
modifiedcrates/jrsonnet-evaluator/src/val.rsdiffbeforeafterboth
--- a/crates/jrsonnet-evaluator/src/val.rs
+++ b/crates/jrsonnet-evaluator/src/val.rs
@@ -1,14 +1,18 @@
 use std::{
 	cell::RefCell,
+	cmp::Ordering,
 	fmt::{self, Debug, Display},
 	mem::replace,
 	num::NonZeroU32,
+	ops::Deref,
 	rc::Rc,
 };
 
+use derivative::Derivative;
 use jrsonnet_gcmodule::{Cc, Trace};
 use jrsonnet_interner::IStr;
 use jrsonnet_types::ValType;
+use thiserror::Error;
 
 pub use crate::arr::{ArrValue, ArrayLike};
 use crate::{
@@ -379,18 +383,127 @@
 }
 impl Eq for StrValue {}
 impl PartialOrd for StrValue {
-	fn partial_cmp(&self, other: &Self) -> Option<std::cmp::Ordering> {
+	fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
 		Some(self.cmp(other))
 	}
 }
 impl Ord for StrValue {
-	fn cmp(&self, other: &Self) -> std::cmp::Ordering {
+	fn cmp(&self, other: &Self) -> Ordering {
 		let a = self.clone().into_flat();
 		let b = other.clone().into_flat();
 		a.cmp(&b)
 	}
 }
 
+/// Represents jsonnet number
+/// Jsonnet numbers are finite f64, with NaNs disallowed
+#[derive(Trace, Clone, Copy, Derivative)]
+#[derivative(Debug = "transparent")]
+#[repr(transparent)]
+pub struct NumValue(f64);
+impl NumValue {
+	/// Creates a [`NumValue`], if value is finite and not NaN
+	pub fn new(v: f64) -> Option<Self> {
+		if !v.is_finite() {
+			return None;
+		}
+		Some(Self(v))
+	}
+	pub const fn get(&self) -> f64 {
+		self.0
+	}
+}
+impl PartialEq for NumValue {
+	fn eq(&self, other: &Self) -> bool {
+		self.0 == other.0
+	}
+}
+impl Eq for NumValue {}
+impl Ord for NumValue {
+	fn cmp(&self, other: &Self) -> Ordering {
+		// Can't use `total_cmp`: its behavior for `-0` and `0`
+		// is not following wanted.
+		self.0.partial_cmp(&other.0).expect("NaNs are disallowed")
+	}
+}
+impl PartialOrd for NumValue {
+	fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
+		Some(self.cmp(other))
+	}
+}
+impl Display for NumValue {
+	fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
+		Display::fmt(&self.0, f)
+	}
+}
+impl Deref for NumValue {
+	type Target = f64;
+
+	fn deref(&self) -> &Self::Target {
+		&self.0
+	}
+}
+macro_rules! impl_num {
+	($($ty:ty),+) => {$(
+		impl From<$ty> for NumValue {
+			fn from(value: $ty) -> Self {
+				Self(value.into())
+			}
+		}
+	)+};
+}
+impl_num!(i8, u8, i16, u16, i32, u32);
+
+#[derive(Clone, Copy, Debug, Error, Trace)]
+pub enum ConvertNumValueError {
+	#[error("overflow")]
+	Overflow,
+	#[error("underflow")]
+	Underflow,
+	#[error("non-finite")]
+	NonFinite,
+}
+impl From<ConvertNumValueError> for Error {
+	fn from(e: ConvertNumValueError) -> Self {
+		Self::new(e.into())
+	}
+}
+
+macro_rules! impl_try_num {
+	($($ty:ty),+) => {$(
+		impl TryFrom<$ty> for NumValue {
+			type Error = ConvertNumValueError;
+			fn try_from(value: $ty) -> Result<Self, ConvertNumValueError> {
+				use crate::typed::conversions::{MIN_SAFE_INTEGER, MAX_SAFE_INTEGER};
+				let value = value as f64;
+				if value < MIN_SAFE_INTEGER {
+					return Err(ConvertNumValueError::Underflow)
+				} else if value > MAX_SAFE_INTEGER {
+					return Err(ConvertNumValueError::Overflow)
+				}
+				// Number is finite.
+				Ok(Self(value))
+			}
+		}
+	)+};
+}
+impl_try_num!(usize, isize, i64, u64);
+
+impl TryFrom<f64> for NumValue {
+	type Error = ConvertNumValueError;
+
+	fn try_from(value: f64) -> Result<Self, Self::Error> {
+		Self::new(value).ok_or(ConvertNumValueError::NonFinite)
+	}
+}
+impl TryFrom<f32> for NumValue {
+	type Error = ConvertNumValueError;
+
+	fn try_from(value: f32) -> Result<Self, Self::Error> {
+		Self::new(f64::from(value)).ok_or(ConvertNumValueError::NonFinite)
+	}
+}
+
 /// Represents any valid Jsonnet value.
 #[derive(Debug, Clone, Trace, Default)]
 pub enum Val {
@@ -404,7 +517,7 @@
 	/// Represents a Jsonnet number.
 	/// Should be finite, and not NaN
 	/// This restriction isn't enforced by enum, as enum field can't be marked as private
-	Num(f64),
+	Num(NumValue),
 	/// Experimental bigint
 	#[cfg(feature = "exp-bigint")]
 	BigInt(#[trace(skip)] Box<num_bigint::BigInt>),
@@ -449,7 +562,7 @@
 	}
 	pub const fn as_num(&self) -> Option<f64> {
 		match self {
-			Self::Num(n) => Some(*n),
+			Self::Num(n) => Some(n.get()),
 			_ => None,
 		}
 	}
@@ -472,16 +585,6 @@
 		}
 	}
 
-	/// Creates `Val::Num` after checking for numeric overflow.
-	/// As numbers are `f64`, we can just check for their finity.
-	pub fn new_checked_num(num: f64) -> Result<Self> {
-		if num.is_finite() {
-			Ok(Self::Num(num))
-		} else {
-			bail!("overflow")
-		}
-	}
-
 	pub const fn value_type(&self) -> ValType {
 		match self {
 			Self::Str(..) => ValType::Str,
@@ -527,6 +630,15 @@
 	pub fn string(string: impl Into<StrValue>) -> Self {
 		Self::Str(string.into())
 	}
+	pub fn num(num: impl Into<NumValue>) -> Self {
+		Self::Num(num.into())
+	}
+	pub fn try_num<V, E>(num: V) -> Result<Self, E>
+	where
+		NumValue: TryFrom<V, Error = E>,
+	{
+		Ok(Self::Num(num.try_into()?))
+	}
 }
 
 impl From<IStr> for Val {
@@ -560,7 +672,7 @@
 		(Val::Bool(a), Val::Bool(b)) => a == b,
 		(Val::Null, Val::Null) => true,
 		(Val::Str(a), Val::Str(b)) => a == b,
-		(Val::Num(a), Val::Num(b)) => (a - b).abs() <= f64::EPSILON,
+		(Val::Num(a), Val::Num(b)) => (a.get() - b.get()).abs() <= f64::EPSILON,
 		#[cfg(feature = "exp-bigint")]
 		(Val::BigInt(a), Val::BigInt(b)) => a == b,
 		(Val::Arr(_), Val::Arr(_)) => {
modifiedcrates/jrsonnet-stdlib/src/arrays.rsdiffbeforeafterboth
--- a/crates/jrsonnet-stdlib/src/arrays.rs
+++ b/crates/jrsonnet-stdlib/src/arrays.rs
@@ -275,7 +275,7 @@
 	if arr.is_empty() {
 		return eval_on_empty(onEmpty);
 	}
-	Ok(Val::Num(arr.iter().sum::<f64>() / (arr.len() as f64)))
+	Ok(Val::try_num(arr.iter().sum::<f64>() / (arr.len() as f64))?)
 }
 
 #[builtin]
modifiedcrates/jrsonnet-stdlib/src/operator.rsdiffbeforeafterboth
--- a/crates/jrsonnet-stdlib/src/operator.rs
+++ b/crates/jrsonnet-stdlib/src/operator.rs
@@ -6,12 +6,12 @@
 	operator::evaluate_mod_op,
 	stdlib::std_format,
 	typed::{Either, Either2},
-	val::{equals, primitive_equals},
+	val::{equals, primitive_equals, NumValue},
 	IStr, Result, Val,
 };
 
 #[builtin]
-pub fn builtin_mod(a: Either![f64, IStr], b: Val) -> Result<Val> {
+pub fn builtin_mod(a: Either![NumValue, IStr], b: Val) -> Result<Val> {
 	use Either2::*;
 	evaluate_mod_op(
 		&match a {
modifiedcrates/jrsonnet-stdlib/src/sort.rsdiffbeforeafterboth
--- a/crates/jrsonnet-stdlib/src/sort.rs
+++ b/crates/jrsonnet-stdlib/src/sort.rs
@@ -20,20 +20,6 @@
 	Unknown,
 }
 
-#[derive(PartialEq)]
-struct NonNaNf64(f64);
-impl PartialOrd for NonNaNf64 {
-	fn partial_cmp(&self, other: &Self) -> Option<std::cmp::Ordering> {
-		Some(self.cmp(other))
-	}
-}
-impl Eq for NonNaNf64 {}
-impl Ord for NonNaNf64 {
-	fn cmp(&self, other: &Self) -> std::cmp::Ordering {
-		self.0.partial_cmp(&other.0).expect("non nan")
-	}
-}
-
 fn get_sort_type<T>(values: &[T], key_getter: impl Fn(&T) -> &Val) -> Result<SortKeyType> {
 	let mut sort_type = SortKeyType::Unknown;
 	for i in values {
@@ -56,7 +42,7 @@
 	let sort_type = get_sort_type(&values, |k| k)?;
 	match sort_type {
 		SortKeyType::Number => values.sort_unstable_by_key(|v| match v {
-			Val::Num(n) => NonNaNf64(*n),
+			Val::Num(n) => *n,
 			_ => unreachable!(),
 		}),
 		SortKeyType::String => values.sort_unstable_by_key(|v| match v {
@@ -95,7 +81,7 @@
 	let sort_type = get_sort_type(&vk, |v| &v.1)?;
 	match sort_type {
 		SortKeyType::Number => vk.sort_by_key(|v| match v.1 {
-			Val::Num(n) => NonNaNf64(n),
+			Val::Num(n) => n,
 			_ => unreachable!(),
 		}),
 		SortKeyType::String => vk.sort_by_key(|v| match &v.1 {
modifiedcrates/jrsonnet-stdlib/src/strings.rsdiffbeforeafterboth
before · crates/jrsonnet-stdlib/src/strings.rs
1use std::collections::BTreeSet;23use jrsonnet_evaluator::{4	bail,5	error::{ErrorKind::*, Result},6	function::builtin,7	typed::{Either2, Typed, M1},8	val::{ArrValue, IndexableVal},9	Either, IStr, Val,10};1112#[builtin]13pub const fn builtin_codepoint(str: char) -> u32 {14	str as u3215}1617#[builtin]18pub fn builtin_substr(str: IStr, from: usize, len: usize) -> String {19	str.chars().skip(from).take(len).collect()20}2122#[builtin]23pub fn builtin_char(n: u32) -> Result<char> {24	Ok(std::char::from_u32(n).ok_or_else(|| InvalidUnicodeCodepointGot(n))?)25}2627#[builtin]28pub fn builtin_str_replace(str: String, from: IStr, to: IStr) -> String {29	str.replace(&from as &str, &to as &str)30}3132#[builtin]33pub fn builtin_escape_string_bash(str_: String) -> String {34	const QUOTE: char = '\'';35	let mut out = str_.replace(QUOTE, "'\"'\"'");36	out.insert(0, QUOTE);37	out.push(QUOTE);38	out39}4041#[builtin]42pub fn builtin_escape_string_dollars(str_: String) -> String {43	str_.replace('$', "$$")44}4546#[builtin]47pub fn builtin_is_empty(str: String) -> bool {48	str.is_empty()49}5051#[builtin]52pub fn builtin_equals_ignore_case(str1: String, str2: String) -> bool {53	str1.to_ascii_lowercase() == str2.to_ascii_lowercase()54}5556#[builtin]57pub fn builtin_splitlimit(str: IStr, c: IStr, maxsplits: Either![usize, M1]) -> ArrValue {58	use Either2::*;59	match maxsplits {60		A(n) => str.splitn(n + 1, &c as &str).map(Val::string).collect(),61		B(_) => str.split(&c as &str).map(Val::string).collect(),62	}63}6465#[builtin]66pub fn builtin_splitlimitr(str: IStr, c: IStr, maxsplits: Either![usize, M1]) -> ArrValue {67	use Either2::*;68	match maxsplits {69		A(n) =>70		// rsplitn does not implement DoubleEndedIterator so collect into71		// a temporary vec72		{73			str.rsplitn(n + 1, &c as &str)74				.map(Val::string)75				.collect::<Vec<_>>()76				.into_iter()77				.rev()78				.collect()79		}80		B(_) => str.split(&c as &str).map(Val::string).collect(),81	}82}8384#[builtin]85pub fn builtin_split(str: IStr, c: IStr) -> ArrValue {86	use Either2::*;87	builtin_splitlimit(str, c, B(M1))88}8990#[builtin]91pub fn builtin_ascii_upper(str: IStr) -> String {92	str.to_ascii_uppercase()93}9495#[builtin]96pub fn builtin_ascii_lower(str: IStr) -> String {97	str.to_ascii_lowercase()98}99100#[builtin]101pub fn builtin_find_substr(pat: IStr, str: IStr) -> ArrValue {102	if pat.is_empty() || str.is_empty() || pat.len() > str.len() {103		return ArrValue::empty();104	}105106	let str = str.as_str();107	let pat = pat.as_bytes();108	let strb = str.as_bytes();109110	let max_pos = str.len() - pat.len();111112	let mut out: Vec<Val> = Vec::new();113	for (ch_idx, (i, _)) in str114		.char_indices()115		.take_while(|(i, _)| i <= &max_pos)116		.enumerate()117	{118		if &strb[i..i + pat.len()] == pat {119			out.push(Val::Num(ch_idx as f64));120		}121	}122	out.into()123}124125#[builtin]126pub fn builtin_parse_int(str: IStr) -> Result<f64> {127	if let Some(raw) = str.strip_prefix('-') {128		if raw.is_empty() {129			bail!("integer only consists of a minus")130		}131132		parse_nat::<10>(raw).map(|value| -value)133	} else {134		if str.is_empty() {135			bail!("empty integer")136		}137138		parse_nat::<10>(str.as_str())139	}140}141142#[builtin]143pub fn builtin_parse_octal(str: IStr) -> Result<f64> {144	if str.is_empty() {145		bail!("empty octal integer");146	}147148	parse_nat::<8>(str.as_str())149}150151#[builtin]152pub fn builtin_parse_hex(str: IStr) -> Result<f64> {153	if str.is_empty() {154		bail!("empty hexadecimal integer");155	}156157	parse_nat::<16>(str.as_str())158}159160fn parse_nat<const BASE: u32>(raw: &str) -> Result<f64> {161	const ZERO_CODE: u32 = '0' as u32;162	const UPPER_A_CODE: u32 = 'A' as u32;163	const LOWER_A_CODE: u32 = 'a' as u32;164165	#[inline]166	fn checked_sub_if(condition: bool, lhs: u32, rhs: u32) -> Option<u32> {167		if condition {168			lhs.checked_sub(rhs)169		} else {170			None171		}172	}173174	debug_assert!(175		1 <= BASE && BASE <= 16,176		"integer base should be between 1 and 16"177	);178179	let base = f64::from(BASE);180181	raw.chars().try_fold(0f64, |aggregate, digit| {182		let digit = digit as u32;183		// if-let-else looks better here than Option combinators184		#[allow(clippy::option_if_let_else)]185		let digit = if let Some(digit) = checked_sub_if(BASE > 10, digit, LOWER_A_CODE) {186			digit + 10187		} else if let Some(digit) = checked_sub_if(BASE > 10, digit, UPPER_A_CODE) {188			digit + 10189		} else {190			digit.checked_sub(ZERO_CODE).unwrap_or(BASE)191		};192193		if digit < BASE {194			Ok(base.mul_add(aggregate, f64::from(digit)))195		} else {196			bail!("{raw:?} is not a base {BASE} integer");197		}198	})199}200201#[cfg(feature = "exp-bigint")]202#[builtin]203pub fn builtin_bigint(v: Either![f64, IStr]) -> Result<Val> {204	use jrsonnet_evaluator::runtime_error;205	use Either2::*;206	Ok(match v {207		A(a) => {208			Val::BigInt(Box::new(a.to_string().parse().map_err(|e| {209				runtime_error!("number is not convertible to bigint: {e}")210			})?))211		}212		B(b) => Val::BigInt(Box::new(213			b.as_str()214				.parse()215				.map_err(|e| runtime_error!("bad bigint: {e}"))?,216		)),217	})218}219220#[builtin]221pub fn builtin_string_chars(str: IStr) -> ArrValue {222	ArrValue::chars(str.chars())223}224225#[builtin]226pub fn builtin_lstrip_chars(str: IStr, chars: IndexableVal) -> Result<IStr> {227	if str.is_empty() || chars.is_empty() {228		return Ok(str);229	}230231	let pattern = new_trim_pattern(chars)?;232	Ok(str.as_str().trim_start_matches(pattern).into())233}234235#[builtin]236pub fn builtin_rstrip_chars(str: IStr, chars: IndexableVal) -> Result<IStr> {237	if str.is_empty() || chars.is_empty() {238		return Ok(str);239	}240241	let pattern = new_trim_pattern(chars)?;242	Ok(str.as_str().trim_end_matches(pattern).into())243}244245#[builtin]246pub fn builtin_strip_chars(str: IStr, chars: IndexableVal) -> Result<IStr> {247	if str.is_empty() || chars.is_empty() {248		return Ok(str);249	}250251	let pattern = new_trim_pattern(chars)?;252	Ok(str.as_str().trim_matches(pattern).into())253}254255fn new_trim_pattern(chars: IndexableVal) -> Result<impl Fn(char) -> bool> {256	let chars: BTreeSet<char> = match chars {257		IndexableVal::Str(chars) => chars.chars().collect(),258		IndexableVal::Arr(chars) => chars259			.iter()260			.filter_map(|it| it.map(|it| char::from_untyped(it).ok()).transpose())261			.collect::<Result<_, _>>()?,262	};263264	Ok(move |char| chars.contains(&char))265}266267#[cfg(test)]268mod tests {269	use super::*;270271	#[test]272	fn parse_nat_base_8() {273		assert_eq!(parse_nat::<8>("0").unwrap(), 0.);274		assert_eq!(parse_nat::<8>("5").unwrap(), 5.);275		assert_eq!(parse_nat::<8>("32").unwrap(), 0o32 as f64);276		assert_eq!(parse_nat::<8>("761").unwrap(), 0o761 as f64);277	}278279	#[test]280	fn parse_nat_base_10() {281		assert_eq!(parse_nat::<10>("0").unwrap(), 0.);282		assert_eq!(parse_nat::<10>("3").unwrap(), 3.);283		assert_eq!(parse_nat::<10>("27").unwrap(), 27.);284		assert_eq!(parse_nat::<10>("123").unwrap(), 123.);285	}286287	#[test]288	fn parse_nat_base_16() {289		assert_eq!(parse_nat::<16>("0").unwrap(), 0.);290		assert_eq!(parse_nat::<16>("A").unwrap(), 10.);291		assert_eq!(parse_nat::<16>("a9").unwrap(), 0xA9 as f64);292		assert_eq!(parse_nat::<16>("BbC").unwrap(), 0xBBC as f64);293	}294}
after · crates/jrsonnet-stdlib/src/strings.rs
1use std::collections::BTreeSet;23use jrsonnet_evaluator::{4	bail,5	error::{ErrorKind::*, Result},6	function::builtin,7	typed::{Either2, Typed, M1},8	val::{ArrValue, IndexableVal},9	Either, IStr, Val,10};1112#[builtin]13pub const fn builtin_codepoint(str: char) -> u32 {14	str as u3215}1617#[builtin]18pub fn builtin_substr(str: IStr, from: usize, len: usize) -> String {19	str.chars().skip(from).take(len).collect()20}2122#[builtin]23pub fn builtin_char(n: u32) -> Result<char> {24	Ok(std::char::from_u32(n).ok_or_else(|| InvalidUnicodeCodepointGot(n))?)25}2627#[builtin]28pub fn builtin_str_replace(str: String, from: IStr, to: IStr) -> String {29	str.replace(&from as &str, &to as &str)30}3132#[builtin]33pub fn builtin_escape_string_bash(str_: String) -> String {34	const QUOTE: char = '\'';35	let mut out = str_.replace(QUOTE, "'\"'\"'");36	out.insert(0, QUOTE);37	out.push(QUOTE);38	out39}4041#[builtin]42pub fn builtin_escape_string_dollars(str_: String) -> String {43	str_.replace('$', "$$")44}4546#[builtin]47pub fn builtin_is_empty(str: String) -> bool {48	str.is_empty()49}5051#[builtin]52pub fn builtin_equals_ignore_case(str1: String, str2: String) -> bool {53	str1.to_ascii_lowercase() == str2.to_ascii_lowercase()54}5556#[builtin]57pub fn builtin_splitlimit(str: IStr, c: IStr, maxsplits: Either![usize, M1]) -> ArrValue {58	use Either2::*;59	match maxsplits {60		A(n) => str.splitn(n + 1, &c as &str).map(Val::string).collect(),61		B(_) => str.split(&c as &str).map(Val::string).collect(),62	}63}6465#[builtin]66pub fn builtin_splitlimitr(str: IStr, c: IStr, maxsplits: Either![usize, M1]) -> ArrValue {67	use Either2::*;68	match maxsplits {69		A(n) =>70		// rsplitn does not implement DoubleEndedIterator so collect into71		// a temporary vec72		{73			str.rsplitn(n + 1, &c as &str)74				.map(Val::string)75				.collect::<Vec<_>>()76				.into_iter()77				.rev()78				.collect()79		}80		B(_) => str.split(&c as &str).map(Val::string).collect(),81	}82}8384#[builtin]85pub fn builtin_split(str: IStr, c: IStr) -> ArrValue {86	use Either2::*;87	builtin_splitlimit(str, c, B(M1))88}8990#[builtin]91pub fn builtin_ascii_upper(str: IStr) -> String {92	str.to_ascii_uppercase()93}9495#[builtin]96pub fn builtin_ascii_lower(str: IStr) -> String {97	str.to_ascii_lowercase()98}99100#[builtin]101pub fn builtin_find_substr(pat: IStr, str: IStr) -> ArrValue {102	if pat.is_empty() || str.is_empty() || pat.len() > str.len() {103		return ArrValue::empty();104	}105106	let str = str.as_str();107	let pat = pat.as_bytes();108	let strb = str.as_bytes();109110	let max_pos = str.len() - pat.len();111112	let mut out: Vec<Val> = Vec::new();113	for (ch_idx, (i, _)) in str114		.char_indices()115		.take_while(|(i, _)| i <= &max_pos)116		.enumerate()117	{118		if &strb[i..i + pat.len()] == pat {119			out.push(Val::Num(120				ch_idx.try_into().expect("unrealisticly long string"),121			));122		}123	}124	out.into()125}126127#[builtin]128pub fn builtin_parse_int(str: IStr) -> Result<f64> {129	if let Some(raw) = str.strip_prefix('-') {130		if raw.is_empty() {131			bail!("integer only consists of a minus")132		}133134		parse_nat::<10>(raw).map(|value| -value)135	} else {136		if str.is_empty() {137			bail!("empty integer")138		}139140		parse_nat::<10>(str.as_str())141	}142}143144#[builtin]145pub fn builtin_parse_octal(str: IStr) -> Result<f64> {146	if str.is_empty() {147		bail!("empty octal integer");148	}149150	parse_nat::<8>(str.as_str())151}152153#[builtin]154pub fn builtin_parse_hex(str: IStr) -> Result<f64> {155	if str.is_empty() {156		bail!("empty hexadecimal integer");157	}158159	parse_nat::<16>(str.as_str())160}161162fn parse_nat<const BASE: u32>(raw: &str) -> Result<f64> {163	const ZERO_CODE: u32 = '0' as u32;164	const UPPER_A_CODE: u32 = 'A' as u32;165	const LOWER_A_CODE: u32 = 'a' as u32;166167	#[inline]168	fn checked_sub_if(condition: bool, lhs: u32, rhs: u32) -> Option<u32> {169		if condition {170			lhs.checked_sub(rhs)171		} else {172			None173		}174	}175176	debug_assert!(177		1 <= BASE && BASE <= 16,178		"integer base should be between 1 and 16"179	);180181	let base = f64::from(BASE);182183	raw.chars().try_fold(0f64, |aggregate, digit| {184		let digit = digit as u32;185		// if-let-else looks better here than Option combinators186		#[allow(clippy::option_if_let_else)]187		let digit = if let Some(digit) = checked_sub_if(BASE > 10, digit, LOWER_A_CODE) {188			digit + 10189		} else if let Some(digit) = checked_sub_if(BASE > 10, digit, UPPER_A_CODE) {190			digit + 10191		} else {192			digit.checked_sub(ZERO_CODE).unwrap_or(BASE)193		};194195		if digit < BASE {196			Ok(base.mul_add(aggregate, f64::from(digit)))197		} else {198			bail!("{raw:?} is not a base {BASE} integer");199		}200	})201}202203#[cfg(feature = "exp-bigint")]204#[builtin]205pub fn builtin_bigint(v: Either![f64, IStr]) -> Result<Val> {206	use jrsonnet_evaluator::runtime_error;207	use Either2::*;208	Ok(match v {209		A(a) => {210			Val::BigInt(Box::new(a.to_string().parse().map_err(|e| {211				runtime_error!("number is not convertible to bigint: {e}")212			})?))213		}214		B(b) => Val::BigInt(Box::new(215			b.as_str()216				.parse()217				.map_err(|e| runtime_error!("bad bigint: {e}"))?,218		)),219	})220}221222#[builtin]223pub fn builtin_string_chars(str: IStr) -> ArrValue {224	ArrValue::chars(str.chars())225}226227#[builtin]228pub fn builtin_lstrip_chars(str: IStr, chars: IndexableVal) -> Result<IStr> {229	if str.is_empty() || chars.is_empty() {230		return Ok(str);231	}232233	let pattern = new_trim_pattern(chars)?;234	Ok(str.as_str().trim_start_matches(pattern).into())235}236237#[builtin]238pub fn builtin_rstrip_chars(str: IStr, chars: IndexableVal) -> Result<IStr> {239	if str.is_empty() || chars.is_empty() {240		return Ok(str);241	}242243	let pattern = new_trim_pattern(chars)?;244	Ok(str.as_str().trim_end_matches(pattern).into())245}246247#[builtin]248pub fn builtin_strip_chars(str: IStr, chars: IndexableVal) -> Result<IStr> {249	if str.is_empty() || chars.is_empty() {250		return Ok(str);251	}252253	let pattern = new_trim_pattern(chars)?;254	Ok(str.as_str().trim_matches(pattern).into())255}256257fn new_trim_pattern(chars: IndexableVal) -> Result<impl Fn(char) -> bool> {258	let chars: BTreeSet<char> = match chars {259		IndexableVal::Str(chars) => chars.chars().collect(),260		IndexableVal::Arr(chars) => chars261			.iter()262			.filter_map(|it| it.map(|it| char::from_untyped(it).ok()).transpose())263			.collect::<Result<_, _>>()?,264	};265266	Ok(move |char| chars.contains(&char))267}268269#[cfg(test)]270mod tests {271	use super::*;272273	#[test]274	fn parse_nat_base_8() {275		assert_eq!(parse_nat::<8>("0").unwrap(), 0.);276		assert_eq!(parse_nat::<8>("5").unwrap(), 5.);277		assert_eq!(parse_nat::<8>("32").unwrap(), 0o32 as f64);278		assert_eq!(parse_nat::<8>("761").unwrap(), 0o761 as f64);279	}280281	#[test]282	fn parse_nat_base_10() {283		assert_eq!(parse_nat::<10>("0").unwrap(), 0.);284		assert_eq!(parse_nat::<10>("3").unwrap(), 3.);285		assert_eq!(parse_nat::<10>("27").unwrap(), 27.);286		assert_eq!(parse_nat::<10>("123").unwrap(), 123.);287	}288289	#[test]290	fn parse_nat_base_16() {291		assert_eq!(parse_nat::<16>("0").unwrap(), 0.);292		assert_eq!(parse_nat::<16>("A").unwrap(), 10.);293		assert_eq!(parse_nat::<16>("a9").unwrap(), 0xA9 as f64);294		assert_eq!(parse_nat::<16>("BbC").unwrap(), 0xBBC as f64);295	}296}