git.delta.rocks / jrsonnet / refs/commits / b8427047424c

difftreelog

style fix clippy warnings

lkwtpzxpYaroslav Bolyukin2026-05-07parent: #baeb367.patch.diff
in: master

30 files changed

modifiedbindings/jrsonnet-web/src/lib.rsdiffbeforeafterboth
--- a/bindings/jrsonnet-web/src/lib.rs
+++ b/bindings/jrsonnet-web/src/lib.rs
@@ -65,6 +65,11 @@
 }
 
 fn unwrap_val_ref(value: &JsValue) -> Result<<WasmVal as RefFromWasmAbi>::Anchor, JsValue> {
+	#[allow(
+		clippy::cast_sign_loss,
+		clippy::cast_possible_truncation,
+		reason = "defined to be u32"
+	)]
 	let ptr = get(value, &JsValue::from_str("__wbg_ptr"))
 		.ok()
 		.and_then(|v| v.as_f64())
@@ -371,14 +376,14 @@
 impl WasmArrValue {
 	#[wasm_bindgen(getter)]
 	pub fn length(&self) -> u32 {
-		self.arr.len()
+		self.arr.len32()
 	}
 	pub fn at(&self, index: u32) -> Result<Option<WasmVal>, JsValue> {
 		let result = self.state.as_ref().map_or_else(
-			|| self.arr.get(index),
+			|| self.arr.get32(index),
 			|state| {
 				let _guard = state.try_enter();
-				self.arr.get(index)
+				self.arr.get32(index)
 			},
 		);
 		result
modifiedbindings/jsonnet/src/lib.rsdiffbeforeafterboth
before · bindings/jsonnet/src/lib.rs
1#![allow(clippy::box_default)]23pub mod interop;45pub mod import;6pub mod native;7pub mod val_extract;8pub mod val_make;9pub mod val_modify;10pub mod vars_tlas;1112use std::{13	alloc::Layout,14	any::Any,15	borrow::Cow,16	cell::RefCell,17	ffi::{CStr, CString, OsStr},18	os::raw::{c_char, c_double, c_int, c_uint},19	path::{Path, PathBuf},20	rc::Rc,21};2223use jrsonnet_evaluator::{24	AsPathLike, FileImportResolver, IStr, ImportResolver, Result, State, Val, apply_tla, bail,25	gc::WithCapacityExt as _,26	manifest::{JsonFormat, ManifestFormat, ToStringFormat},27	rustc_hash::FxHashMap,28	stack::set_stack_depth_limit,29	tla::TlaArg,30	trace::{CompactFormat, PathResolver, TraceFormat},31};32use jrsonnet_gcmodule::Acyclic;33use jrsonnet_ir::SourcePath;34use jrsonnet_stdlib::ContextInitializer;3536/// WASM stub37#[cfg(target_arch = "wasm32")]38#[no_mangle]39pub extern "C" fn _start() {}4041/// Return the version string of the Jsonnet interpreter.42///43/// Conforms to [semantic versioning](http://semver.org/).44/// If this does not match `LIB_JSONNET_VERSION`45/// then there is a mismatch between header and compiled library.46#[unsafe(no_mangle)]47pub extern "C" fn jsonnet_version() -> &'static [u8; 8] {48	b"v0.22.0\0"49}5051unsafe fn parse_path(input: &CStr) -> Cow<'_, Path> {52	#[cfg(target_family = "unix")]53	{54		use std::os::unix::ffi::OsStrExt;55		let str = OsStr::from_bytes(input.to_bytes());56		Cow::Borrowed(Path::new(str))57	}58	#[cfg(not(target_family = "unix"))]59	{60		let string = input.to_str().expect("bad utf-8");61		Cow::Borrowed(string.as_ref())62	}63}6465unsafe fn unparse_path(input: &Path) -> CString {66	#[cfg(target_family = "unix")]67	{68		use std::os::unix::ffi::OsStrExt;69		let str = CString::new(input.as_os_str().as_bytes()).expect("input has zero byte in it");70		str71	}72	#[cfg(not(target_family = "unix"))]73	{74		let str = input.as_os_str().to_str().expect("bad utf-8");75		let cstr = CString::new(str).expect("input has NUL inside");76		cstr77	}78}7980#[derive(Acyclic)]81struct VMImportResolver {82	inner: RefCell<Rc<dyn ImportResolver>>,83}84impl VMImportResolver {85	fn new(value: impl ImportResolver) -> Self {86		Self {87			inner: RefCell::new(Rc::new(value)),88		}89	}90}91impl ImportResolver for VMImportResolver {92	fn load_file_contents(&self, resolved: &SourcePath) -> Result<Vec<u8>> {93		self.inner.borrow().load_file_contents(resolved)94	}9596	fn resolve_from(&self, from: &SourcePath, path: &dyn AsPathLike) -> Result<SourcePath> {97		self.inner.borrow().resolve_from(from, path)98	}99100	fn resolve_from_default(&self, path: &dyn AsPathLike) -> Result<SourcePath> {101		self.inner.borrow().resolve_from_default(path)102	}103}104105pub struct VM {106	state: State,107	manifest_format: Box<dyn ManifestFormat>,108	trailing_newline: bool,109	trace_format: Box<dyn TraceFormat>,110	tla_args: FxHashMap<IStr, TlaArg>,111}112impl VM {113	fn replace_import_resolver(&self, resolver: impl ImportResolver) {114		*(self.state.import_resolver() as &dyn Any)115			.downcast_ref::<VMImportResolver>()116			.expect("valid resolver ty")117			.inner118			.borrow_mut() = Rc::new(resolver);119	}120	fn add_jpath(&self, path: PathBuf) {121		let ir = self.state.import_resolver();122		let vmi = (ir as &dyn Any)123			.downcast_ref::<VMImportResolver>()124			.expect("valid resolver ty");125		let vmi = &mut *vmi.inner.borrow_mut();126		(vmi as &mut dyn Any)127			.downcast_mut::<FileImportResolver>()128			.expect("jpaths are not compatible with callback imports!")129			.add_jpath(path);130	}131}132133/// Creates a new Jsonnet virtual machine.134#[unsafe(no_mangle)]135#[allow(clippy::box_default)]136pub extern "C" fn jsonnet_make() -> *mut VM {137	let mut state = State::builder();138	state139		.import_resolver(VMImportResolver::new(FileImportResolver::default()))140		.context_initializer(ContextInitializer::new(PathResolver::new_cwd_fallback()));141	let state = state.build();142	Box::into_raw(Box::new(VM {143		state,144		manifest_format: Box::new(JsonFormat::default()),145		trace_format: Box::new(CompactFormat::default()),146		trailing_newline: true,147		tla_args: FxHashMap::new(),148	}))149}150151/// Complement of [`jsonnet_vm_make`].152#[unsafe(no_mangle)]153#[allow(clippy::boxed_local)]154pub extern "C" fn jsonnet_destroy(vm: Box<VM>) {155	drop(vm);156}157158/// Set the maximum stack depth.159#[unsafe(no_mangle)]160pub extern "C" fn jsonnet_max_stack(_vm: &VM, v: c_uint) {161	set_stack_depth_limit(v as usize);162}163164/// Set the number of objects required before a garbage collection cycle is allowed.165///166/// No-op for now167#[unsafe(no_mangle)]168pub extern "C" fn jsonnet_gc_min_objects(_vm: &VM, _v: c_uint) {}169170/// Run the garbage collector after this amount of growth in the number of objects171///172/// No-op for now173#[unsafe(no_mangle)]174pub extern "C" fn jsonnet_gc_growth_trigger(_vm: &VM, _v: c_double) {}175176/// Expect a string as output and don't JSON encode it.177#[unsafe(no_mangle)]178pub extern "C" fn jsonnet_string_output(vm: &mut VM, v: c_int) {179	vm.manifest_format = match v {180		0 => Box::new(JsonFormat::default()),181		1 => Box::new(ToStringFormat),182		_ => panic!("incorrect output format"),183	};184}185186/// Enable/disable trailing newline in manifested/string output.187#[unsafe(no_mangle)]188pub extern "C" fn jsonnet_set_trailing_newline(vm: &mut VM, enable: c_int) {189	vm.trailing_newline = enable != 0;190}191192/// Allocate, resize, or free a buffer.  This will abort if the memory cannot be allocated. It will193/// only return NULL if sz was zero.194///195/// # Safety196///197/// `buf` should be either previosly allocated by this library, or NULL198///199/// This function is most definitely broken, but it works somehow, see TODO inside200#[unsafe(no_mangle)]201pub unsafe extern "C" fn jsonnet_realloc(_vm: &VM, buf: *mut u8, sz: usize) -> *mut u8 {202	if buf.is_null() {203		if sz == 0 {204			return std::ptr::null_mut();205		}206		return unsafe {207			std::alloc::alloc(Layout::from_size_align(sz, std::mem::align_of::<u8>()).unwrap())208		};209	}210	// TODO: Somehow store size of allocation, because its real size is probally not 16 :D211	// OR (Alternative way of fixing this TODO)212	// TODO: Standard allocator uses malloc, and it doesn't uses allocation size,213	// TODO: so it should work in normal cases. Maybe force allocator for this library?214	let old_layout = Layout::from_size_align(16, std::mem::align_of::<u8>()).unwrap();215	if sz == 0 {216		unsafe { std::alloc::dealloc(buf, old_layout) };217		return std::ptr::null_mut();218	}219	unsafe { std::alloc::realloc(buf, old_layout, sz) }220}221222/// Clean up a JSON subtree.223///224/// This is useful if you want to abort with an error mid-way through building a complex value.225#[unsafe(no_mangle)]226#[allow(clippy::boxed_local)]227pub extern "C" fn jsonnet_json_destroy(_vm: &VM, v: Box<Val>) {228	drop(v);229}230231/// Set the number of lines of stack trace to display (0 for all of them).232#[unsafe(no_mangle)]233pub extern "C" fn jsonnet_max_trace(vm: &mut VM, v: c_uint) {234	if let Some(format) = vm.trace_format.as_any_mut().downcast_mut::<CompactFormat>() {235		format.max_trace = v as usize;236	} else {237		panic!("max_trace is not supported by current tracing format")238	}239}240241/// Evaluate a file containing Jsonnet code, return a JSON string.242///243/// The returned string should be cleaned up with `jsonnet_realloc`.244///245/// # Safety246///247/// `filename` should be a NUL-terminated string248#[unsafe(no_mangle)]249pub unsafe extern "C" fn jsonnet_evaluate_file(250	vm: &VM,251	filename: *const c_char,252	error: &mut c_int,253) -> *const c_char {254	let filename = unsafe { parse_path(CStr::from_ptr(filename)) };255	match vm256		.state257		.import(filename)258		.and_then(|val| apply_tla(&vm.tla_args, val))259		.and_then(|val| val.manifest(&vm.manifest_format))260	{261		Ok(v) => {262			*error = 0;263			CString::new(&*v as &str).unwrap().into_raw()264		}265		Err(e) => {266			*error = 1;267			let mut out = String::new();268			vm.trace_format.write_trace(&mut out, &e).unwrap();269			CString::new(&out as &str).unwrap().into_raw()270		}271	}272}273274/// Evaluate a string containing Jsonnet code, return a JSON string.275///276/// The returned string should be cleaned up with `jsonnet_realloc`.277///278/// # Safety279///280/// `filename`, `snippet` should be a NUL-terminated strings281#[unsafe(no_mangle)]282pub unsafe extern "C" fn jsonnet_evaluate_snippet(283	vm: &VM,284	filename: *const c_char,285	snippet: *const c_char,286	error: &mut c_int,287) -> *const c_char {288	let filename = unsafe { CStr::from_ptr(filename) };289	let snippet = unsafe { CStr::from_ptr(snippet) };290	match vm291		.state292		.evaluate_snippet(filename.to_str().unwrap(), snippet.to_str().unwrap())293		.and_then(|val| apply_tla(&vm.tla_args, val))294		.and_then(|val| val.manifest(&vm.manifest_format))295	{296		Ok(mut v) => {297			if vm.trailing_newline {298				v.push('\n');299			}300			*error = 0;301			CString::new(&*v as &str).unwrap().into_raw()302		}303		Err(e) => {304			*error = 1;305			let mut out = String::new();306			vm.trace_format.write_trace(&mut out, &e).unwrap();307			CString::new(&out as &str).unwrap().into_raw()308		}309	}310}311312fn val_to_multi(val: Val, format: &dyn ManifestFormat) -> Result<Vec<(IStr, IStr)>> {313	let Val::Obj(val) = val else {314		bail!("expected object as multi output")315	};316	let mut out = Vec::new();317	for (k, v) in val.iter(318		#[cfg(feature = "exp-preserve-order")]319		false,320	) {321		out.push((k, v?.manifest(format)?.into()));322	}323	Ok(out)324}325326fn multi_to_raw(multi: Vec<(IStr, IStr)>, trailing_newline: bool) -> *const c_char {327	let mut out = Vec::new();328	for (i, (k, v)) in multi.iter().enumerate() {329		if i != 0 {330			out.push(0);331		}332		out.extend_from_slice(k.as_bytes());333		out.push(0);334		out.extend_from_slice(v.as_bytes());335		if trailing_newline {336			out.push(b'\n');337		}338	}339	out.push(0);340	out.push(0);341	let v = out.as_ptr();342	std::mem::forget(out);343	v.cast::<c_char>()344}345346/// # Safety347#[unsafe(no_mangle)]348pub unsafe extern "C" fn jsonnet_evaluate_file_multi(349	vm: &VM,350	filename: *const c_char,351	error: &mut c_int,352) -> *const c_char {353	let filename = unsafe { parse_path(CStr::from_ptr(filename)) };354	match vm355		.state356		.import(filename)357		.and_then(|val| apply_tla(&vm.tla_args, val))358		.and_then(|val| val_to_multi(val, &vm.manifest_format))359	{360		Ok(v) => {361			*error = 0;362			multi_to_raw(v, vm.trailing_newline)363		}364		Err(e) => {365			*error = 1;366			let mut out = String::new();367			vm.trace_format.write_trace(&mut out, &e).unwrap();368			CString::new(&out as &str).unwrap().into_raw()369		}370	}371}372373/// # Safety374#[unsafe(no_mangle)]375pub unsafe extern "C" fn jsonnet_evaluate_snippet_multi(376	vm: &VM,377	filename: *const c_char,378	snippet: *const c_char,379	error: &mut c_int,380) -> *const c_char {381	let filename = unsafe { CStr::from_ptr(filename) };382	let snippet = unsafe { CStr::from_ptr(snippet) };383	match vm384		.state385		.evaluate_snippet(filename.to_str().unwrap(), snippet.to_str().unwrap())386		.and_then(|val| apply_tla(&vm.tla_args, val))387		.and_then(|val| val_to_multi(val, &vm.manifest_format))388	{389		Ok(v) => {390			*error = 0;391			multi_to_raw(v, vm.trailing_newline)392		}393		Err(e) => {394			*error = 1;395			let mut out = String::new();396			vm.trace_format.write_trace(&mut out, &e).unwrap();397			CString::new(&out as &str).unwrap().into_raw()398		}399	}400}401402fn val_to_stream(val: Val, format: &dyn ManifestFormat) -> Result<Vec<IStr>> {403	let Val::Arr(val) = val else {404		bail!("expected array as stream output")405	};406	let mut out = Vec::new();407	for item in val.iter() {408		out.push(item?.manifest(format)?.into());409	}410	Ok(out)411}412413fn stream_to_raw(multi: Vec<IStr>, trailing_newline: bool) -> *const c_char {414	let mut out = Vec::new();415	for (i, v) in multi.iter().enumerate() {416		if i != 0 {417			out.push(0);418		}419		out.extend_from_slice(v.as_bytes());420		if trailing_newline {421			out.push(b'\n');422		}423	}424	out.push(0);425	out.push(0);426	let v = out.as_ptr();427	std::mem::forget(out);428	v.cast::<c_char>()429}430431/// # Safety432#[unsafe(no_mangle)]433pub unsafe extern "C" fn jsonnet_evaluate_file_stream(434	vm: &VM,435	filename: *const c_char,436	error: &mut c_int,437) -> *const c_char {438	let filename = unsafe { parse_path(CStr::from_ptr(filename)) };439	match vm440		.state441		.import(filename)442		.and_then(|val| apply_tla(&vm.tla_args, val))443		.and_then(|val| val_to_stream(val, &vm.manifest_format))444	{445		Ok(v) => {446			*error = 0;447			stream_to_raw(v, vm.trailing_newline)448		}449		Err(e) => {450			*error = 1;451			let mut out = String::new();452			vm.trace_format.write_trace(&mut out, &e).unwrap();453			CString::new(&out as &str).unwrap().into_raw()454		}455	}456}457458/// # Safety459#[unsafe(no_mangle)]460pub unsafe extern "C" fn jsonnet_evaluate_snippet_stream(461	vm: &VM,462	filename: *const c_char,463	snippet: *const c_char,464	error: &mut c_int,465) -> *const c_char {466	let filename = unsafe { CStr::from_ptr(filename) };467	let snippet = unsafe { CStr::from_ptr(snippet) };468	match vm469		.state470		.evaluate_snippet(filename.to_str().unwrap(), snippet.to_str().unwrap())471		.and_then(|val| apply_tla(&vm.tla_args, val))472		.and_then(|val| val_to_stream(val, &vm.manifest_format))473	{474		Ok(v) => {475			*error = 0;476			stream_to_raw(v, vm.trailing_newline)477		}478		Err(e) => {479			*error = 1;480			let mut out = String::new();481			vm.trace_format.write_trace(&mut out, &e).unwrap();482			CString::new(&out as &str).unwrap().into_raw()483		}484	}485}
after · bindings/jsonnet/src/lib.rs
1#![allow(clippy::box_default)]23pub mod interop;45pub mod import;6pub mod native;7pub mod val_extract;8pub mod val_make;9pub mod val_modify;10pub mod vars_tlas;1112use std::{13	alloc::Layout,14	any::Any,15	borrow::Cow,16	cell::RefCell,17	ffi::{CStr, CString, OsStr},18	os::raw::{c_char, c_double, c_int, c_uint},19	path::{Path, PathBuf},20	rc::Rc,21};2223use jrsonnet_evaluator::{24	AsPathLike, FileImportResolver, IStr, ImportResolver, Result, State, Val, apply_tla, bail,25	gc::WithCapacityExt as _,26	manifest::{JsonFormat, ManifestFormat, ToStringFormat},27	rustc_hash::FxHashMap,28	stack::set_stack_depth_limit,29	tla::TlaArg,30	trace::{CompactFormat, PathResolver, TraceFormat},31};32use jrsonnet_gcmodule::Acyclic;33use jrsonnet_ir::SourcePath;34use jrsonnet_stdlib::ContextInitializer;3536/// WASM stub37#[cfg(target_arch = "wasm32")]38#[no_mangle]39pub extern "C" fn _start() {}4041/// Return the version string of the Jsonnet interpreter.42///43/// Conforms to [semantic versioning](http://semver.org/).44/// If this does not match `LIB_JSONNET_VERSION`45/// then there is a mismatch between header and compiled library.46#[unsafe(no_mangle)]47pub extern "C" fn jsonnet_version() -> &'static [u8; 8] {48	b"v0.22.0\0"49}5051unsafe fn parse_path(input: &CStr) -> Cow<'_, Path> {52	#[cfg(target_family = "unix")]53	{54		use std::os::unix::ffi::OsStrExt;55		let str = OsStr::from_bytes(input.to_bytes());56		Cow::Borrowed(Path::new(str))57	}58	#[cfg(not(target_family = "unix"))]59	{60		let string = input.to_str().expect("bad utf-8");61		Cow::Borrowed(string.as_ref())62	}63}6465unsafe fn unparse_path(input: &Path) -> CString {66	#[cfg(target_family = "unix")]67	{68		use std::os::unix::ffi::OsStrExt;69		CString::new(input.as_os_str().as_bytes()).expect("input has zero byte in it")70	}71	#[cfg(not(target_family = "unix"))]72	{73		let str = input.as_os_str().to_str().expect("bad utf-8");74		CString::new(str).expect("input has NUL inside")75	}76}7778#[derive(Acyclic)]79struct VMImportResolver {80	inner: RefCell<Rc<dyn ImportResolver>>,81}82impl VMImportResolver {83	fn new(value: impl ImportResolver) -> Self {84		Self {85			inner: RefCell::new(Rc::new(value)),86		}87	}88}89impl ImportResolver for VMImportResolver {90	fn load_file_contents(&self, resolved: &SourcePath) -> Result<Vec<u8>> {91		self.inner.borrow().load_file_contents(resolved)92	}9394	fn resolve_from(&self, from: &SourcePath, path: &dyn AsPathLike) -> Result<SourcePath> {95		self.inner.borrow().resolve_from(from, path)96	}9798	fn resolve_from_default(&self, path: &dyn AsPathLike) -> Result<SourcePath> {99		self.inner.borrow().resolve_from_default(path)100	}101}102103pub struct VM {104	state: State,105	manifest_format: Box<dyn ManifestFormat>,106	trailing_newline: bool,107	trace_format: Box<dyn TraceFormat>,108	tla_args: FxHashMap<IStr, TlaArg>,109}110impl VM {111	fn replace_import_resolver(&self, resolver: impl ImportResolver) {112		*(self.state.import_resolver() as &dyn Any)113			.downcast_ref::<VMImportResolver>()114			.expect("valid resolver ty")115			.inner116			.borrow_mut() = Rc::new(resolver);117	}118	fn add_jpath(&self, path: PathBuf) {119		let ir = self.state.import_resolver();120		let vmi = (ir as &dyn Any)121			.downcast_ref::<VMImportResolver>()122			.expect("valid resolver ty");123		let vmi = &mut *vmi.inner.borrow_mut();124		(vmi as &mut dyn Any)125			.downcast_mut::<FileImportResolver>()126			.expect("jpaths are not compatible with callback imports!")127			.add_jpath(path);128	}129}130131/// Creates a new Jsonnet virtual machine.132#[unsafe(no_mangle)]133#[allow(clippy::box_default)]134pub extern "C" fn jsonnet_make() -> *mut VM {135	let mut state = State::builder();136	state137		.import_resolver(VMImportResolver::new(FileImportResolver::default()))138		.context_initializer(ContextInitializer::new(PathResolver::new_cwd_fallback()));139	let state = state.build();140	Box::into_raw(Box::new(VM {141		state,142		manifest_format: Box::new(JsonFormat::default()),143		trace_format: Box::new(CompactFormat::default()),144		trailing_newline: true,145		tla_args: FxHashMap::new(),146	}))147}148149/// Complement of [`jsonnet_vm_make`].150#[unsafe(no_mangle)]151#[allow(clippy::boxed_local)]152pub extern "C" fn jsonnet_destroy(vm: Box<VM>) {153	drop(vm);154}155156/// Set the maximum stack depth.157#[unsafe(no_mangle)]158pub extern "C" fn jsonnet_max_stack(_vm: &VM, v: c_uint) {159	set_stack_depth_limit(v as usize);160}161162/// Set the number of objects required before a garbage collection cycle is allowed.163///164/// No-op for now165#[unsafe(no_mangle)]166pub extern "C" fn jsonnet_gc_min_objects(_vm: &VM, _v: c_uint) {}167168/// Run the garbage collector after this amount of growth in the number of objects169///170/// No-op for now171#[unsafe(no_mangle)]172pub extern "C" fn jsonnet_gc_growth_trigger(_vm: &VM, _v: c_double) {}173174/// Expect a string as output and don't JSON encode it.175#[unsafe(no_mangle)]176pub extern "C" fn jsonnet_string_output(vm: &mut VM, v: c_int) {177	vm.manifest_format = match v {178		0 => Box::new(JsonFormat::default()),179		1 => Box::new(ToStringFormat),180		_ => panic!("incorrect output format"),181	};182}183184/// Enable/disable trailing newline in manifested/string output.185#[unsafe(no_mangle)]186pub extern "C" fn jsonnet_set_trailing_newline(vm: &mut VM, enable: c_int) {187	vm.trailing_newline = enable != 0;188}189190/// Allocate, resize, or free a buffer.  This will abort if the memory cannot be allocated. It will191/// only return NULL if sz was zero.192///193/// # Safety194///195/// `buf` should be either previosly allocated by this library, or NULL196///197/// This function is most definitely broken, but it works somehow, see TODO inside198#[unsafe(no_mangle)]199pub unsafe extern "C" fn jsonnet_realloc(_vm: &VM, buf: *mut u8, sz: usize) -> *mut u8 {200	if buf.is_null() {201		if sz == 0 {202			return std::ptr::null_mut();203		}204		return unsafe {205			std::alloc::alloc(Layout::from_size_align(sz, std::mem::align_of::<u8>()).unwrap())206		};207	}208	// TODO: Somehow store size of allocation, because its real size is probally not 16 :D209	// OR (Alternative way of fixing this TODO)210	// TODO: Standard allocator uses malloc, and it doesn't uses allocation size,211	// TODO: so it should work in normal cases. Maybe force allocator for this library?212	let old_layout = Layout::from_size_align(16, std::mem::align_of::<u8>()).unwrap();213	if sz == 0 {214		unsafe { std::alloc::dealloc(buf, old_layout) };215		return std::ptr::null_mut();216	}217	unsafe { std::alloc::realloc(buf, old_layout, sz) }218}219220/// Clean up a JSON subtree.221///222/// This is useful if you want to abort with an error mid-way through building a complex value.223#[unsafe(no_mangle)]224#[allow(clippy::boxed_local)]225pub extern "C" fn jsonnet_json_destroy(_vm: &VM, v: Box<Val>) {226	drop(v);227}228229/// Set the number of lines of stack trace to display (0 for all of them).230#[unsafe(no_mangle)]231pub extern "C" fn jsonnet_max_trace(vm: &mut VM, v: c_uint) {232	if let Some(format) = vm.trace_format.as_any_mut().downcast_mut::<CompactFormat>() {233		format.max_trace = v as usize;234	} else {235		panic!("max_trace is not supported by current tracing format")236	}237}238239/// Evaluate a file containing Jsonnet code, return a JSON string.240///241/// The returned string should be cleaned up with `jsonnet_realloc`.242///243/// # Safety244///245/// `filename` should be a NUL-terminated string246#[unsafe(no_mangle)]247pub unsafe extern "C" fn jsonnet_evaluate_file(248	vm: &VM,249	filename: *const c_char,250	error: &mut c_int,251) -> *const c_char {252	let filename = unsafe { parse_path(CStr::from_ptr(filename)) };253	match vm254		.state255		.import(filename)256		.and_then(|val| apply_tla(&vm.tla_args, val))257		.and_then(|val| val.manifest(&vm.manifest_format))258	{259		Ok(v) => {260			*error = 0;261			CString::new(&*v as &str).unwrap().into_raw()262		}263		Err(e) => {264			*error = 1;265			let mut out = String::new();266			vm.trace_format.write_trace(&mut out, &e).unwrap();267			CString::new(&out as &str).unwrap().into_raw()268		}269	}270}271272/// Evaluate a string containing Jsonnet code, return a JSON string.273///274/// The returned string should be cleaned up with `jsonnet_realloc`.275///276/// # Safety277///278/// `filename`, `snippet` should be a NUL-terminated strings279#[unsafe(no_mangle)]280pub unsafe extern "C" fn jsonnet_evaluate_snippet(281	vm: &VM,282	filename: *const c_char,283	snippet: *const c_char,284	error: &mut c_int,285) -> *const c_char {286	let filename = unsafe { CStr::from_ptr(filename) };287	let snippet = unsafe { CStr::from_ptr(snippet) };288	match vm289		.state290		.evaluate_snippet(filename.to_str().unwrap(), snippet.to_str().unwrap())291		.and_then(|val| apply_tla(&vm.tla_args, val))292		.and_then(|val| val.manifest(&vm.manifest_format))293	{294		Ok(mut v) => {295			if vm.trailing_newline {296				v.push('\n');297			}298			*error = 0;299			CString::new(&*v as &str).unwrap().into_raw()300		}301		Err(e) => {302			*error = 1;303			let mut out = String::new();304			vm.trace_format.write_trace(&mut out, &e).unwrap();305			CString::new(&out as &str).unwrap().into_raw()306		}307	}308}309310fn val_to_multi(val: Val, format: &dyn ManifestFormat) -> Result<Vec<(IStr, IStr)>> {311	let Val::Obj(val) = val else {312		bail!("expected object as multi output")313	};314	let mut out = Vec::new();315	for (k, v) in val.iter(316		#[cfg(feature = "exp-preserve-order")]317		false,318	) {319		out.push((k, v?.manifest(format)?.into()));320	}321	Ok(out)322}323324fn multi_to_raw(multi: Vec<(IStr, IStr)>, trailing_newline: bool) -> *const c_char {325	let mut out = Vec::new();326	for (i, (k, v)) in multi.iter().enumerate() {327		if i != 0 {328			out.push(0);329		}330		out.extend_from_slice(k.as_bytes());331		out.push(0);332		out.extend_from_slice(v.as_bytes());333		if trailing_newline {334			out.push(b'\n');335		}336	}337	out.push(0);338	out.push(0);339	let v = out.as_ptr();340	std::mem::forget(out);341	v.cast::<c_char>()342}343344/// # Safety345#[unsafe(no_mangle)]346pub unsafe extern "C" fn jsonnet_evaluate_file_multi(347	vm: &VM,348	filename: *const c_char,349	error: &mut c_int,350) -> *const c_char {351	let filename = unsafe { parse_path(CStr::from_ptr(filename)) };352	match vm353		.state354		.import(filename)355		.and_then(|val| apply_tla(&vm.tla_args, val))356		.and_then(|val| val_to_multi(val, &vm.manifest_format))357	{358		Ok(v) => {359			*error = 0;360			multi_to_raw(v, vm.trailing_newline)361		}362		Err(e) => {363			*error = 1;364			let mut out = String::new();365			vm.trace_format.write_trace(&mut out, &e).unwrap();366			CString::new(&out as &str).unwrap().into_raw()367		}368	}369}370371/// # Safety372#[unsafe(no_mangle)]373pub unsafe extern "C" fn jsonnet_evaluate_snippet_multi(374	vm: &VM,375	filename: *const c_char,376	snippet: *const c_char,377	error: &mut c_int,378) -> *const c_char {379	let filename = unsafe { CStr::from_ptr(filename) };380	let snippet = unsafe { CStr::from_ptr(snippet) };381	match vm382		.state383		.evaluate_snippet(filename.to_str().unwrap(), snippet.to_str().unwrap())384		.and_then(|val| apply_tla(&vm.tla_args, val))385		.and_then(|val| val_to_multi(val, &vm.manifest_format))386	{387		Ok(v) => {388			*error = 0;389			multi_to_raw(v, vm.trailing_newline)390		}391		Err(e) => {392			*error = 1;393			let mut out = String::new();394			vm.trace_format.write_trace(&mut out, &e).unwrap();395			CString::new(&out as &str).unwrap().into_raw()396		}397	}398}399400fn val_to_stream(val: Val, format: &dyn ManifestFormat) -> Result<Vec<IStr>> {401	let Val::Arr(val) = val else {402		bail!("expected array as stream output")403	};404	let mut out = Vec::new();405	for item in val.iter() {406		out.push(item?.manifest(format)?.into());407	}408	Ok(out)409}410411fn stream_to_raw(multi: Vec<IStr>, trailing_newline: bool) -> *const c_char {412	let mut out = Vec::new();413	for (i, v) in multi.iter().enumerate() {414		if i != 0 {415			out.push(0);416		}417		out.extend_from_slice(v.as_bytes());418		if trailing_newline {419			out.push(b'\n');420		}421	}422	out.push(0);423	out.push(0);424	let v = out.as_ptr();425	std::mem::forget(out);426	v.cast::<c_char>()427}428429/// # Safety430#[unsafe(no_mangle)]431pub unsafe extern "C" fn jsonnet_evaluate_file_stream(432	vm: &VM,433	filename: *const c_char,434	error: &mut c_int,435) -> *const c_char {436	let filename = unsafe { parse_path(CStr::from_ptr(filename)) };437	match vm438		.state439		.import(filename)440		.and_then(|val| apply_tla(&vm.tla_args, val))441		.and_then(|val| val_to_stream(val, &vm.manifest_format))442	{443		Ok(v) => {444			*error = 0;445			stream_to_raw(v, vm.trailing_newline)446		}447		Err(e) => {448			*error = 1;449			let mut out = String::new();450			vm.trace_format.write_trace(&mut out, &e).unwrap();451			CString::new(&out as &str).unwrap().into_raw()452		}453	}454}455456/// # Safety457#[unsafe(no_mangle)]458pub unsafe extern "C" fn jsonnet_evaluate_snippet_stream(459	vm: &VM,460	filename: *const c_char,461	snippet: *const c_char,462	error: &mut c_int,463) -> *const c_char {464	let filename = unsafe { CStr::from_ptr(filename) };465	let snippet = unsafe { CStr::from_ptr(snippet) };466	match vm467		.state468		.evaluate_snippet(filename.to_str().unwrap(), snippet.to_str().unwrap())469		.and_then(|val| apply_tla(&vm.tla_args, val))470		.and_then(|val| val_to_stream(val, &vm.manifest_format))471	{472		Ok(v) => {473			*error = 0;474			stream_to_raw(v, vm.trailing_newline)475		}476		Err(e) => {477			*error = 1;478			let mut out = String::new();479			vm.trace_format.write_trace(&mut out, &e).unwrap();480			CString::new(&out as &str).unwrap().into_raw()481		}482	}483}
modifiedcmds/jrb/src/main.rsdiffbeforeafterboth
--- a/cmds/jrb/src/main.rs
+++ b/cmds/jrb/src/main.rs
@@ -104,6 +104,7 @@
 	}
 }
 
+#[allow(clippy::too_many_lines)]
 fn main() {
 	tracing_subscriber::fmt().init();
 
modifiedcrates/jrsonnet-evaluator/src/analyze.rsdiffbeforeafterboth
--- a/crates/jrsonnet-evaluator/src/analyze.rs
+++ b/crates/jrsonnet-evaluator/src/analyze.rs
@@ -28,7 +28,10 @@
 use rustc_hash::FxHashMap;
 use smallvec::SmallVec;
 
-use crate::error::{format_found, suggest_names};
+use crate::{
+	arr::arridx,
+	error::{format_found, suggest_names},
+};
 
 #[derive(Debug, Clone, Copy)]
 #[must_use]
@@ -658,7 +661,7 @@
 	stack: &'s mut AnalysisStack,
 	bomb: DropBomb,
 }
-impl<'s> PendingBody<'s> {
+impl PendingBody<'_> {
 	/// After the body is processed, drop the frame's locals and emit any
 	/// "unused local" warnings.
 	fn finish(self) {
@@ -704,7 +707,7 @@
 			.drain(closures.first_in_frame.idx()..)
 			.collect();
 		for (i, def) in drained.iter().enumerate().rev() {
-			let id = LocalId(closures.first_in_frame.0 + i as u32);
+			let id = LocalId(closures.first_in_frame.0 + arridx(i));
 			let stack_locals = stack
 				.local_by_name
 				.get_mut(&def.name)
@@ -819,7 +822,7 @@
 			let (this_refs, rest) = refs.split_at(*refs_len);
 			refs = rest;
 			let start = next_id;
-			next_id += *dest_count as u32;
+			next_id += arridx(*dest_count);
 			Closure {
 				references: this_refs,
 				ids: start..next_id,
@@ -1043,7 +1046,7 @@
 	}
 
 	fn next_local_id(&self) -> LocalId {
-		LocalId(self.local_defs.len() as u32)
+		LocalId(arridx(self.local_defs.len()))
 	}
 
 	fn report_error(&mut self, msg: impl Into<String>, span: Option<Span>) {
@@ -1565,7 +1568,7 @@
 	let mut pending = alloc.finish();
 
 	let mut l_binds: Vec<LBind> = Vec::with_capacity(binds.len());
-	for (bind, destruct) in binds.iter().zip(destructs.into_iter()) {
+	for (bind, destruct) in binds.iter().zip(destructs) {
 		let mut value_taint = AnalysisResult::default();
 		let (value_shape, value) = pending
 			.stack
@@ -1608,7 +1611,7 @@
 	let mut pending = alloc.finish();
 
 	let mut l_params: Vec<LParam> = Vec::with_capacity(params.exprs.len());
-	for (p, destruct) in params.exprs.iter().zip(param_destructs.into_iter()) {
+	for (p, destruct) in params.exprs.iter().zip(param_destructs) {
 		let mut value_taint = AnalysisResult::default();
 		let default = p.default.as_ref().map_or_else(
 			|| None,
modifiedcrates/jrsonnet-evaluator/src/arr/mod.rsdiffbeforeafterboth
--- a/crates/jrsonnet-evaluator/src/arr/mod.rs
+++ b/crates/jrsonnet-evaluator/src/arr/mod.rs
@@ -2,6 +2,7 @@
 	any::Any,
 	fmt::{self},
 	num::NonZeroU32,
+	ops::{Bound, RangeBounds},
 	rc::Rc,
 };
 
@@ -104,20 +105,37 @@
 		Self::new(RangeArray::new_inclusive(a, b))
 	}
 
+	#[inline]
 	#[must_use]
-	pub fn slice(self, index: Option<i32>, end: Option<i32>, step: Option<NonZeroU32>) -> Self {
+	pub fn slice(self, range: impl RangeBounds<usize>) -> Self {
+		fn map_bound(start: bool, bound: Bound<&usize>) -> Option<i32> {
+			match bound {
+				Bound::Included(&v) => Some(i32::try_from(v).unwrap_or(i32::MAX)),
+				Bound::Excluded(&v) => Some(
+					i32::try_from(v)
+						.unwrap_or(i32::MAX)
+						.saturating_add(if start { 1 } else { -1 }),
+				),
+				Bound::Unbounded => None,
+			}
+		}
+		self.slice32(
+			map_bound(true, range.start_bound()),
+			map_bound(false, range.end_bound()),
+			None,
+		)
+	}
+
+	#[must_use]
+	pub fn slice32(self, index: Option<i32>, end: Option<i32>, step: Option<NonZeroU32>) -> Self {
 		let get_idx = |pos: Option<i32>, len: u32, default| match pos {
-			#[expect(
-				clippy::cast_sign_loss,
-				reason = "abs value is used, len is limited to u31"
-			)]
 			Some(v) if v < 0 => len.saturating_add_signed(v),
 			#[expect(clippy::cast_sign_loss, reason = "abs value is used")]
 			Some(v) => (v as u32).min(len),
 			None => default,
 		};
-		let index = get_idx(index, self.len(), 0);
-		let end = get_idx(end, self.len(), self.len());
+		let index = get_idx(index, self.len32(), 0);
+		let end = get_idx(end, self.len32(), self.len32());
 		let step = step.unwrap_or_else(|| NonZeroU32::new(1).expect("1 != 0"));
 
 		if index >= end {
@@ -126,24 +144,29 @@
 
 		Self::new(SliceArray {
 			inner: self,
-			#[expect(clippy::cast_possible_truncation, reason = "len is limited to u31")]
-			from: index as u32,
-			#[expect(clippy::cast_possible_truncation, reason = "len is limited to u31")]
-			to: end as u32,
+			from: index,
+			to: end,
 			step: step.get(),
 		})
 	}
 
 	/// Array length.
-	pub fn len(&self) -> u32 {
-		self.0.len()
+	#[inline]
+	pub fn len32(&self) -> u32 {
+		self.0.len32()
 	}
 
+	pub fn len(&self) -> usize {
+		self.len32() as usize
+	}
+
 	/// Is array contains no elements?
+	#[inline]
 	pub fn is_empty(&self) -> bool {
 		self.0.is_empty()
 	}
 
+	#[inline]
 	pub fn is_cheap(&self) -> bool {
 		self.0.is_cheap()
 	}
@@ -151,24 +174,37 @@
 	/// Get array element by index, evaluating it, if it is lazy.
 	///
 	/// Returns `None` on out-of-bounds condition.
-	pub fn get(&self, index: u32) -> Result<Option<Val>> {
-		self.0.get(index)
+	#[inline]
+	pub fn get32(&self, index: u32) -> Result<Option<Val>> {
+		self.0.get32(index)
+	}
+
+	pub fn get(&self, index: usize) -> Result<Option<Val>> {
+		let Ok(i) = u32::try_from(index) else {
+			return Ok(None);
+		};
+		self.get32(i)
 	}
 
 	/// Get array element by index, without evaluation.
 	///
 	/// Returns `None` on out-of-bounds condition.
-	pub fn get_lazy(&self, index: u32) -> Option<Thunk<Val>> {
-		self.0.get_lazy(index)
+	#[inline]
+	pub fn get_lazy32(&self, index: u32) -> Option<Thunk<Val>> {
+		self.0.get_lazy32(index)
+	}
+
+	pub fn get_lazy(&self, index: usize) -> Option<Thunk<Val>> {
+		u32::try_from(index).ok().and_then(|i| self.get_lazy32(i))
 	}
 
 	pub fn iter(&self) -> impl ArrayLikeIter<Result<Val>> + '_ {
-		(0..self.len()).map(|i| self.get(i).transpose().expect("length checked"))
+		(0..self.len32()).map(|i| self.get32(i).transpose().expect("length checked"))
 	}
 
 	/// Iterate over elements, returning lazy values.
 	pub fn iter_lazy(&self) -> impl ArrayLikeIter<Thunk<Val>> + '_ {
-		(0..self.len()).map(|i| self.get_lazy(i).expect("length checked"))
+		(0..self.len32()).map(|i| self.get_lazy32(i).expect("length checked"))
 	}
 
 	/// Return a reversed view on current array.
@@ -201,3 +237,18 @@
 		Self::new(iter.into_iter().collect::<Vec<_>>())
 	}
 }
+
+/// Checks that the usize does not exceed 4g with debug assertions enabled
+/// Should only be used on values that can't reasonably exceed this value
+#[inline]
+pub(crate) fn arridx(i: usize) -> u32 {
+	#[allow(
+		clippy::cast_possible_truncation,
+		reason = "array indexes never exceed 4g"
+	)]
+	if cfg!(debug_assertions) {
+		u32::try_from(i).expect("4g hard limit")
+	} else {
+		i as u32
+	}
+}
modifiedcrates/jrsonnet-evaluator/src/arr/spec.rsdiffbeforeafterboth
--- a/crates/jrsonnet-evaluator/src/arr/spec.rs
+++ b/crates/jrsonnet-evaluator/src/arr/spec.rs
@@ -9,7 +9,7 @@
 use jrsonnet_gcmodule::{Cc, Trace};
 use jrsonnet_interner::{IBytes, IStr};
 
-use super::ArrValue;
+use super::{ArrValue, arridx};
 use crate::{
 	Context, Error, ObjValue, Result, Thunk, Val,
 	analyze::{ClosureShape, LExpr},
@@ -21,12 +21,12 @@
 };
 
 pub trait ArrayLike: Any + Trace + Debug {
-	fn len(&self) -> u32;
+	fn len32(&self) -> u32;
 	fn is_empty(&self) -> bool {
-		self.len() == 0
+		self.len32() == 0
 	}
-	fn get(&self, index: u32) -> Result<Option<Val>>;
-	fn get_lazy(&self, index: u32) -> Option<Thunk<Val>>;
+	fn get32(&self, index: u32) -> Result<Option<Val>>;
+	fn get_lazy32(&self, index: u32) -> Option<Thunk<Val>>;
 
 	fn is_cheap(&self) -> bool {
 		false
@@ -40,15 +40,15 @@
 where
 	T: Any + Trace + Debug + ArrayCheap,
 {
-	fn len(&self) -> u32 {
+	fn len32(&self) -> u32 {
 		<T as ArrayCheap>::len(self)
 	}
 
-	fn get(&self, index: u32) -> Result<Option<Val>> {
+	fn get32(&self, index: u32) -> Result<Option<Val>> {
 		Ok(<T as ArrayCheap>::get(self, index))
 	}
 
-	fn get_lazy(&self, index: u32) -> Option<Thunk<Val>> {
+	fn get_lazy32(&self, index: u32) -> Option<Thunk<Val>> {
 		<T as ArrayCheap>::get(self, index).map(Thunk::evaluated)
 	}
 
@@ -80,16 +80,16 @@
 	}
 }
 impl ArrayLike for SliceArray {
-	fn len(&self) -> u32 {
+	fn len32(&self) -> u32 {
 		(self.to - self.from).div_ceil(self.step)
 	}
 
-	fn get(&self, index: u32) -> Result<Option<Val>> {
-		self.inner.get(self.map_idx(index))
+	fn get32(&self, index: u32) -> Result<Option<Val>> {
+		self.inner.get32(self.map_idx(index))
 	}
 
-	fn get_lazy(&self, index: u32) -> Option<Thunk<Val>> {
-		self.inner.get_lazy(self.map_idx(index))
+	fn get_lazy32(&self, index: u32) -> Option<Thunk<Val>> {
+		self.inner.get_lazy32(self.map_idx(index))
 	}
 
 	fn is_cheap(&self) -> bool {
@@ -99,7 +99,7 @@
 
 impl ArrayCheap for IBytes {
 	fn len(&self) -> u32 {
-		self.as_slice().len() as u32
+		arridx(self.as_slice().len())
 	}
 	fn get(&self, index: u32) -> Option<Val> {
 		self.as_slice()
@@ -132,11 +132,11 @@
 	}
 }
 impl ArrayLike for ExprArray {
-	fn len(&self) -> u32 {
-		self.cached.borrow().len() as u32
+	fn len32(&self) -> u32 {
+		arridx(self.cached.borrow().len())
 	}
-	fn get(&self, index: u32) -> Result<Option<Val>> {
-		if index >= self.len() {
+	fn get32(&self, index: u32) -> Result<Option<Val>> {
+		if index >= self.len32() {
 			return Ok(None);
 		}
 		match &self.cached.borrow()[index as usize] {
@@ -157,7 +157,7 @@
 		self.cached.borrow_mut()[index as usize] = ArrayThunk::Computed(new_value.clone());
 		Ok(Some(new_value))
 	}
-	fn get_lazy(&self, index: u32) -> Option<Thunk<Val>> {
+	fn get_lazy32(&self, index: u32) -> Option<Thunk<Val>> {
 		#[derive(Trace)]
 		struct ExprArrThunk {
 			expr: ExprArray,
@@ -168,13 +168,13 @@
 
 			fn get(&self) -> Result<Self::Output> {
 				self.expr
-					.get(self.index)
+					.get32(self.index)
 					.transpose()
 					.expect("index checked")
 			}
 		}
 
-		if index >= self.len() {
+		if index >= self.len32() {
 			return None;
 		}
 		match &self.cached.borrow()[index as usize] {
@@ -202,8 +202,8 @@
 }
 impl ExtendedArray {
 	pub fn new(a: ArrValue, b: ArrValue) -> Option<Self> {
-		let a_len = a.len();
-		let b_len = b.len();
+		let a_len = a.len32();
+		let b_len = b.len32();
 		let len = a_len.checked_add(b_len)?;
 		Some(Self {
 			a,
@@ -251,22 +251,22 @@
 	}
 }
 impl ArrayLike for ExtendedArray {
-	fn get(&self, index: u32) -> Result<Option<Val>> {
+	fn get32(&self, index: u32) -> Result<Option<Val>> {
 		if self.split > index {
-			self.a.get(index)
+			self.a.get32(index)
 		} else {
-			self.b.get(index - self.split)
+			self.b.get32(index - self.split)
 		}
 	}
-	fn get_lazy(&self, index: u32) -> Option<Thunk<Val>> {
+	fn get_lazy32(&self, index: u32) -> Option<Thunk<Val>> {
 		if self.split > index {
-			self.a.get_lazy(index)
+			self.a.get_lazy32(index)
 		} else {
-			self.b.get_lazy(index - self.split)
+			self.b.get_lazy32(index - self.split)
 		}
 	}
 
-	fn len(&self) -> u32 {
+	fn len32(&self) -> u32 {
 		self.len
 	}
 
@@ -280,18 +280,18 @@
 	T: IntoUntyped + Trace + fmt::Debug,
 	for<'a> &'a T: IntoUntyped,
 {
-	fn len(&self) -> u32 {
+	fn len32(&self) -> u32 {
 		self.as_slice().len().try_into().unwrap_or(u32::MAX)
 	}
 
-	fn get(&self, index: u32) -> Result<Option<Val>> {
+	fn get32(&self, index: u32) -> Result<Option<Val>> {
 		let Some(elem) = self.as_slice().get(index as usize) else {
 			return Ok(None);
 		};
 		IntoUntyped::into_untyped(elem).map(Some)
 	}
 
-	fn get_lazy(&self, index: u32) -> Option<Thunk<Val>> {
+	fn get_lazy32(&self, index: u32) -> Option<Thunk<Val>> {
 		let elem = self.as_slice().get(index as usize)?;
 		Some(IntoUntyped::into_lazy_untyped(elem))
 	}
@@ -343,16 +343,16 @@
 #[derive(Debug, Trace)]
 pub struct ReverseArray(pub ArrValue);
 impl ArrayLike for ReverseArray {
-	fn len(&self) -> u32 {
-		self.0.len()
+	fn len32(&self) -> u32 {
+		self.0.len32()
 	}
 
-	fn get(&self, index: u32) -> Result<Option<Val>> {
-		self.0.get(self.0.len() - index - 1)
+	fn get32(&self, index: u32) -> Result<Option<Val>> {
+		self.0.get32(self.0.len32() - index - 1)
 	}
 
-	fn get_lazy(&self, index: u32) -> Option<Thunk<Val>> {
-		self.0.get_lazy(self.0.len() - index - 1)
+	fn get_lazy32(&self, index: u32) -> Option<Thunk<Val>> {
+		self.0.get_lazy32(self.0.len32() - index - 1)
 	}
 
 	fn is_cheap(&self) -> bool {
@@ -374,7 +374,7 @@
 }
 impl MappedArray {
 	pub fn new(inner: ArrValue, mapper: ArrayMapper) -> Self {
-		let len = inner.len();
+		let len = inner.len32();
 		Self {
 			inner,
 			cached: Cc::new(RefCell::new(vec![ArrayThunk::Waiting; len as usize])),
@@ -389,12 +389,12 @@
 	}
 }
 impl ArrayLike for MappedArray {
-	fn len(&self) -> u32 {
-		self.cached.borrow().len() as u32
+	fn len32(&self) -> u32 {
+		arridx(self.cached.borrow().len())
 	}
 
-	fn get(&self, index: u32) -> Result<Option<Val>> {
-		if index >= self.len() {
+	fn get32(&self, index: u32) -> Result<Option<Val>> {
+		if index >= self.len32() {
 			return Ok(None);
 		}
 		match &self.cached.borrow()[index as usize] {
@@ -413,7 +413,7 @@
 
 		let val = self
 			.inner
-			.get(index)
+			.get32(index)
 			.transpose()
 			.expect("index checked")
 			.and_then(|r| self.evaluate(index, r));
@@ -428,7 +428,7 @@
 		self.cached.borrow_mut()[index as usize] = ArrayThunk::Computed(new_value.clone());
 		Ok(Some(new_value))
 	}
-	fn get_lazy(&self, index: u32) -> Option<Thunk<Val>> {
+	fn get_lazy32(&self, index: u32) -> Option<Thunk<Val>> {
 		#[derive(Trace)]
 		struct MappedArrayThunk {
 			arr: MappedArray,
@@ -438,11 +438,14 @@
 			type Output = Val;
 
 			fn get(&self) -> Result<Self::Output> {
-				self.arr.get(self.index).transpose().expect("index checked")
+				self.arr
+					.get32(self.index)
+					.transpose()
+					.expect("index checked")
 			}
 		}
 
-		if index >= self.len() {
+		if index >= self.len32() {
 			return None;
 		}
 		match &self.cached.borrow()[index as usize] {
@@ -471,12 +474,12 @@
 	}
 }
 impl ArrayLike for MakeArray {
-	fn len(&self) -> u32 {
-		self.cached.borrow().len() as u32
+	fn len32(&self) -> u32 {
+		arridx(self.cached.borrow().len())
 	}
 
-	fn get(&self, index: u32) -> Result<Option<Val>> {
-		if index >= self.len() {
+	fn get32(&self, index: u32) -> Result<Option<Val>> {
+		if index >= self.len32() {
 			return Ok(None);
 		}
 		match &self.cached.borrow()[index as usize] {
@@ -493,7 +496,7 @@
 			unreachable!()
 		};
 
-		let val = self.mapper.call(index as u32);
+		let val = self.mapper.call(index);
 
 		let new_value = match val {
 			Ok(v) => v,
@@ -505,7 +508,7 @@
 		self.cached.borrow_mut()[index as usize] = ArrayThunk::Computed(new_value.clone());
 		Ok(Some(new_value))
 	}
-	fn get_lazy(&self, index: u32) -> Option<Thunk<Val>> {
+	fn get_lazy32(&self, index: u32) -> Option<Thunk<Val>> {
 		#[derive(Trace)]
 		struct MakeArrayThunk {
 			arr: MakeArray,
@@ -515,11 +518,14 @@
 			type Output = Val;
 
 			fn get(&self) -> Result<Self::Output> {
-				self.arr.get(self.index).transpose().expect("index checked")
+				self.arr
+					.get32(self.index)
+					.transpose()
+					.expect("index checked")
 			}
 		}
 
-		if index >= self.len() {
+		if index >= self.len32() {
 			return None;
 		}
 		match &self.cached.borrow()[index as usize] {
@@ -543,7 +549,7 @@
 }
 impl RepeatedArray {
 	pub fn new(data: ArrValue, repeats: u32) -> Option<Self> {
-		let total_len = data.len().checked_mul(repeats)?;
+		let total_len = data.len32().checked_mul(repeats)?;
 		Some(Self {
 			data,
 			repeats,
@@ -554,25 +560,25 @@
 		if index > self.total_len {
 			return None;
 		}
-		Some(index % self.data.len())
+		Some(index % self.data.len32())
 	}
 }
 
 impl ArrayLike for RepeatedArray {
-	fn len(&self) -> u32 {
+	fn len32(&self) -> u32 {
 		self.total_len
 	}
 
-	fn get(&self, index: u32) -> Result<Option<Val>> {
+	fn get32(&self, index: u32) -> Result<Option<Val>> {
 		let Some(idx) = self.map_idx(index) else {
 			return Ok(None);
 		};
-		self.data.get(idx)
+		self.data.get32(idx)
 	}
 
-	fn get_lazy(&self, index: u32) -> Option<Thunk<Val>> {
+	fn get_lazy32(&self, index: u32) -> Option<Thunk<Val>> {
 		let idx = self.map_idx(index)?;
-		self.data.get_lazy(idx)
+		self.data.get_lazy32(idx)
 	}
 
 	fn is_cheap(&self) -> bool {
@@ -593,18 +599,18 @@
 }
 
 impl ArrayLike for PickObjectValues {
-	fn len(&self) -> u32 {
-		self.keys.len() as u32
+	fn len32(&self) -> u32 {
+		arridx(self.keys.len())
 	}
 
-	fn get(&self, index: u32) -> Result<Option<Val>> {
+	fn get32(&self, index: u32) -> Result<Option<Val>> {
 		let Some(key) = self.keys.as_slice().get(index as usize) else {
 			return Ok(None);
 		};
 		Ok(Some(self.obj.get_or_bail(key.clone())?))
 	}
 
-	fn get_lazy(&self, index: u32) -> Option<Thunk<Val>> {
+	fn get_lazy32(&self, index: u32) -> Option<Thunk<Val>> {
 		let key = self.keys.as_slice().get(index as usize)?;
 		Some(self.obj.get_lazy_or_bail(key.clone()))
 	}
@@ -633,11 +639,11 @@
 }
 
 impl ArrayLike for PickObjectKeyValues {
-	fn len(&self) -> u32 {
-		self.keys.len() as u32
+	fn len32(&self) -> u32 {
+		arridx(self.keys.len())
 	}
 
-	fn get(&self, index: u32) -> Result<Option<Val>> {
+	fn get32(&self, index: u32) -> Result<Option<Val>> {
 		let Some(key) = self.keys.as_slice().get(index as usize) else {
 			return Ok(None);
 		};
@@ -650,7 +656,7 @@
 		))
 	}
 
-	fn get_lazy(&self, index: u32) -> Option<Thunk<Val>> {
+	fn get_lazy32(&self, index: u32) -> Option<Thunk<Val>> {
 		let key = self.keys.as_slice().get(index as usize)?;
 		// Nothing can fail in the key part, yet value is still
 		// lazy-evaluated
modifiedcrates/jrsonnet-evaluator/src/ctx.rsdiffbeforeafterboth
--- a/crates/jrsonnet-evaluator/src/ctx.rs
+++ b/crates/jrsonnet-evaluator/src/ctx.rs
@@ -122,7 +122,7 @@
 	pub fn enter(self, sup_this: SupThis, build: impl FnOnce(&LocalsFrame, &Context)) -> Context {
 		let locals = LocalsFrame::new_once(self.n_locals);
 		let val = Context(Cc::new(ContextInternal {
-			captures: self.captures.clone(),
+			captures: self.captures,
 			locals,
 			sup_this: Some(sup_this),
 		}));
modifiedcrates/jrsonnet-evaluator/src/evaluate/compspec.rsdiffbeforeafterboth
--- a/crates/jrsonnet-evaluator/src/evaluate/compspec.rs
+++ b/crates/jrsonnet-evaluator/src/evaluate/compspec.rs
@@ -97,7 +97,7 @@
 		let value_ctx = inner_ctx
 			.pack_captures_sup_this(self.frame_shape)
 			.enter(|fill, ctx| {
-				fill_letrec_binds(fill, &ctx, self.locals);
+				fill_letrec_binds(fill, ctx, self.locals);
 			});
 		evaluate_field_member_static(self.builder, inner_ctx, value_ctx, self.field)
 	}
@@ -336,6 +336,7 @@
 	Ok(())
 }
 
+#[allow(clippy::too_many_lines)]
 fn evaluate_compspecs(
 	ctx: Context,
 	specs: &[LCompSpec],
@@ -381,7 +382,7 @@
 			for (i, item) in arr.iter().enumerate() {
 				let item = item?;
 				let inner_ctx = ctx.pack_captures_sup_this(frame_shape).enter(|fill, ctx| {
-					destruct(dst, fill, Thunk::evaluated(item), &ctx);
+					destruct(dst, fill, Thunk::evaluated(item), ctx);
 				});
 				evaluate_compspecs(
 					inner_ctx,
modifiedcrates/jrsonnet-evaluator/src/evaluate/destructure.rsdiffbeforeafterboth
--- a/crates/jrsonnet-evaluator/src/evaluate/destructure.rs
+++ b/crates/jrsonnet-evaluator/src/evaluate/destructure.rs
@@ -5,7 +5,7 @@
 use crate::{
 	Context, LocalsFrame, PackedContext, Result, SupThis, Thunk, Unbound, Val,
 	analyze::{
-		ClosureShape, LBind, LDestruct, LDestructField, LDestructRest, LExpr, LLocalExpr, LocalSlot,
+		ClosureShape, LBind, LDestruct, LDestructField, LDestructRest, LLocalExpr, LocalSlot,
 	},
 	bail,
 	evaluate::evaluate,
@@ -19,7 +19,7 @@
 
 	fill: &LocalsFrame,
 	value: Thunk<Val>,
-	a_ctx: &Context,
+	ctx: &Context,
 ) {
 	let min_len = start.len() + end.len();
 	let has_rest = rest.is_some();
@@ -29,14 +29,14 @@
 			bail!("expected array");
 		};
 		if !has_rest {
-			if arr.len() as usize != min_len {
-				bail!("expected {} elements, got {}", min_len, arr.len())
+			if arr.len() != min_len {
+				bail!("expected {} elements, got {}", min_len, arr.len32())
 			}
-		} else if (arr.len() as usize) < min_len {
+		} else if arr.len() < min_len {
 			bail!(
 				"expected at least {} elements, but array was only {}",
 				min_len,
-				arr.len()
+				arr.len32()
 			)
 		}
 		Ok(arr)
@@ -47,13 +47,13 @@
 		destruct(
 			d,
 			fill,
-			Thunk!(move || Ok(full.evaluate()?.get(i as u32)?.expect("length is checked"))),
-			a_ctx,
+			Thunk!(move || Ok(full.evaluate()?.get(i)?.expect("length is checked"))),
+			ctx,
 		);
 	}
 
-	let start_len = start.len() as u32;
-	let end_len = end.len() as u32;
+	let start_len = start.len();
+	let end_len = end.len();
 
 	if let Some(LDestructRest::Keep(slot)) = rest {
 		let full = full.clone();
@@ -62,11 +62,7 @@
 			Thunk!(move || {
 				let full = full.evaluate()?;
 				let to = full.len() - end_len;
-				Ok(Val::Arr(full.slice(
-					Some(start_len as i32),
-					Some(to as i32),
-					None,
-				)))
+				Ok(Val::Arr(full.slice(start_len..to)))
 			}),
 		);
 	}
@@ -79,10 +75,10 @@
 			Thunk!(move || {
 				let full = full.evaluate()?;
 				Ok(full
-					.get(full.len() - end_len + i as u32)?
+					.get(full.len() - end_len + i)?
 					.expect("length is checked"))
 			}),
-			a_ctx,
+			ctx,
 		);
 	}
 }
@@ -94,7 +90,7 @@
 
 	fill: &LocalsFrame,
 	value: Thunk<Val>,
-	a_ctx: &Context,
+	ctx: &Context,
 ) {
 	use jrsonnet_interner::IStr;
 	use rustc_hash::FxHashSet;
@@ -118,7 +114,7 @@
 			}
 		}
 		if !has_rest {
-			let len = obj.len();
+			let len = obj.len32();
 			if len as usize > field_names.len() {
 				bail!("too many fields, and rest not found");
 			}
@@ -142,10 +138,11 @@
 
 	for field in fields {
 		let field_name = field.name.clone();
-		let default_thunk: Option<Thunk<Val>> = field
-			.default
-			.as_ref()
-			.map(|(shape, expr)| build_b_thunk(a_ctx, shape, expr.clone()));
+		let default_thunk: Option<Thunk<Val>> = field.default.as_ref().map(|(shape, expr)| {
+			let expr = expr.clone();
+			let env = Context::enter_using(ctx, shape);
+			Thunk!(move || evaluate(env, &expr))
+		});
 
 		let field_full = full.clone();
 		let value_thunk = Thunk!(move || {
@@ -157,7 +154,7 @@
 		});
 
 		if let Some(into) = &field.into {
-			destruct(into, fill, value_thunk, a_ctx);
+			destruct(into, fill, value_thunk, ctx);
 		} else {
 			unreachable!("analyzer lowers object-destruct shorthands into `into`");
 		}
@@ -177,21 +174,18 @@
 		#[cfg(feature = "exp-destruct")]
 		LDestruct::Object { fields, rest } => destruct_object(fields, rest.as_ref(), fill, value, a_ctx),
 	}
-}
-
-pub fn build_b_thunk(a_ctx: &Context, shape: &ClosureShape, expr: Rc<LExpr>) -> Thunk<Val> {
-	let env = Context::enter_using(a_ctx, shape);
-	Thunk!(move || evaluate(env, &expr))
-}
-pub fn build_b_thunk_uno(a_ctx: &Context, shape: Rc<(ClosureShape, LExpr)>) -> Thunk<Val> {
-	let env = Context::enter_using(a_ctx, &shape.0);
-	Thunk!(move || evaluate(env, &shape.1))
 }
 
 pub fn fill_letrec_binds(fill: &LocalsFrame, ctx: &Context, binds: &[LBind]) {
 	for bind in binds {
-		let value_thunk = build_b_thunk(ctx, &bind.value_shape, bind.value.clone());
-		destruct(&bind.destruct, fill, value_thunk, ctx);
+		let expr = bind.value.clone();
+		let env = Context::enter_using(ctx, &bind.value_shape);
+		destruct(
+			&bind.destruct,
+			fill,
+			Thunk!(move || evaluate(env, &expr)),
+			ctx,
+		);
 	}
 }
 
modifiedcrates/jrsonnet-evaluator/src/evaluate/mod.rsdiffbeforeafterboth
--- a/crates/jrsonnet-evaluator/src/evaluate/mod.rs
+++ b/crates/jrsonnet-evaluator/src/evaluate/mod.rs
@@ -7,7 +7,7 @@
 
 use self::{
 	compspec::{evaluate_arr_comp, evaluate_obj_comp},
-	destructure::{build_b_thunk_uno, evaluate_local_expr, evaluate_locals_unbound},
+	destructure::{evaluate_local_expr, evaluate_locals_unbound},
 	operator::evaluate_binary_op_special,
 };
 use crate::{
@@ -115,6 +115,7 @@
 	}
 }
 
+#[allow(clippy::too_many_lines)]
 pub fn evaluate(ctx: Context, expr: &LExpr) -> Result<Val> {
 	Ok(match expr {
 		LExpr::Null => Val::Null,
@@ -218,7 +219,7 @@
 					BoundedUsize::from_untyped(v).description("slice step value")
 				})
 				.transpose()?;
-			Val::from(indexable.slice(start, end, step)?)
+			Val::from(indexable.slice32(start, end, step)?)
 		}
 		LExpr::Super => Val::Obj(ctx.try_sup_this()?.standalone_super().ok_or(NoSuperFound)?),
 		LExpr::Import {
@@ -320,6 +321,7 @@
 	)
 }
 
+#[allow(clippy::too_many_lines)]
 fn evaluate_index(ctx: Context, indexable: &LExpr, parts: &[LIndexPart]) -> Result<Val> {
 	let mut parts = parts.iter();
 	let mut indexable = if matches!(indexable, LExpr::Super) {
@@ -394,17 +396,17 @@
 				if n.fract() > f64::EPSILON {
 					bail!(FractionalIndex)
 				}
-				let len = arr.len();
+				let len = arr.len32();
 				if n < 0.0 || n > f64::from(len) {
 					bail!(ArrayBoundsError(n, len));
 				}
 				#[expect(
 					clippy::cast_possible_truncation,
 					clippy::cast_sign_loss,
-					reason = "n is checked positive"
+					reason = "n is checked range"
 				)]
 				let i = n as u32;
-				arr.get(i)
+				arr.get32(i)
 					.with_description_src(loc, || format!("element <{i}> access"))?
 					.ok_or_else(|| ArrayBoundsError(n, len))?
 			}
@@ -507,12 +509,13 @@
 		return Ok(());
 	};
 
-	let thunk = build_b_thunk_uno(&value_ctx, value.clone());
+	let env = Context::enter_using(&value_ctx, &value.0);
+	let value = value.clone();
 	builder
 		.field(name)
 		.with_add(*plus)
 		.with_visibility(*visibility)
-		.try_thunk(thunk)?;
+		.try_thunk(Thunk!(move || evaluate(env, &value.1)))?;
 	Ok(())
 }
 
modifiedcrates/jrsonnet-evaluator/src/function/mod.rsdiffbeforeafterboth
--- a/crates/jrsonnet-evaluator/src/function/mod.rs
+++ b/crates/jrsonnet-evaluator/src/function/mod.rs
@@ -11,12 +11,10 @@
 	prepared::{PreparedCall, parse_prepared_builtin_call},
 };
 use crate::{
-	PackedContextSupThis, Result, Thunk, Val,
+	Context, PackedContextSupThis, Result, Thunk, Val,
 	analyze::LFunction,
-	evaluate::{
-		destructure::{build_b_thunk, destruct},
-		ensure_sufficient_stack, evaluate, evaluate_trivial,
-	},
+	arr::arridx,
+	evaluate::{destructure::destruct, ensure_sufficient_stack, evaluate, evaluate_trivial},
 	function::builtin::BuiltinFunc,
 };
 
@@ -83,7 +81,7 @@
 					&self.func.params[param_idx].destruct,
 					fill,
 					thunk.clone(),
-					&ctx,
+					ctx,
 				);
 			}
 			for &(param_idx, arg_idx) in prepared.named() {
@@ -91,15 +89,22 @@
 					&self.func.params[param_idx].destruct,
 					fill,
 					named[arg_idx].clone(),
-					&ctx,
+					ctx,
 				);
 			}
 
 			for &param_idx in prepared.defaults() {
 				let param = &self.func.params[param_idx];
 				let (shape, expr) = param.default.as_ref().expect("default exists");
-				let thunk = build_b_thunk(&ctx, shape, expr.clone());
-				destruct(&param.destruct, fill, thunk, &ctx);
+				let expr = expr.clone();
+				let env = Context::enter_using(ctx, shape);
+
+				destruct(
+					&param.destruct,
+					fill,
+					Thunk!(move || evaluate(env, &expr)),
+					ctx,
+				);
 			}
 		});
 
@@ -152,8 +157,8 @@
 		}
 	}
 	/// Amount of non-default required arguments
-	pub fn params_len(&self) -> u32 {
-		self.params().iter().filter(|p| !p.has_default()).count() as u32
+	pub fn params_len32(&self) -> u32 {
+		arridx(self.params().iter().filter(|p| !p.has_default()).count())
 	}
 	/// Function name, as defined in code.
 	pub fn name(&self) -> IStr {
modifiedcrates/jrsonnet-evaluator/src/integrations/serde.rsdiffbeforeafterboth
--- a/crates/jrsonnet-evaluator/src/integrations/serde.rs
+++ b/crates/jrsonnet-evaluator/src/integrations/serde.rs
@@ -182,7 +182,7 @@
 			#[cfg(feature = "exp-bigint")]
 			Self::BigInt(b) => b.serialize(serializer),
 			Self::Arr(arr) => {
-				let mut seq = serializer.serialize_seq(Some(arr.len() as usize))?;
+				let mut seq = serializer.serialize_seq(Some(arr.len()))?;
 				for (i, element) in arr.iter().enumerate() {
 					let mut serde_error = None;
 					in_description_frame(
@@ -203,7 +203,7 @@
 				seq.end()
 			}
 			Self::Obj(obj) => {
-				let mut map = serializer.serialize_map(Some(obj.len() as usize))?;
+				let mut map = serializer.serialize_map(Some(obj.len32() as usize))?;
 				for (field, value) in obj.iter(
 					#[cfg(feature = "exp-preserve-order")]
 					true,
modifiedcrates/jrsonnet-evaluator/src/obj/mod.rsdiffbeforeafterboth
--- a/crates/jrsonnet-evaluator/src/obj/mod.rs
+++ b/crates/jrsonnet-evaluator/src/obj/mod.rs
@@ -23,7 +23,7 @@
 
 use crate::{
 	CcUnbound, MaybeUnbound, Result, Thunk, Unbound, Val,
-	arr::{PickObjectKeyValues, PickObjectValues},
+	arr::{PickObjectKeyValues, PickObjectValues, arridx},
 	bail,
 	error::{ErrorKind::*, suggest_object_fields},
 	evaluate::operator::evaluate_add_op,
@@ -510,11 +510,14 @@
 	// }
 	/// Returns amount of visible object fields
 	/// If object only contains hidden fields - may return zero.
-	pub fn len(&self) -> u32 {
+	pub fn len(&self) -> usize {
 		self.fields_visibility()
 			.values()
 			.filter(|d| d.visible())
-			.count() as u32
+			.count()
+	}
+	pub fn len32(&self) -> u32 {
+		arridx(self.len())
 	}
 	/// For each field, calls callback.
 	/// If callback returns false - ends iteration prematurely.
@@ -625,7 +628,7 @@
 				Entry::Vacant(v) => {
 					v.insert(CacheValue::Pending);
 				}
-			};
+			}
 		}
 		let result = self.get_idx_uncached(key, core);
 		{
modifiedcrates/jrsonnet-evaluator/src/stack.rsdiffbeforeafterboth
--- a/crates/jrsonnet-evaluator/src/stack.rs
+++ b/crates/jrsonnet-evaluator/src/stack.rs
@@ -11,7 +11,7 @@
 struct NightlyLocalKey<T>(pub T);
 #[cfg(nightly)]
 impl<T> NightlyLocalKey<T> {
-	#[inline(always)]
+	#[inline]
 	fn with<U>(&self, v: impl FnOnce(&T) -> U) -> U {
 		v(&self.0)
 	}
modifiedcrates/jrsonnet-evaluator/src/trace/mod.rsdiffbeforeafterboth
--- a/crates/jrsonnet-evaluator/src/trace/mod.rs
+++ b/crates/jrsonnet-evaluator/src/trace/mod.rs
@@ -197,7 +197,7 @@
 					w = align
 				)?;
 			} else {
-				write!(out, "{:<p$}{}", "", el.desc, p = self.padding,)?;
+				write!(out, "{:<p$}{}", "", el.desc, p = self.padding)?;
 			}
 		}
 		Ok(())
@@ -258,6 +258,7 @@
 }
 #[cfg(feature = "explaining-traces")]
 impl TraceFormat for HiDocFormat {
+	#[allow(clippy::too_many_lines)]
 	fn write_trace(&self, out: &mut dyn fmt::Write, error: &Error) -> Result<(), fmt::Error> {
 		struct ResetData {
 			loc: Span,
modifiedcrates/jrsonnet-evaluator/src/typed/conversions.rsdiffbeforeafterboth
--- a/crates/jrsonnet-evaluator/src/typed/conversions.rs
+++ b/crates/jrsonnet-evaluator/src/typed/conversions.rs
@@ -637,7 +637,7 @@
 		}
 		<Self as Typed>::TYPE.check(&value)?;
 		// Any::downcast_ref::<ByteArray>(&a);
-		let mut out = Vec::with_capacity(a.len() as usize);
+		let mut out = Vec::with_capacity(a.len());
 		for e in a.iter() {
 			let r = e?;
 			out.push(u8::from_untyped(r)?);
modifiedcrates/jrsonnet-evaluator/src/val.rsdiffbeforeafterboth
--- a/crates/jrsonnet-evaluator/src/val.rs
+++ b/crates/jrsonnet-evaluator/src/val.rs
@@ -277,7 +277,7 @@
 	/// For strings, will create a copy of specified interval.
 	///
 	/// For arrays, nothing will be copied on this call, instead [`ArrValue::Slice`] view will be returned.
-	pub fn slice(
+	pub fn slice32(
 		self,
 		index: Option<i32>,
 		end: Option<i32>,
@@ -321,7 +321,7 @@
 					.into(),
 				))
 			}
-			Self::Arr(arr) => Ok(Self::Arr(arr.clone().slice(
+			Self::Arr(arr) => Ok(Self::Arr(arr.clone().slice32(
 				index,
 				end,
 				#[expect(
@@ -658,7 +658,7 @@
 			if ArrValue::ptr_eq(a, b) {
 				return Ok(true);
 			}
-			if a.len() != b.len() {
+			if a.len32() != b.len32() {
 				return Ok(false);
 			}
 			for (a, b) in a.iter().zip(b.iter()) {
modifiedcrates/jrsonnet-formatter/src/lib.rsdiffbeforeafterboth
--- a/crates/jrsonnet-formatter/src/lib.rs
+++ b/crates/jrsonnet-formatter/src/lib.rs
@@ -477,8 +477,7 @@
 						&mut out,
 					);
 
-					let mut compspecs = compspecs.into_iter().peekable();
-					while let Some(mem) = compspecs.next() {
+					for mem in compspecs {
 						if mem.should_start_with_newline {
 							p!(out, nl);
 						}
modifiedcrates/jrsonnet-peg-parser/src/lib.rsdiffbeforeafterboth
--- a/crates/jrsonnet-peg-parser/src/lib.rs
+++ b/crates/jrsonnet-peg-parser/src/lib.rs
@@ -273,19 +273,15 @@
 				Expr::ArrComp(Box::new(expr), specs)
 			}
 		pub rule number_expr(s: &ParserSettings) -> Expr
-			= n:number() {? if let Some(n) = NumValue::new(n) {
-				Ok(Expr::Num(n))
-			} else {
-				Err("!!!numbers are finite")
-			}}
+			= n:number() {? NumValue::new(n).map_or_else(|| Err("!!!numbers are finite"), |n| Ok(Expr::Num(n)))}
 
 		rule spanned<T: Acyclic>(x: rule<T>, s: &ParserSettings) -> Spanned<T>
-			= a:position!() n:x() b:position!() { Spanned::new(n, Span(s.source.clone(), a as u32, b as u32)) }
+			= a:position!() n:x() b:position!() { Spanned::new(n, Span(s.source.clone(), codeidx(a), codeidx(b))) }
 
 		pub rule var_expr(s: &ParserSettings) -> Expr
 			= n:spanned(<id()>, s) { Expr::Var(n) }
 		pub rule id_loc(s: &ParserSettings) -> Spanned<Expr>
-			= a:position!() n:id() b:position!() { Spanned::new(Expr::Str(n), Span(s.source.clone(), a as u32,b as u32)) }
+			= a:position!() n:id() b:position!() { Spanned::new(Expr::Str(n), Span(s.source.clone(), codeidx(a), codeidx(b))) }
 		pub rule if_then_else_expr(s: &ParserSettings) -> Expr
 			= cond:ifspec(s) _ keyword("then") _ cond_then:expr(s) cond_else:(_ keyword("else") _ e:expr(s) {e})? {Expr::IfElse(Box::new(IfElse{
 				cond,
@@ -421,6 +417,10 @@
 	}
 }
 
+fn codeidx(i: usize) -> u32 {
+	u32::try_from(i).expect("code has 4g hard limit")
+}
+
 pub type ParseError = peg::error::ParseError<peg::str::LineCol>;
 pub fn parse(str: &str, settings: &ParserSettings) -> Result<Expr, ParseError> {
 	jsonnet_parser::jsonnet(str, settings)
@@ -428,7 +428,10 @@
 /// Used for importstr values
 pub fn string_to_expr(str: IStr, settings: &ParserSettings) -> Spanned<Expr> {
 	let len = str.len();
-	Spanned::new(Expr::Str(str), Span(settings.source.clone(), 0, len as u32))
+	Spanned::new(
+		Expr::Str(str),
+		Span(settings.source.clone(), 0, codeidx(len)),
+	)
 }
 
 #[cfg(test)]
modifiedcrates/jrsonnet-pkg/src/install/accessor.rsdiffbeforeafterboth
--- a/crates/jrsonnet-pkg/src/install/accessor.rs
+++ b/crates/jrsonnet-pkg/src/install/accessor.rs
@@ -66,6 +66,10 @@
 		Ok(Some(out))
 	}
 	#[allow(clippy::significant_drop_tightening, reason = "false-positive")]
+	#[allow(
+		clippy::iter_not_returning_iterator,
+		reason = "idk for a better name, it is still inner iteration"
+	)]
 	pub fn iter<E>(
 		&self,
 		subdir: &SubDir,
modifiedcrates/jrsonnet-rowan-parser/src/parser.rsdiffbeforeafterboth
--- a/crates/jrsonnet-rowan-parser/src/parser.rs
+++ b/crates/jrsonnet-rowan-parser/src/parser.rs
@@ -226,12 +226,12 @@
 		self.nth_at(0, kind)
 	}
 	pub fn nth_at(&self, n: usize, kind: SyntaxKind) -> bool {
-		if n == 0 {
-			if let ExpectedSyntax::Unnamed(kinds) = self.expected_syntax_tracking_state.get() {
-				let kinds = kinds.with(kind);
-				self.expected_syntax_tracking_state
-					.set(ExpectedSyntax::Unnamed(kinds));
-			}
+		if n == 0
+			&& let ExpectedSyntax::Unnamed(kinds) = self.expected_syntax_tracking_state.get()
+		{
+			let kinds = kinds.with(kind);
+			self.expected_syntax_tracking_state
+				.set(ExpectedSyntax::Unnamed(kinds));
 		}
 		self.nth(n) == kind
 	}
modifiedcrates/jrsonnet-stdlib/src/arrays.rsdiffbeforeafterboth
--- a/crates/jrsonnet-stdlib/src/arrays.rs
+++ b/crates/jrsonnet-stdlib/src/arrays.rs
@@ -52,7 +52,7 @@
 	step: Option<Option<BoundedUsize<1, { i32::MAX as usize }>>>,
 ) -> Result<Val> {
 	indexable
-		.slice(index.flatten(), end.flatten(), step.flatten())
+		.slice32(index.flatten(), end.flatten(), step.flatten())
 		.map(Val::from)
 }
 
@@ -204,14 +204,14 @@
 				let item = item?.clone();
 				if let Val::Arr(items) = item {
 					if !first {
-						out.reserve(joiner_items.len() as usize);
+						out.reserve(joiner_items.len());
 						// TODO: extend
 						for item in joiner_items.iter() {
 							out.push(item?);
 						}
 					}
 					first = false;
-					out.reserve(items.len() as usize);
+					out.reserve(items.len());
 					for item in items.iter() {
 						out.push(item?);
 					}
@@ -372,10 +372,10 @@
 
 #[builtin]
 pub fn builtin_remove_at(arr: ArrValue, at: i32) -> Result<ArrValue> {
-	let newArrLeft = arr.clone().slice(None, Some(at), None);
-	let newArrRight = arr.slice(Some(at + 1), None, None);
+	let newArrLeft = arr.clone().slice32(None, Some(at), None);
+	let newArrRight = arr.slice32(Some(at + 1), None, None);
 
-	Ok(ArrValue::extended(newArrLeft, newArrRight).ok_or_else(|| error!("array is too large"))?)
+	ArrValue::extended(newArrLeft, newArrRight).ok_or_else(|| error!("array is too large"))
 }
 
 #[builtin]
modifiedcrates/jrsonnet-stdlib/src/manifest/xml.rsdiffbeforeafterboth
--- a/crates/jrsonnet-stdlib/src/manifest/xml.rs
+++ b/crates/jrsonnet-stdlib/src/manifest/xml.rs
@@ -44,15 +44,15 @@
 			bail!("JSONML value should have tag (array length should be >=1)");
 		}
 		let tag = String::from_untyped(
-			arr.get(0)
+			arr.get32(0)
 				.description("getting JSONML tag")?
 				.expect("length checked"),
 		)
 		.description("parsing JSONML tag")?;
 
-		let (has_attrs, attrs) = if arr.len() >= 2 {
+		let (has_attrs, attrs) = if arr.len32() >= 2 {
 			let maybe_attrs = arr
-				.get(1)
+				.get32(1)
 				.with_description(|| "getting JSONML attrs")?
 				.expect("length checked");
 			if let Val::Obj(attrs) = maybe_attrs {
@@ -68,13 +68,7 @@
 			attrs,
 			children: in_description_frame(
 				|| "parsing children".to_owned(),
-				|| {
-					FromUntyped::from_untyped(Val::Arr(arr.slice(
-						Some(if has_attrs { 2 } else { 1 }),
-						None,
-						None,
-					)))
-				},
+				|| FromUntyped::from_untyped(Val::Arr(arr.slice(if has_attrs { 2 } else { 1 }..))),
 			)?,
 		})
 	}
modifiedcrates/jrsonnet-stdlib/src/misc.rsdiffbeforeafterboth
--- a/crates/jrsonnet-stdlib/src/misc.rs
+++ b/crates/jrsonnet-stdlib/src/misc.rs
@@ -16,10 +16,10 @@
 pub fn builtin_length(x: Either![IStr, ArrValue, ObjValue, FuncVal]) -> u32 {
 	use Either4::*;
 	match x {
-		A(x) => x.chars().count() as u32,
-		B(x) => x.len(),
-		C(x) => x.len(),
-		D(f) => f.params_len(),
+		A(x) => u32::try_from(x.chars().count()).expect("4g limit"),
+		B(x) => x.len32(),
+		C(x) => x.len32(),
+		D(f) => f.params_len32(),
 	}
 }
 
@@ -102,7 +102,7 @@
 			} else if b.len() == a.len() {
 				return equals(&Val::Arr(a), &Val::Arr(b));
 			}
-			for (a, b) in a.iter().take(b.len() as usize).zip(b.iter()) {
+			for (a, b) in a.iter().take(b.len()).zip(b.iter()) {
 				let a = a?;
 				let b = b?;
 				if !equals(&a, &b)? {
@@ -127,7 +127,7 @@
 				return equals(&Val::Arr(a), &Val::Arr(b));
 			}
 			let a_len = a.len();
-			for (a, b) in a.iter().skip((a_len - b.len()) as usize).zip(b.iter()) {
+			for (a, b) in a.iter().skip(a_len - b.len()).zip(b.iter()) {
 				let a = a?;
 				let b = b?;
 				if !equals(&a, &b)? {
modifiedcrates/jrsonnet-stdlib/src/sets.rsdiffbeforeafterboth
--- a/crates/jrsonnet-stdlib/src/sets.rs
+++ b/crates/jrsonnet-stdlib/src/sets.rs
@@ -8,13 +8,13 @@
 #[allow(non_snake_case)]
 pub fn builtin_set_member(x: Thunk<Val>, arr: ArrValue, #[default] keyF: KeyF) -> Result<bool> {
 	let mut low = 0;
-	let mut high = arr.len();
+	let mut high = arr.len32();
 
 	let x = keyF.eval(x)?;
 
 	while low < high {
 		let middle = u32::midpoint(high, low);
-		let comp = keyF.eval(arr.get_lazy(middle).expect("in bounds"))?;
+		let comp = keyF.eval(arr.get_lazy32(middle).expect("in bounds"))?;
 		match Val::try_cmp(&comp, &x)? {
 			Ordering::Less => low = middle + 1,
 			Ordering::Equal => return Ok(true),
modifiedcrates/jrsonnet-stdlib/src/sort.rsdiffbeforeafterboth
--- a/crates/jrsonnet-stdlib/src/sort.rs
+++ b/crates/jrsonnet-stdlib/src/sort.rs
@@ -69,7 +69,7 @@
 
 fn sort_keyf(values: ArrValue, keyf: KeyF) -> Result<Vec<Thunk<Val>>> {
 	// Slow path, user provided key getter
-	let mut vk = Vec::with_capacity(values.len() as usize);
+	let mut vk = Vec::with_capacity(values.len());
 	for value in values.iter_lazy() {
 		vk.push((value.clone(), keyf.eval(value)?));
 	}
@@ -137,7 +137,7 @@
 
 fn uniq_keyf(arr: ArrValue, keyf: KeyF) -> Result<Vec<Thunk<Val>>> {
 	let mut out = Vec::new();
-	let last_value = arr.get_lazy(0).unwrap();
+	let last_value = arr.get_lazy32(0).unwrap();
 	let mut last_key = keyf.eval(last_value.clone())?;
 	out.push(last_value);
 
modifiedcrates/jrsonnet-types/src/lib.rsdiffbeforeafterboth
--- a/crates/jrsonnet-types/src/lib.rs
+++ b/crates/jrsonnet-types/src/lib.rs
@@ -103,10 +103,8 @@
 			Self::BoundedNumber(a, b) => write!(
 				f,
 				"BoundedNumber<{}, {}>",
-				a.map(|e| e.to_string())
-					.unwrap_or_else(|| "open".to_owned()),
-				b.map(|e| e.to_string())
-					.unwrap_or_else(|| "open".to_owned())
+				a.map_or_else(|| "open".to_owned(), |e| e.to_string()),
+				b.map_or_else(|| "open".to_owned(), |e| e.to_string())
 			)?,
 			Self::ArrayRef(a) => print_array(a, f)?,
 			Self::Array(a) => print_array(a, f)?,
modifiedtests/tests/cpp_test_suite.rsdiffbeforeafterboth
--- a/tests/tests/cpp_test_suite.rs
+++ b/tests/tests/cpp_test_suite.rs
@@ -60,7 +60,7 @@
 	let _entered = s.enter();
 
 	let trace_format = CompactFormat {
-		resolver: resolver.clone(),
+		resolver,
 		max_trace: 20,
 		padding: 4,
 	};
modifiedxtask/src/bench.rsdiffbeforeafterboth
--- a/xtask/src/bench.rs
+++ b/xtask/src/bench.rs
@@ -91,6 +91,10 @@
 
 	let start = Instant::now();
 	let child = cmd.spawn()?;
+	#[allow(
+		clippy::cast_possible_wrap,
+		reason = "it is signed, but libc didn't set unsigned for it"
+	)]
 	let pid = child.id() as libc::pid_t;
 	// We'll reap via wait4 ourselves; don't let std touch this handle again.
 	mem::forget(child);
@@ -133,10 +137,10 @@
 	);
 	eprintln!(
 		"           max_rss: {} ± {} KiB  [{}..{}]",
-		r.max_rss_kib.mean as i64,
-		r.max_rss_kib.stddev as i64,
-		r.max_rss_kib.min as i64,
-		r.max_rss_kib.max as i64,
+		r.max_rss_kib.mean.trunc(),
+		r.max_rss_kib.stddev.trunc(),
+		r.max_rss_kib.min.trunc(),
+		r.max_rss_kib.max.trunc(),
 	);
 	Ok(())
 }
modifiedxtask/src/sourcegen/mod.rsdiffbeforeafterboth
--- a/xtask/src/sourcegen/mod.rs
+++ b/xtask/src/sourcegen/mod.rs
@@ -113,6 +113,7 @@
 	Ok(())
 }
 
+#[allow(clippy::too_many_lines)]
 fn generate_syntax_kinds(kinds: &KindsSrc, grammar: &AstSrc, lexer: bool) -> Result<String> {
 	let t_macros = kinds.tokens().filter_map(TokenKind::expand_t_macros);
 	let token_kinds = kinds.tokens().map(|t| t.expand_kind(lexer));