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
before · crates/jrsonnet-evaluator/src/stdlib/format.rs
1//! faster std.format impl2#![allow(clippy::too_many_arguments)]34use jrsonnet_gcmodule::Trace;5use jrsonnet_interner::IStr;6use jrsonnet_types::ValType;7use thiserror::Error;89use crate::{10	bail,11	error::{format_found, suggest_object_fields, ErrorKind::*},12	typed::Typed,13	Error, ObjValue, Result, Val,14};1516#[derive(Debug, Clone, Error, Trace)]17pub enum FormatError {18	#[error("truncated format code")]19	TruncatedFormatCode,20	#[error("unrecognized conversion type: {0}")]21	UnrecognizedConversionType(char),2223	#[error("not enough values")]24	NotEnoughValues,2526	#[error("cannot use * width with object")]27	CannotUseStarWidthWithObject,28	#[error("mapping keys required")]29	MappingKeysRequired,30	#[error("no such format field: {0}")]31	NoSuchFormatField(IStr),3233	#[error("expected subfield <{0}> to be an object, got {1} instead")]34	SubfieldDidntYieldAnObject(IStr, ValType),35	#[error("subfield not found: <[{full}]{current}>{}", format_found(.found, "subfield"))]36	SubfieldNotFound {37		current: IStr,38		full: IStr,39		found: Box<Vec<IStr>>,40	},41}4243impl From<FormatError> for Error {44	fn from(e: FormatError) -> Self {45		Self::new(Format(e))46	}47}4849use FormatError::*;5051type ParseResult<'t, T> = std::result::Result<(T, &'t str), FormatError>;5253pub fn try_parse_mapping_key(str: &str) -> ParseResult<'_, &str> {54	if str.is_empty() {55		return Err(TruncatedFormatCode);56	}57	let bytes = str.as_bytes();58	if bytes[0] == b'(' {59		let mut i = 1;60		while i < bytes.len() {61			if bytes[i] == b')' {62				return Ok((&str[1..i], &str[i + 1..]));63			}64			i += 1;65		}66		Err(TruncatedFormatCode)67	} else {68		Ok(("", str))69	}70}7172#[cfg(test)]73pub mod tests_key {74	use super::*;7576	#[test]77	fn parse_key() {78		assert_eq!(79			try_parse_mapping_key("(hello ) world").unwrap(),80			("hello ", " world")81		);82		assert_eq!(try_parse_mapping_key("() world").unwrap(), ("", " world"));83		assert_eq!(try_parse_mapping_key(" world").unwrap(), ("", " world"));84		assert_eq!(85			try_parse_mapping_key(" () world").unwrap(),86			("", " () world")87		);88	}8990	#[test]91	#[should_panic = "TruncatedFormatCode"]92	fn parse_key_missing_start() {93		try_parse_mapping_key("").unwrap();94	}9596	#[test]97	#[should_panic = "TruncatedFormatCode"]98	fn parse_key_missing_end() {99		try_parse_mapping_key("(   ").unwrap();100	}101}102103#[allow(clippy::struct_excessive_bools)]104#[derive(Default, Debug)]105pub struct CFlags {106	pub alt: bool,107	pub zero: bool,108	pub left: bool,109	pub blank: bool,110	pub sign: bool,111}112113pub fn try_parse_cflags(str: &str) -> ParseResult<'_, CFlags> {114	if str.is_empty() {115		return Err(TruncatedFormatCode);116	}117	let bytes = str.as_bytes();118	let mut i = 0;119	let mut out = CFlags::default();120	loop {121		if bytes.len() == i {122			return Err(TruncatedFormatCode);123		}124		match bytes[i] {125			b'#' => out.alt = true,126			b'0' => out.zero = true,127			b'-' => out.left = true,128			b' ' => out.blank = true,129			b'+' => out.sign = true,130			_ => break,131		}132		i += 1;133	}134	Ok((out, &str[i..]))135}136137#[derive(Debug, PartialEq, Eq)]138pub enum Width {139	Star,140	Fixed(usize),141}142pub fn try_parse_field_width(str: &str) -> ParseResult<'_, Width> {143	if str.is_empty() {144		return Err(TruncatedFormatCode);145	}146	let bytes = str.as_bytes();147	if bytes[0] == b'*' {148		return Ok((Width::Star, &str[1..]));149	}150	let mut out: usize = 0;151	let mut digits = 0;152	while let Some(digit) = (bytes[digits] as char).to_digit(10) {153		out *= 10;154		out += digit as usize;155		digits += 1;156		if digits == bytes.len() {157			return Err(TruncatedFormatCode);158		}159	}160	Ok((Width::Fixed(out), &str[digits..]))161}162163pub fn try_parse_precision(str: &str) -> ParseResult<'_, Option<Width>> {164	if str.is_empty() {165		return Err(TruncatedFormatCode);166	}167	let bytes = str.as_bytes();168	if bytes[0] == b'.' {169		try_parse_field_width(&str[1..]).map(|(r, s)| (Some(r), s))170	} else {171		Ok((None, str))172	}173}174175// Only skips176pub fn try_parse_length_modifier(str: &str) -> ParseResult<'_, ()> {177	if str.is_empty() {178		return Err(TruncatedFormatCode);179	}180	let bytes = str.as_bytes();181	let mut idx = 0;182	while bytes[idx] == b'h' || bytes[idx] == b'l' || bytes[idx] == b'L' {183		idx += 1;184		if bytes.len() == idx {185			return Err(TruncatedFormatCode);186		}187	}188	Ok(((), &str[idx..]))189}190191#[derive(Debug, PartialEq, Eq)]192pub enum ConvTypeV {193	Decimal,194	Octal,195	Hexadecimal,196	Scientific,197	Float,198	Shorter,199	Char,200	String,201	Percent,202}203pub struct ConvType {204	v: ConvTypeV,205	caps: bool,206}207208pub fn parse_conversion_type(str: &str) -> ParseResult<'_, ConvType> {209	if str.is_empty() {210		return Err(TruncatedFormatCode);211	}212213	let code = str.as_bytes()[0];214	let v: (ConvTypeV, bool) = match code {215		b'd' | b'i' | b'u' => (ConvTypeV::Decimal, false),216		b'o' => (ConvTypeV::Octal, false),217		b'x' => (ConvTypeV::Hexadecimal, false),218		b'X' => (ConvTypeV::Hexadecimal, true),219		b'e' => (ConvTypeV::Scientific, false),220		b'E' => (ConvTypeV::Scientific, true),221		b'f' => (ConvTypeV::Float, false),222		b'F' => (ConvTypeV::Float, true),223		b'g' => (ConvTypeV::Shorter, false),224		b'G' => (ConvTypeV::Shorter, true),225		b'c' => (ConvTypeV::Char, false),226		b's' => (ConvTypeV::String, false),227		b'%' => (ConvTypeV::Percent, false),228		c => return Err(UnrecognizedConversionType(c as char)),229	};230231	Ok((ConvType { v: v.0, caps: v.1 }, &str[1..]))232}233234#[derive(Debug)]235pub struct Code<'s> {236	mkey: &'s str,237	cflags: CFlags,238	width: Width,239	precision: Option<Width>,240	convtype: ConvTypeV,241	caps: bool,242}243pub fn parse_code(str: &str) -> ParseResult<'_, Code<'_>> {244	if str.is_empty() {245		return Err(TruncatedFormatCode);246	}247	let (mkey, str) = try_parse_mapping_key(str)?;248	let (cflags, str) = try_parse_cflags(str)?;249	let (width, str) = try_parse_field_width(str)?;250	let (precision, str) = try_parse_precision(str)?;251	let ((), str) = try_parse_length_modifier(str)?;252	let (convtype, str) = parse_conversion_type(str)?;253254	Ok((255		Code {256			mkey,257			cflags,258			width,259			precision,260			convtype: convtype.v,261			caps: convtype.caps,262		},263		str,264	))265}266267#[derive(Debug)]268pub enum Element<'s> {269	String(&'s str),270	Code(Code<'s>),271}272pub fn parse_codes(mut str: &str) -> Result<Vec<Element<'_>>> {273	let mut bytes = str.as_bytes();274	let mut out = vec![];275	let mut offset = 0;276277	loop {278		while offset != bytes.len() && bytes[offset] != b'%' {279			offset += 1;280		}281		if offset != 0 {282			out.push(Element::String(&str[0..offset]));283		}284		if offset == bytes.len() {285			return Ok(out);286		}287		str = &str[offset + 1..];288		let code;289		(code, str) = parse_code(str)?;290		bytes = str.as_bytes();291		offset = 0;292293		out.push(Element::Code(code));294	}295}296297const NUMBERS: &[u8] = b"0123456789abcdefghijklmnopqrstuvwxyz";298299#[inline]300pub fn render_integer(301	out: &mut String,302	iv: f64,303	padding: usize,304	precision: usize,305	blank: bool,306	sign: bool,307	radix: i64,308	prefix: &str,309	caps: bool,310) {311	let radix = radix as f64;312	let iv = iv.floor();313	// Digit char indexes in reverse order, i.e314	// for radix = 16 and n = 12f: [15, 2, 1]315	let digits = if iv == 0.0 {316		vec![0u8]317	} else {318		let mut v = iv.abs();319		let mut nums = Vec::with_capacity(1);320		while v != 0.0 {321			nums.push((v % radix) as u8);322			v = (v / radix).floor();323		}324		nums325	};326	let neg = iv < 0.0;327	#[allow(clippy::bool_to_int_with_if)]328	let zp = padding.saturating_sub(if neg || blank || sign { 1 } else { 0 });329	let zp2 = zp330		.max(precision)331		.saturating_sub(prefix.len() + digits.len());332333	if neg {334		out.push('-');335	} else if sign {336		out.push('+');337	} else if blank {338		out.push(' ');339	}340341	out.reserve(zp2);342	for _ in 0..zp2 {343		out.push('0');344	}345	out.push_str(prefix);346347	for digit in digits.into_iter().rev() {348		let ch = NUMBERS[digit as usize] as char;349		out.push(if caps { ch.to_ascii_uppercase() } else { ch });350	}351}352353pub fn render_decimal(354	out: &mut String,355	iv: f64,356	padding: usize,357	precision: usize,358	blank: bool,359	sign: bool,360) {361	render_integer(out, iv, padding, precision, blank, sign, 10, "", false);362}363pub fn render_octal(364	out: &mut String,365	iv: f64,366	padding: usize,367	precision: usize,368	alt: bool,369	blank: bool,370	sign: bool,371) {372	render_integer(373		out,374		iv,375		padding,376		precision,377		blank,378		sign,379		8,380		if alt && iv != 0.0 { "0" } else { "" },381		false,382	);383}384385#[allow(clippy::fn_params_excessive_bools)]386pub fn render_hexadecimal(387	out: &mut String,388	iv: f64,389	padding: usize,390	precision: usize,391	alt: bool,392	blank: bool,393	sign: bool,394	caps: bool,395) {396	render_integer(397		out,398		iv,399		padding,400		precision,401		blank,402		sign,403		16,404		match (alt, caps) {405			(true, true) => "0X",406			(true, false) => "0x",407			(false, _) => "",408		},409		caps,410	);411}412413#[allow(clippy::fn_params_excessive_bools)]414pub fn render_float(415	out: &mut String,416	n: f64,417	mut padding: usize,418	precision: usize,419	blank: bool,420	sign: bool,421	ensure_pt: bool,422	trailing: bool,423) {424	#[allow(clippy::bool_to_int_with_if)]425	let dot_size = if precision == 0 && !ensure_pt { 0 } else { 1 };426	padding = padding.saturating_sub(dot_size + precision);427	render_decimal(out, n.floor(), padding, 0, blank, sign);428	if precision == 0 {429		if ensure_pt {430			out.push('.');431		}432		return;433	}434	let frac = n435		.fract()436		.mul_add(10.0_f64.powf(precision as f64), 0.5)437		.floor();438	if trailing || frac > 0.0 {439		out.push('.');440		let mut frac_str = String::new();441		render_decimal(&mut frac_str, frac, precision, 0, false, false);442		let mut trim = frac_str.len();443		if !trailing {444			for b in frac_str.as_bytes().iter().rev() {445				if *b == b'0' {446					trim -= 1;447				} else {448					break;449				}450			}451		}452		out.push_str(&frac_str[..trim]);453	} else if ensure_pt {454		out.push('.');455	}456}457458#[allow(clippy::fn_params_excessive_bools)]459pub fn render_float_sci(460	out: &mut String,461	n: f64,462	mut padding: usize,463	precision: usize,464	blank: bool,465	sign: bool,466	ensure_pt: bool,467	trailing: bool,468	caps: bool,469) {470	let exponent = n.log10().floor();471	let mantissa = if exponent as i16 == -324 {472		n * 10.0 / 10.0_f64.powf(exponent + 1.0)473	} else {474		n / 10.0_f64.powf(exponent)475	};476	let mut exponent_str = String::new();477	render_decimal(&mut exponent_str, exponent, 3, 0, false, true);478479	// +1 for e480	padding = padding.saturating_sub(exponent_str.len() + 1);481482	render_float(483		out, mantissa, padding, precision, blank, sign, ensure_pt, trailing,484	);485	out.push(if caps { 'E' } else { 'e' });486	out.push_str(&exponent_str);487}488489#[allow(clippy::too_many_lines)]490pub fn format_code(491	out: &mut String,492	value: &Val,493	code: &Code<'_>,494	width: usize,495	precision: Option<usize>,496) -> Result<()> {497	let clfags = &code.cflags;498	let (fpprec, iprec) = precision.map_or((6, 0), |v| (v, v));499	let padding = if clfags.zero && !clfags.left {500		width501	} else {502		0503	};504505	// TODO: If left padded, can optimize by writing directly to out506	let mut tmp_out = String::new();507508	match code.convtype {509		ConvTypeV::String => tmp_out.push_str(&value.clone().to_string()?),510		ConvTypeV::Decimal => {511			let value = f64::from_untyped(value.clone())?;512			render_decimal(513				&mut tmp_out,514				value,515				padding,516				iprec,517				clfags.blank,518				clfags.sign,519			);520		}521		ConvTypeV::Octal => {522			let value = f64::from_untyped(value.clone())?;523			render_octal(524				&mut tmp_out,525				value,526				padding,527				iprec,528				clfags.alt,529				clfags.blank,530				clfags.sign,531			);532		}533		ConvTypeV::Hexadecimal => {534			let value = f64::from_untyped(value.clone())?;535			render_hexadecimal(536				&mut tmp_out,537				value,538				padding,539				iprec,540				clfags.alt,541				clfags.blank,542				clfags.sign,543				code.caps,544			);545		}546		ConvTypeV::Scientific => {547			let value = f64::from_untyped(value.clone())?;548			render_float_sci(549				&mut tmp_out,550				value,551				padding,552				fpprec,553				clfags.blank,554				clfags.sign,555				clfags.alt,556				true,557				code.caps,558			);559		}560		ConvTypeV::Float => {561			let value = f64::from_untyped(value.clone())?;562			render_float(563				&mut tmp_out,564				value,565				padding,566				fpprec,567				clfags.blank,568				clfags.sign,569				clfags.alt,570				true,571			);572		}573		ConvTypeV::Shorter => {574			let value = f64::from_untyped(value.clone())?;575			let exponent = if value == 0.0 {576				0.0577			} else {578				value.abs().log10().floor()579			};580			if exponent < -4.0 || exponent >= fpprec as f64 {581				render_float_sci(582					&mut tmp_out,583					value,584					padding,585					fpprec - 1,586					clfags.blank,587					clfags.sign,588					clfags.alt,589					clfags.alt,590					code.caps,591				);592			} else {593				let digits_before_pt = 1.max(exponent as usize + 1);594				render_float(595					&mut tmp_out,596					value,597					padding,598					fpprec - digits_before_pt,599					clfags.blank,600					clfags.sign,601					clfags.alt,602					clfags.alt,603				);604			}605		}606		ConvTypeV::Char => match value.clone() {607			Val::Num(n) => tmp_out.push(608				std::char::from_u32(n as u32)609					.ok_or_else(|| InvalidUnicodeCodepointGot(n as u32))?,610			),611			Val::Str(s) => {612				let s = s.into_flat();613				if s.chars().count() != 1 {614					bail!("%c expected 1 char string, got {}", s.chars().count());615				}616				tmp_out.push_str(&s);617			}618			_ => {619				bail!(TypeMismatch(620					"%c requires number/string",621					vec![ValType::Num, ValType::Str],622					value.value_type(),623				));624			}625		},626		ConvTypeV::Percent => tmp_out.push('%'),627	};628629	let padding = width.saturating_sub(tmp_out.len());630631	if !clfags.left {632		for _ in 0..padding {633			out.push(' ');634		}635	}636	out.push_str(&tmp_out);637	if clfags.left {638		for _ in 0..padding {639			out.push(' ');640		}641	}642643	Ok(())644}645646pub fn format_arr(str: &str, mut values: &[Val]) -> Result<String> {647	let codes = parse_codes(str)?;648	let mut out = String::new();649	let value_count = values.len();650651	for code in codes {652		match code {653			Element::String(s) => {654				out.push_str(s);655			}656			Element::Code(c) => {657				let width = match c.width {658					Width::Star => {659						if values.is_empty() {660							bail!(NotEnoughValues);661						}662						let value = &values[0];663						values = &values[1..];664						usize::from_untyped(value.clone())?665					}666					Width::Fixed(n) => n,667				};668				let precision = match c.precision {669					Some(Width::Star) => {670						if values.is_empty() {671							bail!(NotEnoughValues);672						}673						let value = &values[0];674						values = &values[1..];675						Some(usize::from_untyped(value.clone())?)676					}677					Some(Width::Fixed(n)) => Some(n),678					None => None,679				};680681				// %% should not consume a value682				let value = if c.convtype == ConvTypeV::Percent {683					&Val::Null684				} else {685					if values.is_empty() {686						bail!(NotEnoughValues);687					}688					let value = &values[0];689					values = &values[1..];690					value691				};692693				format_code(&mut out, value, &c, width, precision)?;694			}695		}696	}697698	if !values.is_empty() {699		bail!(700			"too many values to format, expected {value_count}, got {}",701			value_count + values.len()702		)703	}704705	Ok(out)706}707708fn get_dotted_field(obj: ObjValue, field: &str) -> Result<Val> {709	let mut current = Val::Obj(obj);710	let mut name_offset = 0;711	for component in field.split('.') {712		let end_offset = name_offset + component.len();713		current = if let Val::Obj(obj) = current {714			if let Some(value) = obj.get(component.into())? {715				value716			} else {717				let current = &field[name_offset..end_offset];718				let full = &field[..name_offset];719				let found = Box::new(suggest_object_fields(&obj, current.into()));720				bail!(SubfieldNotFound {721					current: current.into(),722					full: full.into(),723					found,724				})725			}726		} else {727			// No underflow may happen, initially we always start with an object728			let subfield = &field[..name_offset - 1];729			bail!(SubfieldDidntYieldAnObject(730				subfield.into(),731				current.value_type()732			));733		};734		name_offset = end_offset + 1;735	}736	Ok(current)737}738739pub fn format_obj(str: &str, values: &ObjValue) -> Result<String> {740	let codes = parse_codes(str)?;741	let mut out = String::new();742743	for code in codes {744		match code {745			Element::String(s) => {746				out.push_str(s);747			}748			Element::Code(c) => {749				// TODO: Operate on ref750				let f: IStr = c.mkey.into();751				let width = match c.width {752					Width::Star => {753						bail!(CannotUseStarWidthWithObject);754					}755					Width::Fixed(n) => n,756				};757				let precision = match c.precision {758					Some(Width::Star) => {759						bail!(CannotUseStarWidthWithObject);760					}761					Some(Width::Fixed(n)) => Some(n),762					None => None,763				};764765				let value = if c.convtype == ConvTypeV::Percent {766					Val::Null767				} else {768					if f.is_empty() {769						bail!(MappingKeysRequired);770					}771					if let Some(v) = values.get(f.clone())? {772						v773					} else {774						get_dotted_field(values.clone(), &f)?775					}776				};777778				format_code(&mut out, &value, &c, width, precision)?;779			}780		}781	}782783	Ok(out)784}785786#[cfg(test)]787pub mod test_format {788	use super::*;789790	#[test]791	fn parse() {792		assert_eq!(793			parse_codes(794				"How much error budget is left looking at our %.3f%% availability gurantees?"795			)796			.unwrap()797			.len(),798			4799		);800	}801802	#[test]803	fn octals() {804		assert_eq!(format_arr("%#o", &[Val::Num(8.0)]).unwrap(), "010");805		assert_eq!(format_arr("%#4o", &[Val::Num(8.0)]).unwrap(), " 010");806		assert_eq!(format_arr("%4o", &[Val::Num(8.0)]).unwrap(), "  10");807		assert_eq!(format_arr("%04o", &[Val::Num(8.0)]).unwrap(), "0010");808		assert_eq!(format_arr("%+4o", &[Val::Num(8.0)]).unwrap(), " +10");809		assert_eq!(format_arr("%+04o", &[Val::Num(8.0)]).unwrap(), "+010");810		assert_eq!(format_arr("%-4o", &[Val::Num(8.0)]).unwrap(), "10  ");811		assert_eq!(format_arr("%+-4o", &[Val::Num(8.0)]).unwrap(), "+10 ");812		assert_eq!(format_arr("%+-04o", &[Val::Num(8.0)]).unwrap(), "+10 ");813	}814815	#[test]816	fn percent_doesnt_consumes_values() {817		assert_eq!(818			format_arr(819				"How much error budget is left looking at our %.3f%% availability gurantees?",820				&[Val::Num(4.0)]821			)822			.unwrap(),823			"How much error budget is left looking at our 4.000% availability gurantees?"824		);825	}826}
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
--- a/crates/jrsonnet-stdlib/src/strings.rs
+++ b/crates/jrsonnet-stdlib/src/strings.rs
@@ -116,7 +116,9 @@
 		.enumerate()
 	{
 		if &strb[i..i + pat.len()] == pat {
-			out.push(Val::Num(ch_idx as f64));
+			out.push(Val::Num(
+				ch_idx.try_into().expect("unrealisticly long string"),
+			));
 		}
 	}
 	out.into()