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
--- a/bindings/jsonnet/src/lib.rs
+++ b/bindings/jsonnet/src/lib.rs
@@ -66,14 +66,12 @@
 	#[cfg(target_family = "unix")]
 	{
 		use std::os::unix::ffi::OsStrExt;
-		let str = CString::new(input.as_os_str().as_bytes()).expect("input has zero byte in it");
-		str
+		CString::new(input.as_os_str().as_bytes()).expect("input has zero byte in it")
 	}
 	#[cfg(not(target_family = "unix"))]
 	{
 		let str = input.as_os_str().to_str().expect("bad utf-8");
-		let cstr = CString::new(str).expect("input has NUL inside");
-		cstr
+		CString::new(str).expect("input has NUL inside")
 	}
 }
 
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
before · crates/jrsonnet-peg-parser/src/lib.rs
1use jrsonnet_gcmodule::Acyclic;2use jrsonnet_ir::{3	ArgsDesc, AssertExpr, AssertStmt, BinaryOp, BindSpec, CompSpec, Destruct, DestructRest, Expr,4	ExprParam, ExprParams, FieldMember, FieldName, ForSpecData, IStr, IfElse, IfSpecData,5	ImportKind, IndexPart, LiteralType, Member, NumValue, ObjBody, ObjComp, ObjMembers, Slice,6	SliceDesc, Source, Span, Spanned, Visibility, unescape,7};8use peg::parser;910pub struct ParserSettings {11	pub source: Source,12}1314macro_rules! expr_bin {15	($a:ident $op:ident $b:ident) => {16		Expr::BinaryOp(Box::new(BinaryOp {17			lhs: $a,18			op: $op,19			rhs: $b,20		}))21	};22}23macro_rules! expr_un {24	($op:ident $a:ident) => {25		Expr::UnaryOp($op, Box::new($a))26	};27}2829parser! {30	pub grammar jsonnet_parser() for str {31		use peg::ParseLiteral;3233		rule eof() = quiet!{![_]} / expected!("<eof>")34		rule eol() = "\n" / eof()3536		/// Standard C-like comments37		rule comment()38			= "//" (!eol()[_])* eol()39			/ "/*" (!("*/")[_])* "*/"40			/ "#" (!eol()[_])* eol()4142		rule single_whitespace() = quiet!{([' ' | '\r' | '\n' | '\t'] / comment())} / expected!("<whitespace>")43		rule _() = quiet!{([' ' | '\r' | '\n' | '\t']+) / comment()}* / expected!("<whitespace>")4445		/// For comma-delimited elements46		rule comma() = quiet!{_ "," _} / expected!("<comma>")47		rule alpha() -> char = c:$(['_' | 'a'..='z' | 'A'..='Z']) {c.chars().next().unwrap()}48		rule digit() -> char = d:$(['0'..='9']) {d.chars().next().unwrap()}49		rule end_of_ident() = !['0'..='9' | '_' | 'a'..='z' | 'A'..='Z']50		/// Sequence of digits51		rule uint_str() -> &'input str = a:$(digit()+ ("_" digit()+)*) { a }52		/// Number in scientific notation format53		rule number() -> f64 = quiet!{a:$(uint_str() ("." uint_str())? (['e'|'E'] (s:['+'|'-'])? uint_str())?) {? a.replace('_',"").parse().map_err(|_| "<number>") }} / expected!("<number>")5455		/// Reserved word followed by any non-alphanumberic56		rule reserved() = ("assert" / "else" / "error" / "false" / "for" / "function" / "if" / "import" / "importstr" / "importbin" / "in" / "local" / "null" / "tailstrict" / "then" / "self" / "super" / "true") end_of_ident()57		rule id() -> IStr = v:$(quiet!{ !reserved() alpha() (alpha() / digit())*} / expected!("<identifier>")) { v.into() }5859		rule keyword(id: &'static str) -> ()60			= #{|input, pos| input.parse_string_literal(pos, id)} end_of_ident()6162		pub rule param(s: &ParserSettings) -> ExprParam = destruct:destruct(s) default:(_ "=" _ default:expr(s){default})? { ExprParam { destruct, default } }63		pub rule params(s: &ParserSettings) -> ExprParams64			= params:param(s) ** comma() comma()? { ExprParams::new(params) }65			/ { ExprParams::new(Vec::new()) }6667		pub rule arg(s: &ParserSettings) -> (Option<IStr>, Expr)68			= name:(quiet! { (s:id() _ "=" !['='] _ {s})? } / expected!("<argument name>")) expr:expr(s) {(name, expr)}6970		pub rule args(s: &ParserSettings) -> ArgsDesc71			= args:arg(s)**comma() comma()? {?72				let unnamed_count = args.iter().take_while(|(n, _)| n.is_none()).count();73				let mut unnamed = Vec::with_capacity(unnamed_count);74				let mut names = Vec::with_capacity(args.len() - unnamed_count);75				let mut values = Vec::with_capacity(args.len() - unnamed_count);76				let mut named_started = false;77				for (name, value) in args {78					if let Some(name) = name {79						named_started = true;80						names.push(name);81						values.push(value);82					} else {83						if named_started {84							return Err("<named argument>")85						}86						unnamed.push(value);87					}88				}89				Ok(ArgsDesc{unnamed, names, values})90			}9192		pub rule destruct_rest() -> DestructRest93			= "..." into:(_ into:id() {into})? {into.map_or_else(|| DestructRest::Drop, DestructRest::Keep)}94		pub rule destruct_array(s: &ParserSettings) -> Destruct95			= "[" _ start:destruct(s)**comma() rest:(96				comma() _ rest:destruct_rest()? end:(97					comma() end:destruct(s)**comma() (_ comma())? {end}98					/ comma()? {Vec::new()}99				) {(rest, end)}100				/ comma()? {(None, Vec::new())}101			) _ "]" {?102				#[cfg(feature = "exp-destruct")] return Ok(Destruct::Array {103					start,104					rest: rest.0,105					end: rest.1,106				});107				#[cfg(not(feature = "exp-destruct"))] Err("!!!experimental destructuring was not enabled")108			}109		pub rule destruct_object(s: &ParserSettings) -> Destruct110			= "{" _111				fields:(name:id() into:(_ ":" _ into:destruct(s) {into})? default:(_ "=" _ v:spanned(<expr(s)>, s) {v})? {(name, into, default)})**comma()112				rest:(113					comma() rest:destruct_rest()? {rest}114					/ comma()? {None}115				)116			_ "}" {?117				#[cfg(feature = "exp-destruct")] return Ok(Destruct::Object {118					fields,119					rest,120				});121				#[cfg(not(feature = "exp-destruct"))] Err("!!!experimental destructuring was not enabled")122			}123		pub rule destruct(s: &ParserSettings) -> Destruct124			= v:spanned(<id()>, s) {Destruct::Full(v)}125			/ "?" {?126				#[cfg(feature = "exp-destruct")] return Ok(Destruct::Skip);127				#[cfg(not(feature = "exp-destruct"))] Err("!!!experimental destructuring was not enabled")128			}129			/ arr:destruct_array(s) {arr}130			/ obj:destruct_object(s) {obj}131132		pub rule bind(s: &ParserSettings) -> BindSpec133			= into:destruct(s) _ "=" _ value:expr(s) {BindSpec::Field{into, value}}134			/ name:id() _ "(" _ params:params(s) _ ")" _ "=" _ value:expr(s) {BindSpec::Function{name, params, value}}135136		pub rule assertion(s: &ParserSettings) -> AssertStmt137			= keyword("assert") _ assertion:spanned(<expr(s)>, s) message:(_ ":" _ e:expr(s) {e})? { AssertStmt{assertion, message} }138139		pub rule whole_line() -> &'input str140			= str:$((!['\n'][_])* "\n") {str}141		pub rule string_block() -> String142			= "|||" chomped:"-"? (!['\n']single_whitespace())* "\n"143			empty_lines:$(['\n']*)144			prefix:[' ' | '\t']+ first_line:whole_line()145			lines:("\n" {"\n"} / [' ' | '\t']*<{prefix.len()}> s:whole_line() {s})*146			[' ' | '\t']*<, {prefix.len() - 1}> "|||"147			{148				let mut l = empty_lines.to_owned();149				l.push_str(first_line);150				l.extend(lines);151				if chomped.is_some() {152					debug_assert!(l.ends_with('\n'));153					l.truncate(l.len() - 1);154				}155				l156			}157158		rule hex_char()159			= quiet! { ['0'..='9' | 'a'..='f' | 'A'..='F'] } / expected!("<hex char>")160161		rule string_char(c: rule<()>)162			= (!['\\']!c()[_])+163			/ "\\\\"164			/ "\\u" hex_char() hex_char() hex_char() hex_char()165			/ "\\x" hex_char() hex_char()166			/ ['\\'] (quiet! { ['b' | 'f' | 'n' | 'r' | 't' | '"' | '\''] } / expected!("<escape character>"))167		pub rule string() -> String168			= ['"'] str:$(string_char(<"\"">)*) ['"'] {? unescape::unescape(str).ok_or("<escaped string>")}169			/ ['\''] str:$(string_char(<"\'">)*) ['\''] {? unescape::unescape(str).ok_or("<escaped string>")}170			/ quiet!{ "@'" str:$(("''" / (!['\''][_]))*) "'" {str.replace("''", "'")}171			/ "@\"" str:$(("\"\"" / (!['"'][_]))*) "\"" {str.replace("\"\"", "\"")}172			/ string_block() } / expected!("<string>")173174		pub rule field_name(s: &ParserSettings) -> FieldName175			= name:id() {FieldName::Fixed(name)}176			/ name:string() {FieldName::Fixed(name.into())}177			/ "[" _ expr:expr(s) _ "]" {FieldName::Dyn(expr)}178		pub rule visibility() -> Visibility179			= ":::" {Visibility::Unhide}180			/ "::" {Visibility::Hidden}181			/ ":" {Visibility::Normal}182		pub rule field(s: &ParserSettings) -> FieldMember183			= name:spanned(<field_name(s)>, s) _ plus:"+"? _ visibility:visibility() _ value:expr(s) {FieldMember{184				name,185				plus: plus.is_some(),186				params: None,187				visibility,188				value,189			}}190			/ name:spanned(<field_name(s)>, s) _ "(" _ params:params(s) _ ")" _ visibility:visibility() _ value:expr(s) {FieldMember{191				name,192				plus: false,193				params: Some(params),194				visibility,195				value,196			}}197		pub rule obj_local(s: &ParserSettings) -> BindSpec198			= keyword("local") _ bind:bind(s) {bind}199		pub rule member(s: &ParserSettings) -> Member200			= bind:obj_local(s) {Member::BindStmt(bind)}201			/ assertion:assertion(s) {Member::AssertStmt(assertion)}202			/ field:field(s) {Member::Field(field)}203		pub rule objinside(s: &ParserSettings) -> ObjBody204			=  members:(member(s) ** comma()) comma()? _ compspecs:compspecs(s)? {?205				Ok(if let Some(compspecs) = compspecs {206					let mut locals = Vec::new();207					let mut field = None;208					for member in members {209						match member {210							Member::Field(field_member) => if field.replace(field_member).is_some() {211								return Err("<object comprehension can only contain one field>")212							},213							Member::BindStmt(bind_spec) => locals.push(bind_spec),214							Member::AssertStmt(assert_stmt) => return Err("<asserts are unsupported in object comprehension>"),215						}216					}217					ObjBody::ObjComp(ObjComp {218						locals,219						field: Box::new(field.ok_or("<missing object comprehension field>")?),220						compspecs221					})222				} else {223					let mut locals = Vec::new();224					let mut asserts = Vec::new();225					let mut fields = Vec::new();226					for member in members {227						match member {228							Member::Field(field_member) => fields.push(field_member),229							Member::BindStmt(bind_spec) => locals.push(bind_spec),230							Member::AssertStmt(assert_stmt) => asserts.push(assert_stmt),231						}232					}233					ObjBody::MemberList(ObjMembers {234						locals,235						asserts,236						fields237					})238				})239			}240		pub rule ifspec(s: &ParserSettings) -> IfSpecData241			= i:spanned(<keyword("if")>, s) _ cond:expr(s) {IfSpecData { span: i.span, cond }}242		pub rule forspec(s: &ParserSettings) -> ForSpecData243			= keyword("for") _ destruct:destruct(s) _ keyword("in") _ over:expr(s) { ForSpecData { destruct, over } }244		rule ensure_object_iteration()245			= "" {?246				#[cfg(not(feature = "exp-object-iteration"))] return Err("!!!experimental object iteration was not enabled");247				#[cfg(feature = "exp-object-iteration")] Ok(())248			}249		pub rule forobjspec(s: &ParserSettings) -> CompSpec250			= ensure_object_iteration() keyword("for") _ "[" _ key:id() _ "]" _ vis:visibility() _ value:destruct(s) _ keyword("in") _ over:expr(s) {251				#[cfg(feature = "exp-object-iteration")] return CompSpec::ForObjSpec(jrsonnet_ir::ForObjSpecData { key, visibility: vis, value, over });252				#[cfg(not(feature = "exp-object-iteration"))] unreachable!("ensure_object_iteration will fail if feature is not enabled")253			}254		rule compspec(s: &ParserSettings) -> CompSpec255			= i:ifspec(s) { CompSpec::IfSpec(i) } / f:forobjspec(s) { f } / f:forspec(s) {CompSpec::ForSpec(f)}256		pub rule compspecs(s: &ParserSettings) -> Vec<CompSpec>257			= specs:compspec(s) ++ _ {?258				if matches!(specs[0], CompSpec::IfSpec(_)) {259					return Err("<first compspec should be for>")260				}261				Ok(specs)262			}263		pub rule local_expr(s: &ParserSettings) -> Expr264			= keyword("local") _ binds:bind(s) ** comma() (_ ",")? _ ";" _ expr:expr(s) { Expr::LocalExpr(binds, Box::new(expr)) }265		pub rule string_expr(s: &ParserSettings) -> Expr266			= s:string() {Expr::Str(s.into())}267		pub rule obj_expr(s: &ParserSettings) -> Expr268			= "{" _ body:objinside(s) _ "}" {Expr::Obj(body)}269		pub rule array_expr(s: &ParserSettings) -> Expr270			= "[" _ elems:(expr(s) ** comma()) _ comma()? "]" {Expr::Arr(elems)}271		pub rule array_comp_expr(s: &ParserSettings) -> Expr272			= "[" _ expr:expr(s) _ comma()? _ specs:(r: compspecs(s) _ {r}) "]" {273				Expr::ArrComp(Box::new(expr), specs)274			}275		pub rule number_expr(s: &ParserSettings) -> Expr276			= n:number() {? if let Some(n) = NumValue::new(n) {277				Ok(Expr::Num(n))278			} else {279				Err("!!!numbers are finite")280			}}281282		rule spanned<T: Acyclic>(x: rule<T>, s: &ParserSettings) -> Spanned<T>283			= a:position!() n:x() b:position!() { Spanned::new(n, Span(s.source.clone(), a as u32, b as u32)) }284285		pub rule var_expr(s: &ParserSettings) -> Expr286			= n:spanned(<id()>, s) { Expr::Var(n) }287		pub rule id_loc(s: &ParserSettings) -> Spanned<Expr>288			= a:position!() n:id() b:position!() { Spanned::new(Expr::Str(n), Span(s.source.clone(), a as u32,b as u32)) }289		pub rule if_then_else_expr(s: &ParserSettings) -> Expr290			= cond:ifspec(s) _ keyword("then") _ cond_then:expr(s) cond_else:(_ keyword("else") _ e:expr(s) {e})? {Expr::IfElse(Box::new(IfElse{291				cond,292				cond_then,293				cond_else,294			}))}295296		pub rule literal(s: &ParserSettings) -> Expr297			= v:(298				keyword("null") {LiteralType::Null}299				/ keyword("true") {LiteralType::True}300				/ keyword("false") {LiteralType::False}301				/ keyword("self") {LiteralType::This}302				/ keyword("$") {LiteralType::Dollar}303				/ keyword("super") {LiteralType::Super}304			) {Expr::Literal(v)}305306		rule import_kind() -> ImportKind307			= keyword("importstr") { ImportKind::Str }308			/ keyword("importbin") { ImportKind::Bin }309			/ keyword("import") { ImportKind::Normal }310311		pub rule expr_basic(s: &ParserSettings) -> Expr312			= literal(s)313314			/ string_expr(s) / number_expr(s)315			/ array_expr(s)316			/ obj_expr(s)317			/ array_expr(s)318			/ array_comp_expr(s)319320			/ kind:spanned(<import_kind()>, s) _ path:expr(s) {Expr::Import(kind, Box::new(path))}321322			/ var_expr(s)323			/ local_expr(s)324			/ if_then_else_expr(s)325326			/ keyword("function") _ "(" _ params:params(s) _ ")" _ expr:expr(s) {Expr::Function(params, Box::new(expr))}327			/ assert:assertion(s) _ ";" _ rest:expr(s) { Expr::AssertExpr(Box::new(AssertExpr{328				assert, rest329			})) }330331			/ err_kw:spanned(<keyword("error")>, s) _ expr:expr(s) { Expr::ErrorStmt(err_kw.span, Box::new(expr)) }332333		rule slice_part(s: &ParserSettings) -> Option<Spanned<Expr>>334			= _ e:(e:spanned(<expr(s)>, s) _{e})? {e}335		pub rule slice_desc(s: &ParserSettings) -> SliceDesc336			= start:slice_part(s) ":" pair:(end:slice_part(s) step:(":" e:slice_part(s){e})? {(end, step.flatten())})? {337				let (end, step) = if let Some((end, step)) = pair {338					(end, step)339				}else{340					(None, None)341				};342343				SliceDesc { start, end, step }344			}345346		rule binop(x: rule<()>) -> ()347			= quiet!{ x() } / expected!("<binary op>")348		rule unaryop(x: rule<()>) -> ()349			= quiet!{ x() } / expected!("<unary op>")350351		rule ensure_null_coaelse()352			= "" {?353				#[cfg(not(feature = "exp-null-coaelse"))] return Err("!!!experimental null coaelscing was not enabled");354				#[cfg(feature = "exp-null-coaelse")] Ok(())355			}356		use jrsonnet_ir::BinaryOpType::*;357		use jrsonnet_ir::UnaryOpType::*;358		rule expr(s: &ParserSettings) -> Expr359			= precedence! {360				a:(@) _ binop(<"||">) _ b:@ {expr_bin!(a Or b)}361				a:(@) _ binop(<"??">) _ ensure_null_coaelse() b:@ {362					#[cfg(feature = "exp-null-coaelse")] return expr_bin!(a NullCoaelse b);363					unreachable!("ensure_null_coaelse will fail if feature is not enabled")364				}365				--366				a:(@) _ binop(<"&&">) _ b:@ {expr_bin!(a And b)}367				--368				a:(@) _ binop(<"|">) _ b:@ {expr_bin!(a BitOr b)}369				--370				a:@ _ binop(<"^">) _ b:(@) {expr_bin!(a BitXor b)}371				--372				a:(@) _ binop(<"&">) _ b:@ {expr_bin!(a BitAnd b)}373				--374				a:(@) _ binop(<"==">) _ b:@ {expr_bin!(a Eq b)}375				a:(@) _ binop(<"!=">) _ b:@ {expr_bin!(a Neq b)}376				--377				a:(@) _ binop(<"<">) _ b:@ {expr_bin!(a Lt b)}378				a:(@) _ binop(<">">) _ b:@ {expr_bin!(a Gt b)}379				a:(@) _ binop(<"<=">) _ b:@ {expr_bin!(a Lte b)}380				a:(@) _ binop(<">=">) _ b:@ {expr_bin!(a Gte b)}381				a:(@) _ binop(<keyword("in")>) _ b:@ {expr_bin!(a In b)}382				--383				a:(@) _ binop(<"<<">) _ b:@ {expr_bin!(a Lhs b)}384				a:(@) _ binop(<">>">) _ b:@ {expr_bin!(a Rhs b)}385				--386				a:(@) _ binop(<"+">) _ b:@ {expr_bin!(a Add b)}387				a:(@) _ binop(<"-">) _ b:@ {expr_bin!(a Sub b)}388				--389				a:(@) _ binop(<"*">) _ b:@ {expr_bin!(a Mul b)}390				a:(@) _ binop(<"/">) _ b:@ {expr_bin!(a Div b)}391				a:(@) _ binop(<"%">) _ b:@ {expr_bin!(a Mod b)}392				--393						unaryop(<"+">) _ b:@ {expr_un!(Plus b)}394						unaryop(<"-">) _ b:@ {expr_un!(Minus b)}395						unaryop(<"!">) _ b:@ {expr_un!(Not b)}396						unaryop(<"~">) _ b:@ {expr_un!(BitNot b)}397				--398				value:(@) _ "[" _ slice:slice_desc(s) _ "]" {Expr::Slice(Box::new(Slice{value, slice}))}399				indexable:(@) _ parts:index_part(s)+ {Expr::Index{indexable: Box::new(indexable), parts}}400				a:(@) _ args:spanned(<"(" _ a:args(s) _ ")" {a}>, s) ts:(_ keyword("tailstrict"))? {Expr::Apply(Box::new(a), args, ts.is_some())}401				a:(@) _ "{" _ body:objinside(s) _ "}" {Expr::ObjExtend(Box::new(a), body)}402				--403				e:expr_basic(s) {e}404				"(" _ e:expr(s) _ ")" {e}405			}406		pub rule index_part(s: &ParserSettings) -> IndexPart407		= n:("?" _ ensure_null_coaelse())? "." _ value:id_loc(s) {IndexPart {408			span: value.span,409			value: value.value,410			#[cfg(feature = "exp-null-coaelse")]411			null_coaelse: n.is_some(),412		}}413		/ n:("?" _ "." _ ensure_null_coaelse())? value:spanned(<"[" _ v:expr(s) _ "]" {v}>, s) {IndexPart {414			span: value.span,415			value: value.value,416			#[cfg(feature = "exp-null-coaelse")]417			null_coaelse: n.is_some(),418		}}419420		pub rule jsonnet(s: &ParserSettings) -> Expr = _ e:expr(s) _ {e}421	}422}423424pub type ParseError = peg::error::ParseError<peg::str::LineCol>;425pub fn parse(str: &str, settings: &ParserSettings) -> Result<Expr, ParseError> {426	jsonnet_parser::jsonnet(str, settings)427}428/// Used for importstr values429pub fn string_to_expr(str: IStr, settings: &ParserSettings) -> Spanned<Expr> {430	let len = str.len();431	Spanned::new(Expr::Str(str), Span(settings.source.clone(), 0, len as u32))432}433434#[cfg(test)]435mod tests {436	#[test]437	#[cfg(not(feature = "exp-null-coaelse"))]438	fn snapshots() {439		use std::fs;440441		use insta::{assert_snapshot, glob};442		use jrsonnet_ir::{IStr, Source};443444		use crate::{ParserSettings, parse};445446		glob!("tests/*.jsonnet", |path| {447			let input = fs::read_to_string(path).expect("read test file");448			let v = parse(449				&input,450				&ParserSettings {451					source: Source::new_virtual("<test>".into(), IStr::empty()),452				},453			)454			.unwrap();455			let v = format!("{v:#?}");456			assert_snapshot!(v);457		});458	}459}
after · crates/jrsonnet-peg-parser/src/lib.rs
1use jrsonnet_gcmodule::Acyclic;2use jrsonnet_ir::{3	ArgsDesc, AssertExpr, AssertStmt, BinaryOp, BindSpec, CompSpec, Destruct, DestructRest, Expr,4	ExprParam, ExprParams, FieldMember, FieldName, ForSpecData, IStr, IfElse, IfSpecData,5	ImportKind, IndexPart, LiteralType, Member, NumValue, ObjBody, ObjComp, ObjMembers, Slice,6	SliceDesc, Source, Span, Spanned, Visibility, unescape,7};8use peg::parser;910pub struct ParserSettings {11	pub source: Source,12}1314macro_rules! expr_bin {15	($a:ident $op:ident $b:ident) => {16		Expr::BinaryOp(Box::new(BinaryOp {17			lhs: $a,18			op: $op,19			rhs: $b,20		}))21	};22}23macro_rules! expr_un {24	($op:ident $a:ident) => {25		Expr::UnaryOp($op, Box::new($a))26	};27}2829parser! {30	pub grammar jsonnet_parser() for str {31		use peg::ParseLiteral;3233		rule eof() = quiet!{![_]} / expected!("<eof>")34		rule eol() = "\n" / eof()3536		/// Standard C-like comments37		rule comment()38			= "//" (!eol()[_])* eol()39			/ "/*" (!("*/")[_])* "*/"40			/ "#" (!eol()[_])* eol()4142		rule single_whitespace() = quiet!{([' ' | '\r' | '\n' | '\t'] / comment())} / expected!("<whitespace>")43		rule _() = quiet!{([' ' | '\r' | '\n' | '\t']+) / comment()}* / expected!("<whitespace>")4445		/// For comma-delimited elements46		rule comma() = quiet!{_ "," _} / expected!("<comma>")47		rule alpha() -> char = c:$(['_' | 'a'..='z' | 'A'..='Z']) {c.chars().next().unwrap()}48		rule digit() -> char = d:$(['0'..='9']) {d.chars().next().unwrap()}49		rule end_of_ident() = !['0'..='9' | '_' | 'a'..='z' | 'A'..='Z']50		/// Sequence of digits51		rule uint_str() -> &'input str = a:$(digit()+ ("_" digit()+)*) { a }52		/// Number in scientific notation format53		rule number() -> f64 = quiet!{a:$(uint_str() ("." uint_str())? (['e'|'E'] (s:['+'|'-'])? uint_str())?) {? a.replace('_',"").parse().map_err(|_| "<number>") }} / expected!("<number>")5455		/// Reserved word followed by any non-alphanumberic56		rule reserved() = ("assert" / "else" / "error" / "false" / "for" / "function" / "if" / "import" / "importstr" / "importbin" / "in" / "local" / "null" / "tailstrict" / "then" / "self" / "super" / "true") end_of_ident()57		rule id() -> IStr = v:$(quiet!{ !reserved() alpha() (alpha() / digit())*} / expected!("<identifier>")) { v.into() }5859		rule keyword(id: &'static str) -> ()60			= #{|input, pos| input.parse_string_literal(pos, id)} end_of_ident()6162		pub rule param(s: &ParserSettings) -> ExprParam = destruct:destruct(s) default:(_ "=" _ default:expr(s){default})? { ExprParam { destruct, default } }63		pub rule params(s: &ParserSettings) -> ExprParams64			= params:param(s) ** comma() comma()? { ExprParams::new(params) }65			/ { ExprParams::new(Vec::new()) }6667		pub rule arg(s: &ParserSettings) -> (Option<IStr>, Expr)68			= name:(quiet! { (s:id() _ "=" !['='] _ {s})? } / expected!("<argument name>")) expr:expr(s) {(name, expr)}6970		pub rule args(s: &ParserSettings) -> ArgsDesc71			= args:arg(s)**comma() comma()? {?72				let unnamed_count = args.iter().take_while(|(n, _)| n.is_none()).count();73				let mut unnamed = Vec::with_capacity(unnamed_count);74				let mut names = Vec::with_capacity(args.len() - unnamed_count);75				let mut values = Vec::with_capacity(args.len() - unnamed_count);76				let mut named_started = false;77				for (name, value) in args {78					if let Some(name) = name {79						named_started = true;80						names.push(name);81						values.push(value);82					} else {83						if named_started {84							return Err("<named argument>")85						}86						unnamed.push(value);87					}88				}89				Ok(ArgsDesc{unnamed, names, values})90			}9192		pub rule destruct_rest() -> DestructRest93			= "..." into:(_ into:id() {into})? {into.map_or_else(|| DestructRest::Drop, DestructRest::Keep)}94		pub rule destruct_array(s: &ParserSettings) -> Destruct95			= "[" _ start:destruct(s)**comma() rest:(96				comma() _ rest:destruct_rest()? end:(97					comma() end:destruct(s)**comma() (_ comma())? {end}98					/ comma()? {Vec::new()}99				) {(rest, end)}100				/ comma()? {(None, Vec::new())}101			) _ "]" {?102				#[cfg(feature = "exp-destruct")] return Ok(Destruct::Array {103					start,104					rest: rest.0,105					end: rest.1,106				});107				#[cfg(not(feature = "exp-destruct"))] Err("!!!experimental destructuring was not enabled")108			}109		pub rule destruct_object(s: &ParserSettings) -> Destruct110			= "{" _111				fields:(name:id() into:(_ ":" _ into:destruct(s) {into})? default:(_ "=" _ v:spanned(<expr(s)>, s) {v})? {(name, into, default)})**comma()112				rest:(113					comma() rest:destruct_rest()? {rest}114					/ comma()? {None}115				)116			_ "}" {?117				#[cfg(feature = "exp-destruct")] return Ok(Destruct::Object {118					fields,119					rest,120				});121				#[cfg(not(feature = "exp-destruct"))] Err("!!!experimental destructuring was not enabled")122			}123		pub rule destruct(s: &ParserSettings) -> Destruct124			= v:spanned(<id()>, s) {Destruct::Full(v)}125			/ "?" {?126				#[cfg(feature = "exp-destruct")] return Ok(Destruct::Skip);127				#[cfg(not(feature = "exp-destruct"))] Err("!!!experimental destructuring was not enabled")128			}129			/ arr:destruct_array(s) {arr}130			/ obj:destruct_object(s) {obj}131132		pub rule bind(s: &ParserSettings) -> BindSpec133			= into:destruct(s) _ "=" _ value:expr(s) {BindSpec::Field{into, value}}134			/ name:id() _ "(" _ params:params(s) _ ")" _ "=" _ value:expr(s) {BindSpec::Function{name, params, value}}135136		pub rule assertion(s: &ParserSettings) -> AssertStmt137			= keyword("assert") _ assertion:spanned(<expr(s)>, s) message:(_ ":" _ e:expr(s) {e})? { AssertStmt{assertion, message} }138139		pub rule whole_line() -> &'input str140			= str:$((!['\n'][_])* "\n") {str}141		pub rule string_block() -> String142			= "|||" chomped:"-"? (!['\n']single_whitespace())* "\n"143			empty_lines:$(['\n']*)144			prefix:[' ' | '\t']+ first_line:whole_line()145			lines:("\n" {"\n"} / [' ' | '\t']*<{prefix.len()}> s:whole_line() {s})*146			[' ' | '\t']*<, {prefix.len() - 1}> "|||"147			{148				let mut l = empty_lines.to_owned();149				l.push_str(first_line);150				l.extend(lines);151				if chomped.is_some() {152					debug_assert!(l.ends_with('\n'));153					l.truncate(l.len() - 1);154				}155				l156			}157158		rule hex_char()159			= quiet! { ['0'..='9' | 'a'..='f' | 'A'..='F'] } / expected!("<hex char>")160161		rule string_char(c: rule<()>)162			= (!['\\']!c()[_])+163			/ "\\\\"164			/ "\\u" hex_char() hex_char() hex_char() hex_char()165			/ "\\x" hex_char() hex_char()166			/ ['\\'] (quiet! { ['b' | 'f' | 'n' | 'r' | 't' | '"' | '\''] } / expected!("<escape character>"))167		pub rule string() -> String168			= ['"'] str:$(string_char(<"\"">)*) ['"'] {? unescape::unescape(str).ok_or("<escaped string>")}169			/ ['\''] str:$(string_char(<"\'">)*) ['\''] {? unescape::unescape(str).ok_or("<escaped string>")}170			/ quiet!{ "@'" str:$(("''" / (!['\''][_]))*) "'" {str.replace("''", "'")}171			/ "@\"" str:$(("\"\"" / (!['"'][_]))*) "\"" {str.replace("\"\"", "\"")}172			/ string_block() } / expected!("<string>")173174		pub rule field_name(s: &ParserSettings) -> FieldName175			= name:id() {FieldName::Fixed(name)}176			/ name:string() {FieldName::Fixed(name.into())}177			/ "[" _ expr:expr(s) _ "]" {FieldName::Dyn(expr)}178		pub rule visibility() -> Visibility179			= ":::" {Visibility::Unhide}180			/ "::" {Visibility::Hidden}181			/ ":" {Visibility::Normal}182		pub rule field(s: &ParserSettings) -> FieldMember183			= name:spanned(<field_name(s)>, s) _ plus:"+"? _ visibility:visibility() _ value:expr(s) {FieldMember{184				name,185				plus: plus.is_some(),186				params: None,187				visibility,188				value,189			}}190			/ name:spanned(<field_name(s)>, s) _ "(" _ params:params(s) _ ")" _ visibility:visibility() _ value:expr(s) {FieldMember{191				name,192				plus: false,193				params: Some(params),194				visibility,195				value,196			}}197		pub rule obj_local(s: &ParserSettings) -> BindSpec198			= keyword("local") _ bind:bind(s) {bind}199		pub rule member(s: &ParserSettings) -> Member200			= bind:obj_local(s) {Member::BindStmt(bind)}201			/ assertion:assertion(s) {Member::AssertStmt(assertion)}202			/ field:field(s) {Member::Field(field)}203		pub rule objinside(s: &ParserSettings) -> ObjBody204			=  members:(member(s) ** comma()) comma()? _ compspecs:compspecs(s)? {?205				Ok(if let Some(compspecs) = compspecs {206					let mut locals = Vec::new();207					let mut field = None;208					for member in members {209						match member {210							Member::Field(field_member) => if field.replace(field_member).is_some() {211								return Err("<object comprehension can only contain one field>")212							},213							Member::BindStmt(bind_spec) => locals.push(bind_spec),214							Member::AssertStmt(assert_stmt) => return Err("<asserts are unsupported in object comprehension>"),215						}216					}217					ObjBody::ObjComp(ObjComp {218						locals,219						field: Box::new(field.ok_or("<missing object comprehension field>")?),220						compspecs221					})222				} else {223					let mut locals = Vec::new();224					let mut asserts = Vec::new();225					let mut fields = Vec::new();226					for member in members {227						match member {228							Member::Field(field_member) => fields.push(field_member),229							Member::BindStmt(bind_spec) => locals.push(bind_spec),230							Member::AssertStmt(assert_stmt) => asserts.push(assert_stmt),231						}232					}233					ObjBody::MemberList(ObjMembers {234						locals,235						asserts,236						fields237					})238				})239			}240		pub rule ifspec(s: &ParserSettings) -> IfSpecData241			= i:spanned(<keyword("if")>, s) _ cond:expr(s) {IfSpecData { span: i.span, cond }}242		pub rule forspec(s: &ParserSettings) -> ForSpecData243			= keyword("for") _ destruct:destruct(s) _ keyword("in") _ over:expr(s) { ForSpecData { destruct, over } }244		rule ensure_object_iteration()245			= "" {?246				#[cfg(not(feature = "exp-object-iteration"))] return Err("!!!experimental object iteration was not enabled");247				#[cfg(feature = "exp-object-iteration")] Ok(())248			}249		pub rule forobjspec(s: &ParserSettings) -> CompSpec250			= ensure_object_iteration() keyword("for") _ "[" _ key:id() _ "]" _ vis:visibility() _ value:destruct(s) _ keyword("in") _ over:expr(s) {251				#[cfg(feature = "exp-object-iteration")] return CompSpec::ForObjSpec(jrsonnet_ir::ForObjSpecData { key, visibility: vis, value, over });252				#[cfg(not(feature = "exp-object-iteration"))] unreachable!("ensure_object_iteration will fail if feature is not enabled")253			}254		rule compspec(s: &ParserSettings) -> CompSpec255			= i:ifspec(s) { CompSpec::IfSpec(i) } / f:forobjspec(s) { f } / f:forspec(s) {CompSpec::ForSpec(f)}256		pub rule compspecs(s: &ParserSettings) -> Vec<CompSpec>257			= specs:compspec(s) ++ _ {?258				if matches!(specs[0], CompSpec::IfSpec(_)) {259					return Err("<first compspec should be for>")260				}261				Ok(specs)262			}263		pub rule local_expr(s: &ParserSettings) -> Expr264			= keyword("local") _ binds:bind(s) ** comma() (_ ",")? _ ";" _ expr:expr(s) { Expr::LocalExpr(binds, Box::new(expr)) }265		pub rule string_expr(s: &ParserSettings) -> Expr266			= s:string() {Expr::Str(s.into())}267		pub rule obj_expr(s: &ParserSettings) -> Expr268			= "{" _ body:objinside(s) _ "}" {Expr::Obj(body)}269		pub rule array_expr(s: &ParserSettings) -> Expr270			= "[" _ elems:(expr(s) ** comma()) _ comma()? "]" {Expr::Arr(elems)}271		pub rule array_comp_expr(s: &ParserSettings) -> Expr272			= "[" _ expr:expr(s) _ comma()? _ specs:(r: compspecs(s) _ {r}) "]" {273				Expr::ArrComp(Box::new(expr), specs)274			}275		pub rule number_expr(s: &ParserSettings) -> Expr276			= n:number() {? NumValue::new(n).map_or_else(|| Err("!!!numbers are finite"), |n| Ok(Expr::Num(n)))}277278		rule spanned<T: Acyclic>(x: rule<T>, s: &ParserSettings) -> Spanned<T>279			= a:position!() n:x() b:position!() { Spanned::new(n, Span(s.source.clone(), codeidx(a), codeidx(b))) }280281		pub rule var_expr(s: &ParserSettings) -> Expr282			= n:spanned(<id()>, s) { Expr::Var(n) }283		pub rule id_loc(s: &ParserSettings) -> Spanned<Expr>284			= a:position!() n:id() b:position!() { Spanned::new(Expr::Str(n), Span(s.source.clone(), codeidx(a), codeidx(b))) }285		pub rule if_then_else_expr(s: &ParserSettings) -> Expr286			= cond:ifspec(s) _ keyword("then") _ cond_then:expr(s) cond_else:(_ keyword("else") _ e:expr(s) {e})? {Expr::IfElse(Box::new(IfElse{287				cond,288				cond_then,289				cond_else,290			}))}291292		pub rule literal(s: &ParserSettings) -> Expr293			= v:(294				keyword("null") {LiteralType::Null}295				/ keyword("true") {LiteralType::True}296				/ keyword("false") {LiteralType::False}297				/ keyword("self") {LiteralType::This}298				/ keyword("$") {LiteralType::Dollar}299				/ keyword("super") {LiteralType::Super}300			) {Expr::Literal(v)}301302		rule import_kind() -> ImportKind303			= keyword("importstr") { ImportKind::Str }304			/ keyword("importbin") { ImportKind::Bin }305			/ keyword("import") { ImportKind::Normal }306307		pub rule expr_basic(s: &ParserSettings) -> Expr308			= literal(s)309310			/ string_expr(s) / number_expr(s)311			/ array_expr(s)312			/ obj_expr(s)313			/ array_expr(s)314			/ array_comp_expr(s)315316			/ kind:spanned(<import_kind()>, s) _ path:expr(s) {Expr::Import(kind, Box::new(path))}317318			/ var_expr(s)319			/ local_expr(s)320			/ if_then_else_expr(s)321322			/ keyword("function") _ "(" _ params:params(s) _ ")" _ expr:expr(s) {Expr::Function(params, Box::new(expr))}323			/ assert:assertion(s) _ ";" _ rest:expr(s) { Expr::AssertExpr(Box::new(AssertExpr{324				assert, rest325			})) }326327			/ err_kw:spanned(<keyword("error")>, s) _ expr:expr(s) { Expr::ErrorStmt(err_kw.span, Box::new(expr)) }328329		rule slice_part(s: &ParserSettings) -> Option<Spanned<Expr>>330			= _ e:(e:spanned(<expr(s)>, s) _{e})? {e}331		pub rule slice_desc(s: &ParserSettings) -> SliceDesc332			= start:slice_part(s) ":" pair:(end:slice_part(s) step:(":" e:slice_part(s){e})? {(end, step.flatten())})? {333				let (end, step) = if let Some((end, step)) = pair {334					(end, step)335				}else{336					(None, None)337				};338339				SliceDesc { start, end, step }340			}341342		rule binop(x: rule<()>) -> ()343			= quiet!{ x() } / expected!("<binary op>")344		rule unaryop(x: rule<()>) -> ()345			= quiet!{ x() } / expected!("<unary op>")346347		rule ensure_null_coaelse()348			= "" {?349				#[cfg(not(feature = "exp-null-coaelse"))] return Err("!!!experimental null coaelscing was not enabled");350				#[cfg(feature = "exp-null-coaelse")] Ok(())351			}352		use jrsonnet_ir::BinaryOpType::*;353		use jrsonnet_ir::UnaryOpType::*;354		rule expr(s: &ParserSettings) -> Expr355			= precedence! {356				a:(@) _ binop(<"||">) _ b:@ {expr_bin!(a Or b)}357				a:(@) _ binop(<"??">) _ ensure_null_coaelse() b:@ {358					#[cfg(feature = "exp-null-coaelse")] return expr_bin!(a NullCoaelse b);359					unreachable!("ensure_null_coaelse will fail if feature is not enabled")360				}361				--362				a:(@) _ binop(<"&&">) _ b:@ {expr_bin!(a And b)}363				--364				a:(@) _ binop(<"|">) _ b:@ {expr_bin!(a BitOr b)}365				--366				a:@ _ binop(<"^">) _ b:(@) {expr_bin!(a BitXor b)}367				--368				a:(@) _ binop(<"&">) _ b:@ {expr_bin!(a BitAnd b)}369				--370				a:(@) _ binop(<"==">) _ b:@ {expr_bin!(a Eq b)}371				a:(@) _ binop(<"!=">) _ b:@ {expr_bin!(a Neq b)}372				--373				a:(@) _ binop(<"<">) _ b:@ {expr_bin!(a Lt b)}374				a:(@) _ binop(<">">) _ b:@ {expr_bin!(a Gt b)}375				a:(@) _ binop(<"<=">) _ b:@ {expr_bin!(a Lte b)}376				a:(@) _ binop(<">=">) _ b:@ {expr_bin!(a Gte b)}377				a:(@) _ binop(<keyword("in")>) _ b:@ {expr_bin!(a In b)}378				--379				a:(@) _ binop(<"<<">) _ b:@ {expr_bin!(a Lhs b)}380				a:(@) _ binop(<">>">) _ b:@ {expr_bin!(a Rhs b)}381				--382				a:(@) _ binop(<"+">) _ b:@ {expr_bin!(a Add b)}383				a:(@) _ binop(<"-">) _ b:@ {expr_bin!(a Sub b)}384				--385				a:(@) _ binop(<"*">) _ b:@ {expr_bin!(a Mul b)}386				a:(@) _ binop(<"/">) _ b:@ {expr_bin!(a Div b)}387				a:(@) _ binop(<"%">) _ b:@ {expr_bin!(a Mod b)}388				--389						unaryop(<"+">) _ b:@ {expr_un!(Plus b)}390						unaryop(<"-">) _ b:@ {expr_un!(Minus b)}391						unaryop(<"!">) _ b:@ {expr_un!(Not b)}392						unaryop(<"~">) _ b:@ {expr_un!(BitNot b)}393				--394				value:(@) _ "[" _ slice:slice_desc(s) _ "]" {Expr::Slice(Box::new(Slice{value, slice}))}395				indexable:(@) _ parts:index_part(s)+ {Expr::Index{indexable: Box::new(indexable), parts}}396				a:(@) _ args:spanned(<"(" _ a:args(s) _ ")" {a}>, s) ts:(_ keyword("tailstrict"))? {Expr::Apply(Box::new(a), args, ts.is_some())}397				a:(@) _ "{" _ body:objinside(s) _ "}" {Expr::ObjExtend(Box::new(a), body)}398				--399				e:expr_basic(s) {e}400				"(" _ e:expr(s) _ ")" {e}401			}402		pub rule index_part(s: &ParserSettings) -> IndexPart403		= n:("?" _ ensure_null_coaelse())? "." _ value:id_loc(s) {IndexPart {404			span: value.span,405			value: value.value,406			#[cfg(feature = "exp-null-coaelse")]407			null_coaelse: n.is_some(),408		}}409		/ n:("?" _ "." _ ensure_null_coaelse())? value:spanned(<"[" _ v:expr(s) _ "]" {v}>, s) {IndexPart {410			span: value.span,411			value: value.value,412			#[cfg(feature = "exp-null-coaelse")]413			null_coaelse: n.is_some(),414		}}415416		pub rule jsonnet(s: &ParserSettings) -> Expr = _ e:expr(s) _ {e}417	}418}419420fn codeidx(i: usize) -> u32 {421	u32::try_from(i).expect("code has 4g hard limit")422}423424pub type ParseError = peg::error::ParseError<peg::str::LineCol>;425pub fn parse(str: &str, settings: &ParserSettings) -> Result<Expr, ParseError> {426	jsonnet_parser::jsonnet(str, settings)427}428/// Used for importstr values429pub fn string_to_expr(str: IStr, settings: &ParserSettings) -> Spanned<Expr> {430	let len = str.len();431	Spanned::new(432		Expr::Str(str),433		Span(settings.source.clone(), 0, codeidx(len)),434	)435}436437#[cfg(test)]438mod tests {439	#[test]440	#[cfg(not(feature = "exp-null-coaelse"))]441	fn snapshots() {442		use std::fs;443444		use insta::{assert_snapshot, glob};445		use jrsonnet_ir::{IStr, Source};446447		use crate::{ParserSettings, parse};448449		glob!("tests/*.jsonnet", |path| {450			let input = fs::read_to_string(path).expect("read test file");451			let v = parse(452				&input,453				&ParserSettings {454					source: Source::new_virtual("<test>".into(), IStr::empty()),455				},456			)457			.unwrap();458			let v = format!("{v:#?}");459			assert_snapshot!(v);460		});461	}462}
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));