git.delta.rocks / jrsonnet / refs/commits / 7af406eaa740

difftreelog

feat return NumValue directly from parser

rlsuqplzYaroslav Bolyukin2026-04-25parent: #eee6c62.patch.diff
in: master

15 files changed

modifiedbindings/jsonnet/src/val_make.rsdiffbeforeafterboth
--- a/bindings/jsonnet/src/val_make.rs
+++ b/bindings/jsonnet/src/val_make.rs
@@ -5,10 +5,7 @@
 	os::raw::{c_char, c_double, c_int},
 };
 
-use jrsonnet_evaluator::{
-	ObjValue, Val,
-	val::{ArrValue, NumValue},
-};
+use jrsonnet_evaluator::{NumValue, ObjValue, Val};
 
 use crate::VM;
 
modifiedcrates/jrsonnet-evaluator/src/error.rsdiffbeforeafterboth
--- a/crates/jrsonnet-evaluator/src/error.rs
+++ b/crates/jrsonnet-evaluator/src/error.rs
@@ -2,7 +2,9 @@
 
 use jrsonnet_gcmodule::{Acyclic, Trace};
 use jrsonnet_interner::IStr;
-use jrsonnet_ir::{BinaryOpType, Source, SourcePath, Span, Spanned, UnaryOpType};
+use jrsonnet_ir::{
+	BinaryOpType, ConvertNumValueError, Source, SourcePath, Span, Spanned, UnaryOpType,
+};
 use jrsonnet_types::ValType;
 use thiserror::Error;
 
@@ -11,7 +13,6 @@
 	function::{CallLocation, FunctionSignature, ParamName},
 	stdlib::format::FormatError,
 	typed::TypeLocError,
-	val::ConvertNumValueError,
 };
 
 #[derive(Debug, Clone)]
@@ -228,6 +229,11 @@
 		Self::new(e)
 	}
 }
+impl From<ConvertNumValueError> for Error {
+	fn from(e: ConvertNumValueError) -> Self {
+		Self::new(ErrorKind::ConvertNumValue(e))
+	}
+}
 
 impl From<Infallible> for Error {
 	fn from(_value: Infallible) -> Self {
modifiedcrates/jrsonnet-evaluator/src/evaluate/mod.rsdiffbeforeafterboth
--- a/crates/jrsonnet-evaluator/src/evaluate/mod.rs
+++ b/crates/jrsonnet-evaluator/src/evaluate/mod.rs
@@ -21,7 +21,7 @@
 	function::{CallLocation, FuncDesc, FuncVal, PreparedFuncVal},
 	in_frame,
 	typed::{FromUntyped, IntoUntyped as _, Typed},
-	val::{CachedUnbound, IndexableVal, NumValue, StrValue, Thunk},
+	val::{CachedUnbound, IndexableVal, StrValue, Thunk},
 	with_state,
 };
 pub mod destructure;
@@ -58,9 +58,7 @@
 	}
 	Some(match expr {
 		Expr::Str(s) => Val::string(s.clone()),
-		Expr::Num(n) => {
-			Val::Num(NumValue::new(*n).expect("parser will not allow non-finite values"))
-		}
+		Expr::Num(n) => Val::Num(*n),
 		Expr::Literal(LiteralType::False) => Val::Bool(false),
 		Expr::Literal(LiteralType::True) => Val::Bool(true),
 		Expr::Literal(LiteralType::Null) => Val::Null,
modifiedcrates/jrsonnet-evaluator/src/integrations/serde.rsdiffbeforeafterboth
--- a/crates/jrsonnet-evaluator/src/integrations/serde.rs
+++ b/crates/jrsonnet-evaluator/src/integrations/serde.rs
@@ -1,6 +1,7 @@
 use std::borrow::Cow;
 
 use jrsonnet_interner::{IBytes, IStr};
+use jrsonnet_ir::NumValue;
 use serde::{
 	Deserialize, Serialize, Serializer,
 	de::{self, Visitor},
@@ -12,7 +13,6 @@
 
 use crate::{
 	Error as JrError, ObjValue, ObjValueBuilder, Result, Val, in_description_frame, runtime_error,
-	val::NumValue,
 };
 
 impl<'de> Deserialize<'de> for Val {
modifiedcrates/jrsonnet-evaluator/src/lib.rsdiffbeforeafterboth
--- a/crates/jrsonnet-evaluator/src/lib.rs
+++ b/crates/jrsonnet-evaluator/src/lib.rs
@@ -42,6 +42,7 @@
 use jrsonnet_gcmodule::{Cc, Trace, cc_dyn};
 pub use jrsonnet_interner::{IBytes, IStr};
 pub use jrsonnet_ir as parser;
+pub use jrsonnet_ir::NumValue;
 use jrsonnet_ir::{Expr, Source, SourcePath};
 #[doc(hidden)]
 pub use jrsonnet_macros;
modifiedcrates/jrsonnet-evaluator/src/stdlib/format.rsdiffbeforeafterboth
--- a/crates/jrsonnet-evaluator/src/stdlib/format.rs
+++ b/crates/jrsonnet-evaluator/src/stdlib/format.rs
@@ -829,7 +829,7 @@
 #[cfg(test)]
 pub mod test_format {
 	use super::*;
-	use crate::val::NumValue;
+	use crate::NumValue;
 
 	#[test]
 	fn parse() {
modifiedcrates/jrsonnet-evaluator/src/typed/conversions.rsdiffbeforeafterboth
--- a/crates/jrsonnet-evaluator/src/typed/conversions.rs
+++ b/crates/jrsonnet-evaluator/src/typed/conversions.rs
@@ -2,6 +2,8 @@
 
 use jrsonnet_gcmodule::Trace;
 use jrsonnet_interner::{IBytes, IStr};
+use jrsonnet_ir::NumValue;
+pub use jrsonnet_ir::{MAX_SAFE_INTEGER, MIN_SAFE_INTEGER};
 use jrsonnet_types::{ComplexValType, ValType};
 
 use crate::{
@@ -10,7 +12,7 @@
 	bail,
 	function::FuncVal,
 	typed::CheckType,
-	val::{IndexableVal, NumValue, StrValue, ThunkMapper},
+	val::{IndexableVal, StrValue, ThunkMapper},
 };
 
 #[doc(hidden)]
@@ -219,11 +221,6 @@
 		Ok(inner.map(<ThunkFromUntyped<T>>::default()))
 	}
 }
-
-#[expect(clippy::cast_precision_loss, reason = "checked to not overflow")]
-pub const MAX_SAFE_INTEGER: f64 = ((1u64 << (f64::MANTISSA_DIGITS)) - 1) as f64;
-#[expect(clippy::cast_precision_loss, reason = "checked to not overflow")]
-pub const MIN_SAFE_INTEGER: f64 = (-((1i64 << (f64::MANTISSA_DIGITS)) - 1)) as f64;
 
 macro_rules! impl_int {
 	($($ty:ty)*) => {$(
modifiedcrates/jrsonnet-evaluator/src/val.rsdiffbeforeafterboth
--- a/crates/jrsonnet-evaluator/src/val.rs
+++ b/crates/jrsonnet-evaluator/src/val.rs
@@ -5,7 +5,6 @@
 	marker::PhantomData,
 	mem::replace,
 	num::NonZeroU32,
-	ops::Deref,
 	rc::Rc,
 };
 
@@ -14,16 +13,15 @@
 pub use jrsonnet_macros::Thunk;
 use jrsonnet_types::ValType;
 use rustc_hash::FxHashMap;
-use thiserror::Error;
 
 pub use crate::arr::{ArrValue, ArrayLike};
 use crate::{
-	ObjValue, Result, SupThis, Unbound, WeakSupThis, bail,
+	NumValue, ObjValue, Result, SupThis, Unbound, WeakSupThis, bail,
 	error::{Error, ErrorKind::*},
 	function::FuncVal,
 	gc::WithCapacityExt as _,
 	manifest::{ManifestFormat, ToStringFormat},
-	typed::{BoundedUsize, MAX_SAFE_INTEGER, MIN_SAFE_INTEGER},
+	typed::BoundedUsize,
 };
 
 pub trait ThunkValue: Trace {
@@ -439,134 +437,6 @@
 		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)]
-#[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))
-	}
-	#[inline]
-	pub const fn get(&self) -> f64 {
-		self.0
-	}
-	pub(crate) fn truncate_for_bitwise(self) -> Result<i64> {
-		if self.0 < MIN_SAFE_INTEGER || self.0 > MAX_SAFE_INTEGER {
-			bail!("numberic value outside of safe integer range for bitwise operation");
-		}
-		#[expect(clippy::cast_possible_truncation, reason = "intended")]
-		Ok(self.0 as i64)
-	}
-}
-impl PartialEq for NumValue {
-	fn eq(&self, other: &Self) -> bool {
-		self.0 == other.0
-	}
-}
-impl Eq for NumValue {}
-impl Ord for NumValue {
-	#[inline]
-	fn cmp(&self, other: &Self) -> Ordering {
-		// Can't use `total_cmp`: its behavior for `-0` and `0`
-		// is not following wanted.
-		unsafe { self.0.partial_cmp(&other.0).unwrap_unchecked() }
-	}
-}
-impl PartialOrd for NumValue {
-	#[inline]
-	fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
-		Some(self.cmp(other))
-	}
-}
-impl Debug for NumValue {
-	fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
-		Debug::fmt(&self.0, f)
-	}
-}
-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;
-
-	#[inline]
-	fn deref(&self) -> &Self::Target {
-		&self.0
-	}
-}
-macro_rules! impl_num {
-	($($ty:ty),+) => {$(
-		impl From<$ty> for NumValue {
-			#[inline]
-			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;
-			#[inline]
-			fn try_from(value: $ty) -> Result<Self, ConvertNumValueError> {
-				#[expect(clippy::cast_precision_loss, reason = "precision loss is explicitly handled")]
-				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;
-
-	#[inline]
-	fn try_from(value: f64) -> Result<Self, Self::Error> {
-		Self::new(value).ok_or(ConvertNumValueError::NonFinite)
-	}
-}
-impl TryFrom<f32> for NumValue {
-	type Error = ConvertNumValueError;
-
-	#[inline]
-	fn try_from(value: f32) -> Result<Self, Self::Error> {
-		Self::new(f64::from(value)).ok_or(ConvertNumValueError::NonFinite)
 	}
 }
 
modifiedcrates/jrsonnet-ir-parser/src/lib.rsdiffbeforeafterboth
--- a/crates/jrsonnet-ir-parser/src/lib.rs
+++ b/crates/jrsonnet-ir-parser/src/lib.rs
@@ -4,8 +4,8 @@
 use jrsonnet_ir::{
 	ArgsDesc, AssertExpr, AssertStmt, BinaryOp, BinaryOpType, BindSpec, CompSpec, Destruct, Expr,
 	ExprParam, ExprParams, FieldMember, FieldName, ForSpecData, IStr, IfElse, IfSpecData,
-	ImportKind, IndexPart, LiteralType, Member, ObjBody, ObjComp, ObjMembers, Slice, SliceDesc,
-	Source, Span, Spanned, UnaryOpType, Visibility, unescape,
+	ImportKind, IndexPart, LiteralType, Member, NumValue, ObjBody, ObjComp, ObjMembers, Slice,
+	SliceDesc, Source, Span, Spanned, UnaryOpType, Visibility, unescape,
 };
 use jrsonnet_lexer::{Lexeme, Lexer, Span as LexSpan, SyntaxKind, T, collect_lexed_str_block};
 
@@ -202,17 +202,21 @@
 	)
 }
 
-fn parse_number(p: &mut Parser<'_>) -> Result<f64> {
+fn parse_number(p: &mut Parser<'_>) -> Result<NumValue> {
 	let text = p.text();
 	let n: f64 = text
 		.replace('_', "")
 		.parse()
 		.map_err(|_| p.error(format!("invalid number literal: {text}")))?;
-	if !n.is_finite() {
-		return Err(p.error("numbers are finite".into()));
-	}
+
+	let v = match NumValue::try_from(n) {
+		Ok(v) => v,
+		Err(e) => return Err(p.error(format!("invalid number value: {e}"))),
+	};
+
 	p.eat_any();
-	Ok(n)
+
+	Ok(v)
 }
 
 fn ident(p: &mut Parser<'_>) -> Result<IStr> {
modifiedcrates/jrsonnet-ir/Cargo.tomldiffbeforeafterboth
--- a/crates/jrsonnet-ir/Cargo.toml
+++ b/crates/jrsonnet-ir/Cargo.toml
@@ -19,6 +19,7 @@
 static_assertions.workspace = true
 
 peg.workspace = true
+thiserror.workspace = true
 
 [dev-dependencies]
 insta.workspace = true
modifiedcrates/jrsonnet-ir/src/expr.rsdiffbeforeafterboth
--- a/crates/jrsonnet-ir/src/expr.rs
+++ b/crates/jrsonnet-ir/src/expr.rs
@@ -8,6 +8,7 @@
 use jrsonnet_interner::IStr;
 
 use crate::{
+	NumValue,
 	function::{FunctionSignature, ParamDefault, ParamName, ParamParse},
 	source::Source,
 };
@@ -398,7 +399,7 @@
 	/// String value: "hello"
 	Str(IStr),
 	/// Number: 1, 2.0, 2e+20
-	Num(f64),
+	Num(NumValue),
 	/// Variable name: test
 	Var(Spanned<IStr>),
 
modifiedcrates/jrsonnet-ir/src/lib.rsdiffbeforeafterboth
--- a/crates/jrsonnet-ir/src/lib.rs
+++ b/crates/jrsonnet-ir/src/lib.rs
@@ -1,7 +1,10 @@
 #![allow(clippy::redundant_closure_call, clippy::derive_partial_eq_without_eq)]
 
 mod expr;
+use std::{cmp::Ordering, fmt, ops::Deref};
+
 pub use expr::*;
+use jrsonnet_gcmodule::Acyclic;
 pub use jrsonnet_interner::IStr;
 pub mod function;
 mod location;
@@ -14,3 +17,134 @@
 	Source, SourceDefaultIgnoreJpath, SourceDirectory, SourceFifo, SourceFile, SourcePath,
 	SourcePathT, SourceVirtual,
 };
+
+// It seels to be a wrong place for this kind of stuff, but as it would also be used for static analysis and
+// is already wanted for NumValue, I don't know a better place.
+#[expect(clippy::cast_precision_loss, reason = "checked to not overflow")]
+pub const MAX_SAFE_INTEGER: f64 = ((1u64 << (f64::MANTISSA_DIGITS)) - 1) as f64;
+#[expect(clippy::cast_precision_loss, reason = "checked to not overflow")]
+pub const MIN_SAFE_INTEGER: f64 = (-((1i64 << (f64::MANTISSA_DIGITS)) - 1)) as f64;
+
+/// Represents jsonnet number
+/// Jsonnet numbers are finite f64, with NaNs disallowed
+#[derive(Acyclic, Clone, Copy)]
+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))
+	}
+	#[inline]
+	pub const fn get(&self) -> f64 {
+		self.0
+	}
+	pub fn truncate_for_bitwise(self) -> Result<i64, ConvertNumValueError> {
+		if self.0 < MIN_SAFE_INTEGER || self.0 > MAX_SAFE_INTEGER {
+			return Err(ConvertNumValueError::BitwiseSafeRange);
+		}
+		#[expect(clippy::cast_possible_truncation, reason = "intended")]
+		Ok(self.0 as i64)
+	}
+}
+impl PartialEq for NumValue {
+	fn eq(&self, other: &Self) -> bool {
+		self.0 == other.0
+	}
+}
+impl Eq for NumValue {}
+impl Ord for NumValue {
+	#[inline]
+	fn cmp(&self, other: &Self) -> Ordering {
+		// Can't use `total_cmp`: its behavior for `-0` and `0`
+		// is not following wanted.
+		unsafe { self.0.partial_cmp(&other.0).unwrap_unchecked() }
+	}
+}
+impl PartialOrd for NumValue {
+	#[inline]
+	fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
+		Some(self.cmp(other))
+	}
+}
+impl fmt::Debug for NumValue {
+	fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
+		fmt::Debug::fmt(&self.0, f)
+	}
+}
+impl fmt::Display for NumValue {
+	fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
+		fmt::Display::fmt(&self.0, f)
+	}
+}
+impl Deref for NumValue {
+	type Target = f64;
+
+	#[inline]
+	fn deref(&self) -> &Self::Target {
+		&self.0
+	}
+}
+macro_rules! impl_num {
+	($($ty:ty),+) => {$(
+		impl From<$ty> for NumValue {
+			#[inline]
+			fn from(value: $ty) -> Self {
+				Self(value.into())
+			}
+		}
+	)+};
+}
+impl_num!(i8, u8, i16, u16, i32, u32);
+
+#[derive(Clone, Copy, Debug, thiserror::Error, Acyclic)]
+pub enum ConvertNumValueError {
+	#[error("overflow")]
+	Overflow,
+	#[error("underflow")]
+	Underflow,
+	#[error("non-finite")]
+	NonFinite,
+	#[error("float out of safe int range")]
+	BitwiseSafeRange,
+}
+
+macro_rules! impl_try_num {
+	($($ty:ty),+) => {$(
+		impl TryFrom<$ty> for NumValue {
+			type Error = ConvertNumValueError;
+			#[inline]
+			fn try_from(value: $ty) -> Result<Self, ConvertNumValueError> {
+				#[expect(clippy::cast_precision_loss, reason = "precision loss is explicitly handled")]
+				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;
+
+	#[inline]
+	fn try_from(value: f64) -> Result<Self, Self::Error> {
+		Self::new(value).ok_or(ConvertNumValueError::NonFinite)
+	}
+}
+impl TryFrom<f32> for NumValue {
+	type Error = ConvertNumValueError;
+
+	#[inline]
+	fn try_from(value: f32) -> Result<Self, Self::Error> {
+		Self::new(f64::from(value)).ok_or(ConvertNumValueError::NonFinite)
+	}
+}
modifiedcrates/jrsonnet-peg-parser/src/lib.rsdiffbeforeafterboth
--- a/crates/jrsonnet-peg-parser/src/lib.rs
+++ b/crates/jrsonnet-peg-parser/src/lib.rs
@@ -4,8 +4,8 @@
 use jrsonnet_ir::{
 	ArgsDesc, AssertExpr, AssertStmt, BinaryOp, BindSpec, CompSpec, Destruct, DestructRest, Expr,
 	ExprParam, ExprParams, FieldMember, FieldName, ForSpecData, IStr, IfElse, IfSpecData,
-	ImportKind, IndexPart, LiteralType, Member, ObjBody, ObjComp, ObjMembers, Slice, SliceDesc,
-	Source, Span, Spanned, Visibility, unescape,
+	ImportKind, IndexPart, LiteralType, Member, NumValue, ObjBody, ObjComp, ObjMembers, Slice,
+	SliceDesc, Source, Span, Spanned, Visibility, unescape,
 };
 use peg::parser;
 
@@ -52,7 +52,7 @@
 		/// Sequence of digits
 		rule uint_str() -> &'input str = a:$(digit()+ ("_" digit()+)*) { a }
 		/// Number in scientific notation format
-		rule number() -> f64 = quiet!{a:$(uint_str() ("." uint_str())? (['e'|'E'] (s:['+'|'-'])? uint_str())?) {? a.replace("_","").parse().map_err(|_| "<number>") }} / expected!("<number>")
+		rule number() -> f64 = quiet!{a:$(uint_str() ("." uint_str())? (['e'|'E'] (s:['+'|'-'])? uint_str())?) {? a.replace('_',"").parse().map_err(|_| "<number>") }} / expected!("<number>")
 
 		/// Reserved word followed by any non-alphanumberic
 		rule reserved() = ("assert" / "else" / "error" / "false" / "for" / "function" / "if" / "import" / "importstr" / "importbin" / "in" / "local" / "null" / "tailstrict" / "then" / "self" / "super" / "true") end_of_ident()
@@ -267,7 +267,7 @@
 				Expr::ArrComp(Rc::new(expr), specs)
 			}
 		pub rule number_expr(s: &ParserSettings) -> Expr
-			= n:number() {? if n.is_finite() {
+			= n:number() {? if let Some(n) = NumValue::new(n) {
 				Ok(Expr::Num(n))
 			} else {
 				Err("!!!numbers are finite")
modifiedcrates/jrsonnet-stdlib/src/lib.rsdiffbeforeafterboth
before · crates/jrsonnet-stdlib/src/lib.rs
1#![allow(clippy::similar_names)]23use std::{4	cell::{Ref, RefCell, RefMut},5	collections::HashMap,6	f64,7	rc::Rc,8};910pub use arrays::*;11pub use compat::*;12pub use encoding::*;13pub use hash::*;14use jrsonnet_evaluator::{15	ContextBuilder, IStr, ObjValue, ObjValueBuilder, Thunk, Val,16	error::Result,17	function::{CallLocation, FuncVal, builtin_id},18	tla::TlaArg,19	trace::PathResolver,20	typed::SerializeTypedObj as _,21	val::NumValue,22};23use jrsonnet_gcmodule::{Acyclic, Cc, Trace};24use jrsonnet_ir::Source;25use jrsonnet_macros::{IntoUntyped, Typed};26pub use manifest::*;27pub use math::*;28pub use misc::*;29pub use objects::*;30pub use operator::*;31pub use parse::*;32pub use sets::*;33pub use sort::*;34pub use strings::*;35pub use types::*;3637#[cfg(feature = "exp-regex")]38pub use crate::regex::*;3940mod arrays;41mod compat;42mod encoding;43mod hash;44mod keyf;45mod manifest;46mod math;47mod misc;48mod objects;49mod operator;50mod parse;51#[cfg(feature = "exp-regex")]52mod regex;53mod sets;54mod sort;55mod strings;56mod types;5758#[derive(Typed, IntoUntyped, Default)]59#[allow(non_snake_case)]60struct Builtins {61	#[typed(method)]62	id: builtin_id,63	// Types64	#[typed(method, rename = "type")]65	r#type: builtin_type,66	#[typed(method)]67	isString: builtin_is_string,68	#[typed(method)]69	isNumber: builtin_is_number,70	#[typed(method)]71	isBoolean: builtin_is_boolean,72	#[typed(method)]73	isObject: builtin_is_object,74	#[typed(method)]75	isArray: builtin_is_array,76	#[typed(method)]77	isFunction: builtin_is_function,78	#[typed(method)]79	isNull: builtin_is_null,80	// Arrays81	#[typed(method)]82	makeArray: builtin_make_array,83	#[typed(method)]84	repeat: builtin_repeat,85	#[typed(method)]86	slice: builtin_slice,87	#[typed(method)]88	map: builtin_map,89	#[typed(method)]90	mapWithIndex: builtin_map_with_index,91	#[typed(method)]92	mapWithKey: builtin_map_with_key,93	#[typed(method)]94	flatMap: builtin_flatmap,95	#[typed(method)]96	filter: builtin_filter,97	#[typed(method)]98	foldl: builtin_foldl,99	#[typed(method)]100	foldr: builtin_foldr,101	#[typed(method)]102	range: builtin_range,103	#[typed(method)]104	join: builtin_join,105	#[typed(method)]106	lines: builtin_lines,107	#[typed(method)]108	resolvePath: builtin_resolve_path,109	#[typed(method)]110	deepJoin: builtin_deep_join,111	#[typed(method)]112	reverse: builtin_reverse,113	#[typed(method)]114	any: builtin_any,115	#[typed(method)]116	all: builtin_all,117	#[typed(method)]118	member: builtin_member,119	#[typed(method)]120	find: builtin_find,121	#[typed(method)]122	contains: builtin_contains,123	#[typed(method)]124	count: builtin_count,125	#[typed(method)]126	avg: builtin_avg,127	#[typed(method)]128	removeAt: builtin_remove_at,129	#[typed(method)]130	remove: builtin_remove,131	#[typed(method)]132	flattenArrays: builtin_flatten_arrays,133	#[typed(method)]134	flattenDeepArray: builtin_flatten_deep_array,135	#[typed(method)]136	prune: builtin_prune,137	#[typed(method)]138	filterMap: builtin_filter_map,139	// Math140	#[typed(method)]141	abs: builtin_abs,142	#[typed(method)]143	sign: builtin_sign,144	#[typed(method)]145	max: builtin_max,146	#[typed(method)]147	min: builtin_min,148	#[typed(method)]149	clamp: builtin_clamp,150	#[typed(method)]151	sum: builtin_sum,152	#[typed(method)]153	modulo: builtin_modulo,154	#[typed(method)]155	floor: builtin_floor,156	#[typed(method)]157	ceil: builtin_ceil,158	#[typed(method)]159	log: builtin_log,160	#[typed(method)]161	log2: builtin_log2,162	#[typed(method)]163	log10: builtin_log10,164	#[typed(method)]165	pow: builtin_pow,166	#[typed(method)]167	sqrt: builtin_sqrt,168	#[typed(method)]169	sin: builtin_sin,170	#[typed(method)]171	cos: builtin_cos,172	#[typed(method)]173	tan: builtin_tan,174	#[typed(method)]175	asin: builtin_asin,176	#[typed(method)]177	acos: builtin_acos,178	#[typed(method)]179	atan: builtin_atan,180	#[typed(method)]181	atan2: builtin_atan2,182	#[typed(method)]183	exp: builtin_exp,184	#[typed(method)]185	mantissa: builtin_mantissa,186	#[typed(method)]187	exponent: builtin_exponent,188	#[typed(method)]189	round: builtin_round,190	#[typed(method)]191	isEven: builtin_is_even,192	#[typed(method)]193	isOdd: builtin_is_odd,194	#[typed(method)]195	isInteger: builtin_is_integer,196	#[typed(method)]197	isDecimal: builtin_is_decimal,198	#[typed(method)]199	deg2rad: builtin_deg2rad,200	#[typed(method)]201	rad2deg: builtin_rad2deg,202	#[typed(method)]203	hypot: builtin_hypot,204	// Operator205	#[typed(rename = "mod", method)]206	r#mod: builtin_mod,207	#[typed(method)]208	primitiveEquals: builtin_primitive_equals,209	#[typed(method)]210	equals: builtin_equals,211	#[typed(method)]212	xor: builtin_xor,213	#[typed(method)]214	xnor: builtin_xnor,215	#[typed(method)]216	format: builtin_format,217	// Sort218	#[typed(method)]219	sort: builtin_sort,220	#[typed(method)]221	uniq: builtin_uniq,222	#[typed(method)]223	set: builtin_set,224	#[typed(method)]225	minArray: builtin_min_array,226	#[typed(method)]227	maxArray: builtin_max_array,228	// Hash229	#[typed(method)]230	md5: builtin_md5,231	#[typed(method)]232	sha1: builtin_sha1,233	#[typed(method)]234	sha256: builtin_sha256,235	#[typed(method)]236	sha512: builtin_sha512,237	#[typed(method)]238	sha3: builtin_sha3,239	// Encoding240	#[typed(method)]241	encodeUTF8: builtin_encode_utf8,242	#[typed(method)]243	decodeUTF8: builtin_decode_utf8,244	#[typed(method)]245	base64: builtin_base64,246	#[typed(method)]247	base64Decode: builtin_base64_decode,248	#[typed(method)]249	base64DecodeBytes: builtin_base64_decode_bytes,250	// Objects251	#[typed(method)]252	objectFieldsEx: builtin_object_fields_ex,253	#[typed(method)]254	objectFields: builtin_object_fields,255	#[typed(method)]256	objectFieldsAll: builtin_object_fields_all,257	#[typed(method)]258	objectValues: builtin_object_values,259	#[typed(method)]260	objectValuesAll: builtin_object_values_all,261	#[typed(method)]262	objectKeysValues: builtin_object_keys_values,263	#[typed(method)]264	objectKeysValuesAll: builtin_object_keys_values_all,265	#[typed(method)]266	objectHasEx: builtin_object_has_ex,267	#[typed(method)]268	objectHas: builtin_object_has,269	#[typed(method)]270	objectHasAll: builtin_object_has_all,271	#[typed(method)]272	objectRemoveKey: builtin_object_remove_key,273	// Manifest274	#[typed(method)]275	escapeStringJson: builtin_escape_string_json,276	#[typed(method)]277	escapeStringPython: builtin_escape_string_python,278	#[typed(method)]279	escapeStringXML: builtin_escape_string_xml,280	#[typed(method)]281	manifestJsonEx: builtin_manifest_json_ex,282	#[typed(method)]283	manifestJson: builtin_manifest_json,284	#[typed(method)]285	manifestJsonMinified: builtin_manifest_json_minified,286	#[typed(method)]287	manifestYamlDoc: builtin_manifest_yaml_doc,288	#[typed(method)]289	manifestYamlStream: builtin_manifest_yaml_stream,290	#[typed(method)]291	manifestTomlEx: builtin_manifest_toml_ex,292	#[typed(method)]293	manifestToml: builtin_manifest_toml,294	#[typed(method)]295	toString: builtin_to_string,296	#[typed(method)]297	manifestPython: builtin_manifest_python,298	#[typed(method)]299	manifestPythonVars: builtin_manifest_python_vars,300	#[typed(method)]301	manifestXmlJsonml: builtin_manifest_xml_jsonml,302	#[typed(method)]303	manifestIni: builtin_manifest_ini,304	// Parse305	#[typed(method)]306	parseJson: builtin_parse_json,307	#[typed(method)]308	parseYaml: builtin_parse_yaml,309	// Strings310	#[typed(method)]311	codepoint: builtin_codepoint,312	#[typed(method)]313	substr: builtin_substr,314	#[typed(method)]315	char: builtin_char,316	#[typed(method)]317	strReplace: builtin_str_replace,318	#[typed(method)]319	escapeStringBash: builtin_escape_string_bash,320	#[typed(method)]321	escapeStringDollars: builtin_escape_string_dollars,322	#[typed(method)]323	isEmpty: builtin_is_empty,324	#[typed(method)]325	equalsIgnoreCase: builtin_equals_ignore_case,326	#[typed(method)]327	splitLimit: builtin_splitlimit,328	#[typed(method)]329	splitLimitR: builtin_splitlimitr,330	#[typed(method)]331	split: builtin_split,332	#[typed(method)]333	asciiUpper: builtin_ascii_upper,334	#[typed(method)]335	asciiLower: builtin_ascii_lower,336	#[typed(method)]337	findSubstr: builtin_find_substr,338	#[typed(method)]339	parseInt: builtin_parse_int,340	#[cfg(feature = "exp-bigint")]341	#[typed(method)]342	bigint: builtin_bigint,343	#[typed(method)]344	parseOctal: builtin_parse_octal,345	#[typed(method)]346	parseHex: builtin_parse_hex,347	#[typed(method)]348	stringChars: builtin_string_chars,349	#[typed(method)]350	lstripChars: builtin_lstrip_chars,351	#[typed(method)]352	rstripChars: builtin_rstrip_chars,353	#[typed(method)]354	stripChars: builtin_strip_chars,355	#[typed(method)]356	trim: builtin_trim,357	// Misc358	#[typed(method)]359	length: builtin_length,360	#[typed(method)]361	get: builtin_get,362	#[typed(method)]363	startsWith: builtin_starts_with,364	#[typed(method)]365	endsWith: builtin_ends_with,366	#[typed(method)]367	assertEqual: builtin_assert_equal,368	#[typed(method)]369	mergePatch: builtin_merge_patch,370	// Sets371	#[typed(method)]372	setMember: builtin_set_member,373	#[typed(method)]374	setInter: builtin_set_inter,375	#[typed(method)]376	setDiff: builtin_set_diff,377	#[typed(method)]378	setUnion: builtin_set_union,379	// Regex380	#[cfg(feature = "exp-regex")]381	#[typed(method)]382	regexQuoteMeta: builtin_regex_quote_meta,383	// Compat384	#[typed(method)]385	__compare: builtin___compare,386	#[typed(method)]387	__compare_array: builtin___compare_array,388	#[typed(method)]389	__array_less: builtin___array_less,390	#[typed(method)]391	__array_greater: builtin___array_greater,392	#[typed(method)]393	__array_less_or_equal: builtin___array_less_or_equal,394	#[typed(method)]395	__array_greater_or_equal: builtin___array_greater_or_equal,396}397398#[allow(clippy::too_many_lines)]399pub fn stdlib_uncached(settings: Cc<RefCell<Settings>>) -> ObjValue {400	let mut builder = ObjValueBuilder::new();401402	let builtins = Builtins::default();403	builtins.serialize(&mut builder).expect("no conflicts");404405	builder.method(406		"extVar",407		builtin_ext_var {408			settings: settings.clone(),409		},410	);411	builder.method(412		"native",413		builtin_native {414			settings: settings.clone(),415		},416	);417	builder.method("trace", builtin_trace { settings });418419	builder.field("pi").hide().value(Val::Num(420		NumValue::new(f64::consts::PI).expect("pi is finite"),421	));422423	#[cfg(feature = "exp-regex")]424	{425		// Regex426		let regex_cache = RegexCache::default();427		builder.method(428			"regexFullMatch",429			builtin_regex_full_match {430				cache: regex_cache.clone(),431			},432		);433		builder.method(434			"regexPartialMatch",435			builtin_regex_partial_match {436				cache: regex_cache.clone(),437			},438		);439		builder.method(440			"regexReplace",441			builtin_regex_replace {442				cache: regex_cache.clone(),443			},444		);445		builder.method(446			"regexGlobalReplace",447			builtin_regex_global_replace { cache: regex_cache },448		);449	};450451	builder.build()452}453454pub trait TracePrinter: Acyclic {455	fn print_trace(&self, loc: CallLocation, value: IStr);456}457458#[derive(Acyclic)]459pub struct StdTracePrinter {460	resolver: PathResolver,461}462impl StdTracePrinter {463	pub fn new(resolver: PathResolver) -> Self {464		Self { resolver }465	}466}467impl TracePrinter for StdTracePrinter {468	fn print_trace(&self, loc: CallLocation, value: IStr) {469		eprint!("TRACE:");470		if let Some(loc) = loc.0 {471			let locs = loc.0.map_source_locations(&[loc.1]);472			eprint!(473				" {}:{}",474				loc.0.source_path().path().map_or_else(475					|| loc.0.source_path().to_string(),476					|p| self.resolver.resolve(p)477				),478				locs[0].line479			);480		}481		eprintln!(" {value}");482	}483}484485#[derive(Clone, Trace)]486pub struct Settings {487	/// Used for `std.extVar`488	pub ext_vars: HashMap<IStr, TlaArg>,489	/// Used for `std.native`490	pub ext_natives: HashMap<IStr, FuncVal>,491	/// Used for `std.trace`492	pub trace_printer: Rc<dyn TracePrinter>,493	/// Used for `std.thisFile`494	pub path_resolver: PathResolver,495}496497#[derive(Trace, Clone)]498pub struct ContextInitializer {499	/// std without applied thisFile overlay500	stdlib_obj: ObjValue,501	settings: Cc<RefCell<Settings>>,502}503impl ContextInitializer {504	pub fn new(resolver: PathResolver) -> Self {505		let settings = Settings {506			ext_vars: HashMap::new(),507			ext_natives: HashMap::new(),508			trace_printer: Rc::new(StdTracePrinter::new(resolver.clone())),509			path_resolver: resolver,510		};511		let settings = Cc::new(RefCell::new(settings));512		let stdlib_obj = stdlib_uncached(settings.clone());513		Self {514			stdlib_obj,515			settings,516		}517	}518	pub fn settings(&self) -> Ref<'_, Settings> {519		self.settings.borrow()520	}521	pub fn settings_mut(&self) -> RefMut<'_, Settings> {522		self.settings.borrow_mut()523	}524	pub fn add_ext_var(&self, name: IStr, value: Val) {525		self.settings_mut()526			.ext_vars527			.insert(name, TlaArg::Val(value));528	}529	pub fn add_ext_str(&self, name: IStr, value: IStr) {530		self.settings_mut()531			.ext_vars532			.insert(name, TlaArg::String(value));533	}534	pub fn add_ext_code(&self, name: &str, code: impl AsRef<str>) -> Result<()> {535		// self.data_mut().volatile_files.insert(source_name, code);536		self.settings_mut()537			.ext_vars538			.insert(name.into(), TlaArg::InlineCode(code.as_ref().to_owned()));539		Ok(())540	}541	pub fn add_native(&self, name: impl Into<IStr>, cb: impl Into<FuncVal>) {542		self.settings_mut()543			.ext_natives544			.insert(name.into(), cb.into());545	}546}547impl jrsonnet_evaluator::ContextInitializer for ContextInitializer {548	fn populate(&self, source: Source, builder: &mut ContextBuilder) {549		let mut std = ObjValueBuilder::new();550		std.with_super(self.stdlib_obj.clone());551		std.field("thisFile").hide().value({552			let source_path = source.source_path();553			source_path.path().map_or_else(554				|| source_path.to_string(),555				|p| self.settings().path_resolver.resolve(p),556			)557		});558		let stdlib_with_this_file = std.build();559560		builder.bind("std", Thunk::evaluated(Val::Obj(stdlib_with_this_file)));561	}562	fn as_any(&self) -> &dyn std::any::Any {563		self564	}565}
modifiedcrates/jrsonnet-stdlib/src/operator.rsdiffbeforeafterboth
--- a/crates/jrsonnet-stdlib/src/operator.rs
+++ b/crates/jrsonnet-stdlib/src/operator.rs
@@ -2,12 +2,12 @@
 //! However, in our case we instead implement them in native, and implement native functions on top of core for backwards compatibility
 
 use jrsonnet_evaluator::{
-	IStr, Result, Val,
+	IStr, NumValue, Result, Val,
 	function::builtin,
 	operator::evaluate_mod_op,
 	stdlib::std_format,
 	typed::{Either, Either2},
-	val::{NumValue, equals, primitive_equals},
+	val::{equals, primitive_equals},
 };
 
 #[builtin]