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
before · crates/jrsonnet-evaluator/src/lib.rs
1//! jsonnet interpreter implementation2#![cfg_attr(nightly, feature(thread_local, type_alias_impl_trait))]34// For jrsonnet-macros5extern crate self as jrsonnet_evaluator;67mod arr;8pub mod async_import;9mod ctx;10mod dynamic;11pub mod error;12mod evaluate;13pub mod function;14pub mod gc;15mod import;16mod integrations;17pub mod manifest;18mod obj;19pub mod stack;20pub mod stdlib;21pub mod tla;22pub mod trace;23pub mod typed;24pub mod val;2526use std::{27	any::Any,28	cell::{RefCell, RefMut},29	clone::Clone,30	collections::hash_map::Entry,31	fmt::{self, Debug},32	marker::PhantomData,33	rc::Rc,34};3536pub use ctx::*;37pub use dynamic::*;38pub use error::{Error, ErrorKind::*, Result, ResultExt};39pub use evaluate::*;40use function::CallLocation;41pub use import::*;42use jrsonnet_gcmodule::{Cc, Trace, cc_dyn};43pub use jrsonnet_interner::{IBytes, IStr};44pub use jrsonnet_ir as parser;45use jrsonnet_ir::{Expr, Source, SourcePath};46#[doc(hidden)]47pub use jrsonnet_macros;4849#[cfg(not(any(feature = "ir-parser", feature = "peg-parser")))]50compile_error!("at least one of `ir-parser` or `peg-parser` features must be enabled");5152pub use error::SyntaxError;53pub use obj::*;54pub use rustc_hash;55use rustc_hash::FxHashMap;56use stack::check_depth;57pub use tla::apply_tla;58pub use val::{Thunk, Val};5960use crate::gc::WithCapacityExt as _;6162#[allow(clippy::needless_return)]63pub(crate) fn parse_jsonnet(code: &str, source: Source) -> Result<Expr, SyntaxError> {64	#[cfg(feature = "peg-parser")]65	{66		use std::sync::LazyLock;67		static USE_LEGACY_PARSER: LazyLock<bool> =68			LazyLock::new(|| std::env::var_os("JRSONNET_LEGACY_PARSER").is_some());6970		if *USE_LEGACY_PARSER {71			return parse_peg(code, source);72		}73	}74	#[cfg(feature = "ir-parser")]75	{76		return parse_ir(code, source);77	}78	#[cfg(feature = "peg-parser")]79	{80		return parse_peg(code, source);81	}82}8384#[cfg(feature = "ir-parser")]85fn parse_ir(code: &str, source: Source) -> Result<Expr, SyntaxError> {86	jrsonnet_ir_parser::parse(code, &jrsonnet_ir_parser::ParserSettings { source }).map_err(|e| {87		SyntaxError {88			message: e.message,89			location: (e.location.0, e.location.1),90		}91	})92}9394#[cfg(feature = "peg-parser")]95fn parse_peg(code: &str, source: Source) -> Result<Expr, SyntaxError> {96	jrsonnet_peg_parser::parse(code, &jrsonnet_peg_parser::ParserSettings { source }).map_err(|e| {97		let message = e98			.expected99			.tokens()100			.find(|t| t.starts_with("!!!"))101			.map_or_else(102				|| {103					format!(104						"expected {}, got {:?}",105						e.expected,106						code.chars()107							.nth(e.location.0)108							.map_or_else(|| "EOF".into(), |c: char| c.to_string())109					)110				},111				|v| v[3..].into(),112			);113		SyntaxError {114			message,115			location: e.location,116		}117	})118}119120cc_dyn!(121	#[derive(Clone)]122	CcUnbound<V>,123	Unbound<Bound = V>124);125126/// Thunk without bound `super`/`this`127/// object inheritance may be overriden multiple times, and will be fixed only on field read128pub trait Unbound: Trace {129	/// Type of value after object context is bound130	type Bound;131	/// Create value bound to specified object context132	fn bind(&self, sup_this: SupThis) -> Result<Self::Bound>;133}134135/// Object fields may, or may not depend on `this`/`super`, this enum allows cheaper reuse of object-independent fields for native code136/// Standard jsonnet fields are always unbound137#[derive(Clone, Trace)]138pub enum MaybeUnbound {139	/// Value needs to be bound to `this`/`super`140	Unbound(CcUnbound<Val>),141	/// Value is object-independent142	Bound(Thunk<Val>),143}144145impl Debug for MaybeUnbound {146	fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {147		write!(f, "MaybeUnbound")148	}149}150impl MaybeUnbound {151	/// Attach object context to value, if required152	pub fn evaluate(&self, sup_this: SupThis) -> Result<Val> {153		match self {154			Self::Unbound(v) => v.0.bind(sup_this),155			Self::Bound(v) => Ok(v.evaluate()?),156		}157	}158}159160cc_dyn!(CcContextInitializer, ContextInitializer);161162/// During import, this trait will be called to create initial context for file.163/// It may initialize global variables, stdlib for example.164pub trait ContextInitializer {165	/// For composability: extend builder. May panic if this initialization is not supported,166	/// and the context may only be created via `initialize`.167	fn populate(&self, for_file: Source, builder: &mut ContextBuilder);168	/// Allows upcasting from abstract to concrete context initializer.169	/// jrsonnet by itself doesn't use this method, it is allowed for it to panic.170	fn as_any(&self) -> &dyn Any;171}172impl<T> ContextInitializer for &T173where174	T: ContextInitializer,175{176	fn populate(&self, for_file: Source, builder: &mut ContextBuilder) {177		(*self).populate(for_file, builder);178	}179180	fn as_any(&self) -> &dyn Any {181		(*self).as_any()182	}183}184185/// Context initializer which adds nothing.186impl ContextInitializer for () {187	fn populate(&self, _for_file: Source, _builder: &mut ContextBuilder) {}188	fn as_any(&self) -> &dyn Any {189		self190	}191}192193impl<T> ContextInitializer for Option<T>194where195	T: ContextInitializer + 'static,196{197	fn populate(&self, for_file: Source, builder: &mut ContextBuilder) {198		if let Some(ctx) = self {199			ctx.populate(for_file, builder);200		}201	}202203	fn as_any(&self) -> &dyn Any {204		self205	}206}207208macro_rules! impl_context_initializer {209	($($gen:ident)*) => {210		#[allow(non_snake_case)]211		impl<$($gen: ContextInitializer + Trace,)*> ContextInitializer for ($($gen,)*) {212			fn populate(&self, for_file: Source, builder: &mut ContextBuilder) {213				let ($($gen,)*) = self;214				$($gen.populate(for_file.clone(), builder);)*215			}216			fn as_any(&self) -> &dyn Any {217				self218			}219		}220	};221	($($cur:ident)* @ $c:ident $($rest:ident)*) => {222		impl_context_initializer!($($cur)*);223		impl_context_initializer!($($cur)* $c @ $($rest)*);224	};225	($($cur:ident)* @) => {226		impl_context_initializer!($($cur)*);227	}228}229impl_context_initializer! {230	A @ B C D E F G231}232233#[derive(Trace)]234struct FileData {235	string: Option<IStr>,236	bytes: Option<IBytes>,237	parsed: Option<Rc<Expr>>,238	evaluated: Option<Val>,239240	evaluating: bool,241}242impl FileData {243	fn new_string(data: IStr) -> Self {244		Self {245			string: Some(data),246			bytes: None,247			parsed: None,248			evaluated: None,249			evaluating: false,250		}251	}252	fn new_bytes(data: IBytes) -> Self {253		Self {254			string: None,255			bytes: Some(data),256			parsed: None,257			evaluated: None,258			evaluating: false,259		}260	}261	pub(crate) fn get_string(&mut self) -> Option<IStr> {262		if self.string.is_none() {263			self.string = Some(264				self.bytes265					.as_ref()266					.expect("either string or bytes should be set")267					.clone()268					.cast_str()?,269			);270		}271		Some(self.string.clone().expect("just set"))272	}273}274275#[derive(Trace)]276pub struct EvaluationStateInternals {277	/// Internal state278	file_cache: RefCell<FxHashMap<SourcePath, FileData>>,279	/// Context initializer, which will be used for imports and everything280	/// [`NoopContextInitializer`] is used by default, most likely you want to have `jrsonnet-stdlib`281	context_initializer: CcContextInitializer,282	/// Used to resolve file locations/contents283	import_resolver: Rc<dyn ImportResolver>,284}285286/// Maintains stack trace and import resolution287#[derive(Clone, Trace)]288pub struct State(Cc<EvaluationStateInternals>);289290thread_local! {291	pub static DEFAULT_STATE: State = State::builder().build();292	pub static STATE: RefCell<Option<State>> = const {RefCell::new(None)};293}294pub struct StateEnterGuard(PhantomData<()>);295impl Drop for StateEnterGuard {296	fn drop(&mut self) {297		STATE.with_borrow_mut(|v| *v = None);298	}299}300301pub fn with_state<V>(v: impl FnOnce(State) -> V) -> V {302	if let Some(state) = STATE.with_borrow(Clone::clone) {303		v(state)304	} else {305		let s = DEFAULT_STATE.with(Clone::clone);306		v(s)307	}308}309310impl State {311	pub fn enter(&self) -> StateEnterGuard {312		self.try_enter().expect("entered state already exists")313	}314	pub fn try_enter(&self) -> Option<StateEnterGuard> {315		STATE.with_borrow_mut(|v| {316			if v.is_none() {317				*v = Some(self.clone());318				Some(StateEnterGuard(PhantomData))319			} else {320				None321			}322		})323	}324	/// Should only be called with path retrieved from [`resolve_path`], may panic otherwise325	pub fn import_resolved_str(&self, path: SourcePath) -> Result<IStr> {326		let mut file_cache = self.file_cache();327		let mut file = file_cache.entry(path.clone());328329		let file = match file {330			Entry::Occupied(ref mut d) => d.get_mut(),331			Entry::Vacant(v) => {332				let data = self.import_resolver().load_file_contents(&path)?;333				v.insert(FileData::new_string(334					std::str::from_utf8(&data)335						.map_err(|_| ImportBadFileUtf8(path.clone()))?336						.into(),337				))338			}339		};340		Ok(file341			.get_string()342			.ok_or_else(|| ImportBadFileUtf8(path.clone()))?)343	}344	/// Should only be called with path retrieved from [`resolve_path`], may panic otherwise345	pub fn import_resolved_bin(&self, path: SourcePath) -> Result<IBytes> {346		let mut file_cache = self.file_cache();347		let mut file = file_cache.entry(path.clone());348349		let file = match file {350			Entry::Occupied(ref mut d) => d.get_mut(),351			Entry::Vacant(v) => {352				let data = self.import_resolver().load_file_contents(&path)?;353				v.insert(FileData::new_bytes(data.as_slice().into()))354			}355		};356		if let Some(str) = &file.bytes {357			return Ok(str.clone());358		}359		if file.bytes.is_none() {360			file.bytes = Some(361				file.string362					.as_ref()363					.expect("either string or bytes should be set")364					.clone()365					.cast_bytes(),366			);367		}368		Ok(file.bytes.as_ref().expect("just set").clone())369	}370	/// Should only be called with path retrieved from [`resolve_path`], may panic otherwise371	pub fn import_resolved(&self, path: SourcePath) -> Result<Val> {372		let mut file_cache = self.file_cache();373		let mut file = file_cache.entry(path.clone());374375		let file = match file {376			Entry::Occupied(ref mut d) => d.get_mut(),377			Entry::Vacant(v) => {378				let data = self.import_resolver().load_file_contents(&path)?;379				v.insert(FileData::new_string(380					std::str::from_utf8(&data)381						.map_err(|_| ImportBadFileUtf8(path.clone()))?382						.into(),383				))384			}385		};386		if let Some(val) = &file.evaluated {387			return Ok(val.clone());388		}389		let code = file390			.get_string()391			.ok_or_else(|| ImportBadFileUtf8(path.clone()))?;392		let file_name = Source::new(path.clone(), code.clone());393		if file.parsed.is_none() {394			file.parsed = Some(395				parse_jsonnet(&code, file_name.clone())396					.map(Rc::new)397					.map_err(|e| ImportSyntaxError {398						path: file_name.clone(),399						error: Box::new(e),400					})?,401			);402		}403		let parsed = file.parsed.as_ref().expect("just set").clone();404		if file.evaluating {405			bail!(InfiniteRecursionDetected)406		}407		file.evaluating = true;408		// Dropping file cache guard here, as evaluation may use this map too409		drop(file_cache);410		let res = evaluate(self.create_default_context(file_name), &parsed);411412		let mut file_cache = self.file_cache();413		let mut file = file_cache.entry(path);414415		let Entry::Occupied(file) = &mut file else {416			unreachable!("this file was just here")417		};418		let file = file.get_mut();419		file.evaluating = false;420		match res {421			Ok(v) => {422				file.evaluated = Some(v.clone());423				Ok(v)424			}425			Err(e) => Err(e),426		}427	}428429	/// Has same semantics as `import 'path'` called from `from` file430	pub fn import_from(&self, from: &SourcePath, path: impl AsPathLike) -> Result<Val> {431		let resolved = self.resolve_from(from, &path)?;432		self.import_resolved(resolved)433	}434	pub fn import(&self, path: impl AsPathLike) -> Result<Val> {435		let resolved = self.resolve_from_default(&path)?;436		self.import_resolved(resolved)437	}438439	/// Creates context with all passed global variables440	pub fn create_default_context(&self, source: Source) -> Context {441		self.create_default_context_with(source, &())442	}443444	/// Creates context with all passed global variables, calling custom modifier445	pub fn create_default_context_with(446		&self,447		source: Source,448		context_initializer: &dyn ContextInitializer,449	) -> Context {450		let default_initializer = self.context_initializer();451		let mut builder = ContextBuilder::new();452		default_initializer.populate(source.clone(), &mut builder);453		context_initializer.populate(source, &mut builder);454455		builder.build()456	}457}458459/// Internals460impl State {461	fn file_cache(&self) -> RefMut<'_, FxHashMap<SourcePath, FileData>> {462		self.0.file_cache.borrow_mut()463	}464}465/// Executes code creating a new stack frame, to be replaced with try{}466pub fn in_frame<T>(467	e: CallLocation<'_>,468	frame_desc: impl FnOnce() -> String,469	f: impl FnOnce() -> Result<T>,470) -> Result<T> {471	let _guard = check_depth()?;472473	f().with_description_src(e, frame_desc)474}475476/// Executes code creating a new stack frame, to be replaced with try{}477pub fn in_description_frame<T>(478	frame_desc: impl FnOnce() -> String,479	f: impl FnOnce() -> Result<T>,480) -> Result<T> {481	let _guard = check_depth()?;482483	f().with_description(frame_desc)484}485486#[derive(Trace)]487pub struct InitialUnderscore(pub Thunk<Val>);488impl ContextInitializer for InitialUnderscore {489	fn populate(&self, _for_file: Source, builder: &mut ContextBuilder) {490		builder.bind("_", self.0.clone());491	}492493	fn as_any(&self) -> &dyn Any {494		self495	}496}497498/// Raw methods evaluate passed values but don't perform TLA execution499impl State {500	/// Parses and evaluates the given snippet501	pub fn evaluate_snippet(&self, name: impl Into<IStr>, code: impl Into<IStr>) -> Result<Val> {502		self.evaluate_snippet_with(name, code, &())503	}504	/// Parses and evaluates the given snippet with custom context modifier505	pub fn evaluate_snippet_with(506		&self,507		name: impl Into<IStr>,508		code: impl Into<IStr>,509		context_initializer: &dyn ContextInitializer,510	) -> Result<Val> {511		let code = code.into();512		let source = Source::new_virtual(name.into(), code.clone());513		let parsed = parse_jsonnet(&code, source.clone()).map_err(|e| ImportSyntaxError {514			path: source.clone(),515			error: Box::new(e),516		})?;517		evaluate(518			self.create_default_context_with(source, context_initializer),519			&parsed,520		)521	}522}523524/// Settings utilities525impl State {526	// Only panics in case of [`ImportResolver`] contract violation527	#[allow(clippy::missing_panics_doc)]528	pub fn resolve_from(&self, from: &SourcePath, path: &dyn AsPathLike) -> Result<SourcePath> {529		self.import_resolver().resolve_from(from, path)530	}531	#[allow(clippy::missing_panics_doc)]532	pub fn resolve_from_default(&self, path: &dyn AsPathLike) -> Result<SourcePath> {533		self.import_resolver().resolve_from_default(path)534	}535	pub fn import_resolver(&self) -> &dyn ImportResolver {536		&*self.0.import_resolver537	}538	pub fn context_initializer(&self) -> &dyn ContextInitializer {539		&*self.0.context_initializer.0540	}541}542543impl State {544	pub fn builder() -> StateBuilder {545		StateBuilder::default()546	}547}548549impl Default for State {550	fn default() -> Self {551		Self::builder().build()552	}553}554555#[derive(Default)]556pub struct StateBuilder {557	import_resolver: Option<Rc<dyn ImportResolver>>,558	context_initializer: Option<CcContextInitializer>,559}560impl StateBuilder {561	pub fn import_resolver(&mut self, import_resolver: impl ImportResolver) -> &mut Self {562		let _ = self.import_resolver.insert(Rc::new(import_resolver));563		self564	}565	pub fn context_initializer(566		&mut self,567		context_initializer: impl ContextInitializer + Trace,568	) -> &mut Self {569		let _ = self570			.context_initializer571			.insert(CcContextInitializer::new(context_initializer));572		self573	}574	pub fn build(mut self) -> State {575		State(Cc::new(EvaluationStateInternals {576			file_cache: RefCell::new(FxHashMap::new()),577			context_initializer: self578				.context_initializer579				.take()580				.unwrap_or_else(|| CcContextInitializer::new(())),581			import_resolver: self582				.import_resolver583				.take()584				.unwrap_or_else(|| Rc::new(DummyImportResolver)),585		}))586	}587}
after · crates/jrsonnet-evaluator/src/lib.rs
1//! jsonnet interpreter implementation2#![cfg_attr(nightly, feature(thread_local, type_alias_impl_trait))]34// For jrsonnet-macros5extern crate self as jrsonnet_evaluator;67mod arr;8pub mod async_import;9mod ctx;10mod dynamic;11pub mod error;12mod evaluate;13pub mod function;14pub mod gc;15mod import;16mod integrations;17pub mod manifest;18mod obj;19pub mod stack;20pub mod stdlib;21pub mod tla;22pub mod trace;23pub mod typed;24pub mod val;2526use std::{27	any::Any,28	cell::{RefCell, RefMut},29	clone::Clone,30	collections::hash_map::Entry,31	fmt::{self, Debug},32	marker::PhantomData,33	rc::Rc,34};3536pub use ctx::*;37pub use dynamic::*;38pub use error::{Error, ErrorKind::*, Result, ResultExt};39pub use evaluate::*;40use function::CallLocation;41pub use import::*;42use jrsonnet_gcmodule::{Cc, Trace, cc_dyn};43pub use jrsonnet_interner::{IBytes, IStr};44pub use jrsonnet_ir as parser;45pub use jrsonnet_ir::NumValue;46use jrsonnet_ir::{Expr, Source, SourcePath};47#[doc(hidden)]48pub use jrsonnet_macros;4950#[cfg(not(any(feature = "ir-parser", feature = "peg-parser")))]51compile_error!("at least one of `ir-parser` or `peg-parser` features must be enabled");5253pub use error::SyntaxError;54pub use obj::*;55pub use rustc_hash;56use rustc_hash::FxHashMap;57use stack::check_depth;58pub use tla::apply_tla;59pub use val::{Thunk, Val};6061use crate::gc::WithCapacityExt as _;6263#[allow(clippy::needless_return)]64pub(crate) fn parse_jsonnet(code: &str, source: Source) -> Result<Expr, SyntaxError> {65	#[cfg(feature = "peg-parser")]66	{67		use std::sync::LazyLock;68		static USE_LEGACY_PARSER: LazyLock<bool> =69			LazyLock::new(|| std::env::var_os("JRSONNET_LEGACY_PARSER").is_some());7071		if *USE_LEGACY_PARSER {72			return parse_peg(code, source);73		}74	}75	#[cfg(feature = "ir-parser")]76	{77		return parse_ir(code, source);78	}79	#[cfg(feature = "peg-parser")]80	{81		return parse_peg(code, source);82	}83}8485#[cfg(feature = "ir-parser")]86fn parse_ir(code: &str, source: Source) -> Result<Expr, SyntaxError> {87	jrsonnet_ir_parser::parse(code, &jrsonnet_ir_parser::ParserSettings { source }).map_err(|e| {88		SyntaxError {89			message: e.message,90			location: (e.location.0, e.location.1),91		}92	})93}9495#[cfg(feature = "peg-parser")]96fn parse_peg(code: &str, source: Source) -> Result<Expr, SyntaxError> {97	jrsonnet_peg_parser::parse(code, &jrsonnet_peg_parser::ParserSettings { source }).map_err(|e| {98		let message = e99			.expected100			.tokens()101			.find(|t| t.starts_with("!!!"))102			.map_or_else(103				|| {104					format!(105						"expected {}, got {:?}",106						e.expected,107						code.chars()108							.nth(e.location.0)109							.map_or_else(|| "EOF".into(), |c: char| c.to_string())110					)111				},112				|v| v[3..].into(),113			);114		SyntaxError {115			message,116			location: e.location,117		}118	})119}120121cc_dyn!(122	#[derive(Clone)]123	CcUnbound<V>,124	Unbound<Bound = V>125);126127/// Thunk without bound `super`/`this`128/// object inheritance may be overriden multiple times, and will be fixed only on field read129pub trait Unbound: Trace {130	/// Type of value after object context is bound131	type Bound;132	/// Create value bound to specified object context133	fn bind(&self, sup_this: SupThis) -> Result<Self::Bound>;134}135136/// Object fields may, or may not depend on `this`/`super`, this enum allows cheaper reuse of object-independent fields for native code137/// Standard jsonnet fields are always unbound138#[derive(Clone, Trace)]139pub enum MaybeUnbound {140	/// Value needs to be bound to `this`/`super`141	Unbound(CcUnbound<Val>),142	/// Value is object-independent143	Bound(Thunk<Val>),144}145146impl Debug for MaybeUnbound {147	fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {148		write!(f, "MaybeUnbound")149	}150}151impl MaybeUnbound {152	/// Attach object context to value, if required153	pub fn evaluate(&self, sup_this: SupThis) -> Result<Val> {154		match self {155			Self::Unbound(v) => v.0.bind(sup_this),156			Self::Bound(v) => Ok(v.evaluate()?),157		}158	}159}160161cc_dyn!(CcContextInitializer, ContextInitializer);162163/// During import, this trait will be called to create initial context for file.164/// It may initialize global variables, stdlib for example.165pub trait ContextInitializer {166	/// For composability: extend builder. May panic if this initialization is not supported,167	/// and the context may only be created via `initialize`.168	fn populate(&self, for_file: Source, builder: &mut ContextBuilder);169	/// Allows upcasting from abstract to concrete context initializer.170	/// jrsonnet by itself doesn't use this method, it is allowed for it to panic.171	fn as_any(&self) -> &dyn Any;172}173impl<T> ContextInitializer for &T174where175	T: ContextInitializer,176{177	fn populate(&self, for_file: Source, builder: &mut ContextBuilder) {178		(*self).populate(for_file, builder);179	}180181	fn as_any(&self) -> &dyn Any {182		(*self).as_any()183	}184}185186/// Context initializer which adds nothing.187impl ContextInitializer for () {188	fn populate(&self, _for_file: Source, _builder: &mut ContextBuilder) {}189	fn as_any(&self) -> &dyn Any {190		self191	}192}193194impl<T> ContextInitializer for Option<T>195where196	T: ContextInitializer + 'static,197{198	fn populate(&self, for_file: Source, builder: &mut ContextBuilder) {199		if let Some(ctx) = self {200			ctx.populate(for_file, builder);201		}202	}203204	fn as_any(&self) -> &dyn Any {205		self206	}207}208209macro_rules! impl_context_initializer {210	($($gen:ident)*) => {211		#[allow(non_snake_case)]212		impl<$($gen: ContextInitializer + Trace,)*> ContextInitializer for ($($gen,)*) {213			fn populate(&self, for_file: Source, builder: &mut ContextBuilder) {214				let ($($gen,)*) = self;215				$($gen.populate(for_file.clone(), builder);)*216			}217			fn as_any(&self) -> &dyn Any {218				self219			}220		}221	};222	($($cur:ident)* @ $c:ident $($rest:ident)*) => {223		impl_context_initializer!($($cur)*);224		impl_context_initializer!($($cur)* $c @ $($rest)*);225	};226	($($cur:ident)* @) => {227		impl_context_initializer!($($cur)*);228	}229}230impl_context_initializer! {231	A @ B C D E F G232}233234#[derive(Trace)]235struct FileData {236	string: Option<IStr>,237	bytes: Option<IBytes>,238	parsed: Option<Rc<Expr>>,239	evaluated: Option<Val>,240241	evaluating: bool,242}243impl FileData {244	fn new_string(data: IStr) -> Self {245		Self {246			string: Some(data),247			bytes: None,248			parsed: None,249			evaluated: None,250			evaluating: false,251		}252	}253	fn new_bytes(data: IBytes) -> Self {254		Self {255			string: None,256			bytes: Some(data),257			parsed: None,258			evaluated: None,259			evaluating: false,260		}261	}262	pub(crate) fn get_string(&mut self) -> Option<IStr> {263		if self.string.is_none() {264			self.string = Some(265				self.bytes266					.as_ref()267					.expect("either string or bytes should be set")268					.clone()269					.cast_str()?,270			);271		}272		Some(self.string.clone().expect("just set"))273	}274}275276#[derive(Trace)]277pub struct EvaluationStateInternals {278	/// Internal state279	file_cache: RefCell<FxHashMap<SourcePath, FileData>>,280	/// Context initializer, which will be used for imports and everything281	/// [`NoopContextInitializer`] is used by default, most likely you want to have `jrsonnet-stdlib`282	context_initializer: CcContextInitializer,283	/// Used to resolve file locations/contents284	import_resolver: Rc<dyn ImportResolver>,285}286287/// Maintains stack trace and import resolution288#[derive(Clone, Trace)]289pub struct State(Cc<EvaluationStateInternals>);290291thread_local! {292	pub static DEFAULT_STATE: State = State::builder().build();293	pub static STATE: RefCell<Option<State>> = const {RefCell::new(None)};294}295pub struct StateEnterGuard(PhantomData<()>);296impl Drop for StateEnterGuard {297	fn drop(&mut self) {298		STATE.with_borrow_mut(|v| *v = None);299	}300}301302pub fn with_state<V>(v: impl FnOnce(State) -> V) -> V {303	if let Some(state) = STATE.with_borrow(Clone::clone) {304		v(state)305	} else {306		let s = DEFAULT_STATE.with(Clone::clone);307		v(s)308	}309}310311impl State {312	pub fn enter(&self) -> StateEnterGuard {313		self.try_enter().expect("entered state already exists")314	}315	pub fn try_enter(&self) -> Option<StateEnterGuard> {316		STATE.with_borrow_mut(|v| {317			if v.is_none() {318				*v = Some(self.clone());319				Some(StateEnterGuard(PhantomData))320			} else {321				None322			}323		})324	}325	/// Should only be called with path retrieved from [`resolve_path`], may panic otherwise326	pub fn import_resolved_str(&self, path: SourcePath) -> Result<IStr> {327		let mut file_cache = self.file_cache();328		let mut file = file_cache.entry(path.clone());329330		let file = match file {331			Entry::Occupied(ref mut d) => d.get_mut(),332			Entry::Vacant(v) => {333				let data = self.import_resolver().load_file_contents(&path)?;334				v.insert(FileData::new_string(335					std::str::from_utf8(&data)336						.map_err(|_| ImportBadFileUtf8(path.clone()))?337						.into(),338				))339			}340		};341		Ok(file342			.get_string()343			.ok_or_else(|| ImportBadFileUtf8(path.clone()))?)344	}345	/// Should only be called with path retrieved from [`resolve_path`], may panic otherwise346	pub fn import_resolved_bin(&self, path: SourcePath) -> Result<IBytes> {347		let mut file_cache = self.file_cache();348		let mut file = file_cache.entry(path.clone());349350		let file = match file {351			Entry::Occupied(ref mut d) => d.get_mut(),352			Entry::Vacant(v) => {353				let data = self.import_resolver().load_file_contents(&path)?;354				v.insert(FileData::new_bytes(data.as_slice().into()))355			}356		};357		if let Some(str) = &file.bytes {358			return Ok(str.clone());359		}360		if file.bytes.is_none() {361			file.bytes = Some(362				file.string363					.as_ref()364					.expect("either string or bytes should be set")365					.clone()366					.cast_bytes(),367			);368		}369		Ok(file.bytes.as_ref().expect("just set").clone())370	}371	/// Should only be called with path retrieved from [`resolve_path`], may panic otherwise372	pub fn import_resolved(&self, path: SourcePath) -> Result<Val> {373		let mut file_cache = self.file_cache();374		let mut file = file_cache.entry(path.clone());375376		let file = match file {377			Entry::Occupied(ref mut d) => d.get_mut(),378			Entry::Vacant(v) => {379				let data = self.import_resolver().load_file_contents(&path)?;380				v.insert(FileData::new_string(381					std::str::from_utf8(&data)382						.map_err(|_| ImportBadFileUtf8(path.clone()))?383						.into(),384				))385			}386		};387		if let Some(val) = &file.evaluated {388			return Ok(val.clone());389		}390		let code = file391			.get_string()392			.ok_or_else(|| ImportBadFileUtf8(path.clone()))?;393		let file_name = Source::new(path.clone(), code.clone());394		if file.parsed.is_none() {395			file.parsed = Some(396				parse_jsonnet(&code, file_name.clone())397					.map(Rc::new)398					.map_err(|e| ImportSyntaxError {399						path: file_name.clone(),400						error: Box::new(e),401					})?,402			);403		}404		let parsed = file.parsed.as_ref().expect("just set").clone();405		if file.evaluating {406			bail!(InfiniteRecursionDetected)407		}408		file.evaluating = true;409		// Dropping file cache guard here, as evaluation may use this map too410		drop(file_cache);411		let res = evaluate(self.create_default_context(file_name), &parsed);412413		let mut file_cache = self.file_cache();414		let mut file = file_cache.entry(path);415416		let Entry::Occupied(file) = &mut file else {417			unreachable!("this file was just here")418		};419		let file = file.get_mut();420		file.evaluating = false;421		match res {422			Ok(v) => {423				file.evaluated = Some(v.clone());424				Ok(v)425			}426			Err(e) => Err(e),427		}428	}429430	/// Has same semantics as `import 'path'` called from `from` file431	pub fn import_from(&self, from: &SourcePath, path: impl AsPathLike) -> Result<Val> {432		let resolved = self.resolve_from(from, &path)?;433		self.import_resolved(resolved)434	}435	pub fn import(&self, path: impl AsPathLike) -> Result<Val> {436		let resolved = self.resolve_from_default(&path)?;437		self.import_resolved(resolved)438	}439440	/// Creates context with all passed global variables441	pub fn create_default_context(&self, source: Source) -> Context {442		self.create_default_context_with(source, &())443	}444445	/// Creates context with all passed global variables, calling custom modifier446	pub fn create_default_context_with(447		&self,448		source: Source,449		context_initializer: &dyn ContextInitializer,450	) -> Context {451		let default_initializer = self.context_initializer();452		let mut builder = ContextBuilder::new();453		default_initializer.populate(source.clone(), &mut builder);454		context_initializer.populate(source, &mut builder);455456		builder.build()457	}458}459460/// Internals461impl State {462	fn file_cache(&self) -> RefMut<'_, FxHashMap<SourcePath, FileData>> {463		self.0.file_cache.borrow_mut()464	}465}466/// Executes code creating a new stack frame, to be replaced with try{}467pub fn in_frame<T>(468	e: CallLocation<'_>,469	frame_desc: impl FnOnce() -> String,470	f: impl FnOnce() -> Result<T>,471) -> Result<T> {472	let _guard = check_depth()?;473474	f().with_description_src(e, frame_desc)475}476477/// Executes code creating a new stack frame, to be replaced with try{}478pub fn in_description_frame<T>(479	frame_desc: impl FnOnce() -> String,480	f: impl FnOnce() -> Result<T>,481) -> Result<T> {482	let _guard = check_depth()?;483484	f().with_description(frame_desc)485}486487#[derive(Trace)]488pub struct InitialUnderscore(pub Thunk<Val>);489impl ContextInitializer for InitialUnderscore {490	fn populate(&self, _for_file: Source, builder: &mut ContextBuilder) {491		builder.bind("_", self.0.clone());492	}493494	fn as_any(&self) -> &dyn Any {495		self496	}497}498499/// Raw methods evaluate passed values but don't perform TLA execution500impl State {501	/// Parses and evaluates the given snippet502	pub fn evaluate_snippet(&self, name: impl Into<IStr>, code: impl Into<IStr>) -> Result<Val> {503		self.evaluate_snippet_with(name, code, &())504	}505	/// Parses and evaluates the given snippet with custom context modifier506	pub fn evaluate_snippet_with(507		&self,508		name: impl Into<IStr>,509		code: impl Into<IStr>,510		context_initializer: &dyn ContextInitializer,511	) -> Result<Val> {512		let code = code.into();513		let source = Source::new_virtual(name.into(), code.clone());514		let parsed = parse_jsonnet(&code, source.clone()).map_err(|e| ImportSyntaxError {515			path: source.clone(),516			error: Box::new(e),517		})?;518		evaluate(519			self.create_default_context_with(source, context_initializer),520			&parsed,521		)522	}523}524525/// Settings utilities526impl State {527	// Only panics in case of [`ImportResolver`] contract violation528	#[allow(clippy::missing_panics_doc)]529	pub fn resolve_from(&self, from: &SourcePath, path: &dyn AsPathLike) -> Result<SourcePath> {530		self.import_resolver().resolve_from(from, path)531	}532	#[allow(clippy::missing_panics_doc)]533	pub fn resolve_from_default(&self, path: &dyn AsPathLike) -> Result<SourcePath> {534		self.import_resolver().resolve_from_default(path)535	}536	pub fn import_resolver(&self) -> &dyn ImportResolver {537		&*self.0.import_resolver538	}539	pub fn context_initializer(&self) -> &dyn ContextInitializer {540		&*self.0.context_initializer.0541	}542}543544impl State {545	pub fn builder() -> StateBuilder {546		StateBuilder::default()547	}548}549550impl Default for State {551	fn default() -> Self {552		Self::builder().build()553	}554}555556#[derive(Default)]557pub struct StateBuilder {558	import_resolver: Option<Rc<dyn ImportResolver>>,559	context_initializer: Option<CcContextInitializer>,560}561impl StateBuilder {562	pub fn import_resolver(&mut self, import_resolver: impl ImportResolver) -> &mut Self {563		let _ = self.import_resolver.insert(Rc::new(import_resolver));564		self565	}566	pub fn context_initializer(567		&mut self,568		context_initializer: impl ContextInitializer + Trace,569	) -> &mut Self {570		let _ = self571			.context_initializer572			.insert(CcContextInitializer::new(context_initializer));573		self574	}575	pub fn build(mut self) -> State {576		State(Cc::new(EvaluationStateInternals {577			file_cache: RefCell::new(FxHashMap::new()),578			context_initializer: self579				.context_initializer580				.take()581				.unwrap_or_else(|| CcContextInitializer::new(())),582			import_resolver: self583				.import_resolver584				.take()585				.unwrap_or_else(|| Rc::new(DummyImportResolver)),586		}))587	}588}
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
--- a/crates/jrsonnet-stdlib/src/lib.rs
+++ b/crates/jrsonnet-stdlib/src/lib.rs
@@ -12,13 +12,12 @@
 pub use encoding::*;
 pub use hash::*;
 use jrsonnet_evaluator::{
-	ContextBuilder, IStr, ObjValue, ObjValueBuilder, Thunk, Val,
+	ContextBuilder, IStr, NumValue, ObjValue, ObjValueBuilder, Thunk, Val,
 	error::Result,
 	function::{CallLocation, FuncVal, builtin_id},
 	tla::TlaArg,
 	trace::PathResolver,
 	typed::SerializeTypedObj as _,
-	val::NumValue,
 };
 use jrsonnet_gcmodule::{Acyclic, Cc, Trace};
 use jrsonnet_ir::Source;
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]