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
before · crates/jrsonnet-formatter/src/lib.rs
1use std::{any::type_name, rc::Rc};23use children::{children_between, trivia_before};4use dprint_core::formatting::{5	ConditionResolver, ConditionResolverContext, LineNumber, PrintItems, PrintOptions,6	condition_helpers::is_multiple_lines,7	condition_resolvers::true_resolver,8	ir_helpers::{new_line_group, with_indent},9};10use hi_doc::{Formatting, SnippetBuilder};11use jrsonnet_lexer::collect_lexed_str_block;12use jrsonnet_rowan_parser::{13	AstNode, AstToken as _, SyntaxToken,14	nodes::{15		Arg, ArgsDesc, Assertion, BinaryOperator, Bind, CompSpec, Destruct, DestructArrayPart,16		DestructRest, Expr, ExprArray, ExprBase, FieldName, ForObjSpec, ForSpec, IfSpec,17		ImportKind, Literal, Member, Name, Number, ObjBody, ObjLocal, ParamsDesc, SliceDesc,18		SourceFile, Stmt, Suffix, Text, TextKind, UnaryOperator, Visibility,19	},20};2122use crate::{23	children::{Child, EndingComments, trivia_after},24	comments::{CommentLocation, format_comments},25};2627mod children;28mod comments;29mod tests;3031fn with_indent_eoi(cond: ConditionResolver, o: PrintItems, e: EndingComments) -> PrintItems {32	let end_comments_items = {33		let mut items = PrintItems::new();34		if e.should_start_with_newline {35			p!(&mut items, nl);36		}37		format_comments(&e.trivia, CommentLocation::EndOfItems, &mut items);38		items.into_rc_path()39	};40	let items = new_line_group(pi!(@i; items(o) items(end_comments_items.into()))).into_rc_path();4142	let indented = with_indent(pi!(@i; nl items(items.into())));4344	pi!(@i; if_else("indented body", cond, items(indented))(str(" ") items(items.into())))45}4647pub trait Printable {48	fn print(&self, out: &mut PrintItems);49}5051macro_rules! pi {52	(@i; $($t:tt)*) => {{53		#[allow(unused_mut)]54		let mut o = dprint_core::formatting::PrintItems::new();55		pi!(@s; o: $($t)*);56		o57	}};58	(@s; $o:ident: str($e:expr $(,)?) $($t:tt)*) => {{59		$o.push_string($e.to_owned());60		pi!(@s; $o: $($t)*);61	}};62	(@s; $o:ident: string($e:expr $(,)?) $($t:tt)*) => {{63		$o.push_string($e);64		pi!(@s; $o: $($t)*);65	}};66	(@s; $o:ident: nl $($t:tt)*) => {{67		$o.push_signal(dprint_core::formatting::Signal::NewLine);68		pi!(@s; $o: $($t)*);69	}};70	(@s; $o:ident: sonl $($t:tt)*) => {{71		$o.push_signal(dprint_core::formatting::Signal::SpaceOrNewLine);72		pi!(@s; $o: $($t)*);73	}};74	(@s; $o:ident: tab $($t:tt)*) => {{75		$o.push_signal(dprint_core::formatting::Signal::Tab);76		pi!(@s; $o: $($t)*);77	}};78	(@s; $o:ident: >i $($t:tt)*) => {{79		$o.push_signal(dprint_core::formatting::Signal::StartIndent);80		pi!(@s; $o: $($t)*);81	}};82	(@s; $o:ident: <i $($t:tt)*) => {{83		$o.push_signal(dprint_core::formatting::Signal::FinishIndent);84		pi!(@s; $o: $($t)*);85	}};86	(@s; $o:ident: >ii $($t:tt)*) => {{87		$o.push_signal(dprint_core::formatting::Signal::StartIgnoringIndent);88		pi!(@s; $o: $($t)*);89	}};90	(@s; $o:ident: <ii $($t:tt)*) => {{91		$o.push_signal(dprint_core::formatting::Signal::FinishIgnoringIndent);92		pi!(@s; $o: $($t)*);93	}};94	(@s; $o:ident: info($v:expr) $($t:tt)*) => {{95		$o.push_info($v);96		pi!(@s; $o: $($t)*);97	}};98	(@s; $o:ident: ln_anchor($v:expr) $($t:tt)*) => {{99		$o.push_anchor(LineNumberAnchor::new($v));100		pi!(@s; $o: $($t)*);101	}};102	(@s; $o:ident: if($s:literal, $cond:expr, $($i:tt)*) $($t:tt)*) => {{103		$o.push_condition(dprint_core::formatting::conditions::if_true(104			$s,105			$cond.clone(),106			{107				let mut o = PrintItems::new();108				p!(o, $($i)*);109				o110			},111		));112		pi!(@s; $o: $($t)*);113	}};114	(@s; $o:ident: if_else($s:literal, $cond:expr, $($i:tt)*)($($e:tt)+) $($t:tt)*) => {{115		$o.push_condition(dprint_core::formatting::conditions::if_true_or(116			$s,117			$cond.clone(),118			{119				let mut o = PrintItems::new();120				p!(o, $($i)*);121				o122			},123			{124				let mut o = PrintItems::new();125				p!(o, $($e)*);126				o127			},128		));129		pi!(@s; $o: $($t)*);130	}};131	(@s; $o:ident: if_not($s:literal, $cond:expr, $($e:tt)*) $($t:tt)*) => {{132		$o.push_condition(dprint_core::formatting::conditions::if_true_or(133			$s,134			$cond.clone(),135			{136				let o = PrintItems::new();137				o138			},139			{140				let mut o = PrintItems::new();141				p!(o, $($e)*);142				o143			},144		));145		pi!(@s; $o: $($t)*);146	}};147	(@s; $o:ident: {$expr:expr} $($t:tt)*) => {{148		$expr.print($o);149		pi!(@s; $o: $($t)*);150	}};151	(@s; $o:ident: items($expr:expr) $($t:tt)*) => {{152		$o.extend($expr);153		pi!(@s; $o: $($t)*);154	}};155	(@s; $o:ident: if ($e:expr)($($then:tt)*) $($t:tt)*) => {{156		if $e {157			pi!(@s; $o: $($then)*);158		}159		pi!(@s; $o: $($t)*);160	}};161	(@s; $o:ident: ifelse ($e:expr)($($then:tt)*)($($else:tt)*) $($t:tt)*) => {{162		if $e {163			pi!(@s; $o: $($then)*);164		} else {165			pi!(@s; $o: $($else)*);166		}167		pi!(@s; $o: $($t)*);168	}};169	(@s; $i:ident:) => {}170}171macro_rules! p {172	($o:ident, $($t:tt)*) => {173		pi!(@s; $o: $($t)*)174	};175	(&mut $o:ident, $($t:tt)*) => {176		let om = &mut $o;177		pi!(@s; om: $($t)*)178	};179}180pub(crate) use p;181pub(crate) use pi;182183impl<P> Printable for Option<P>184where185	P: Printable,186{187	fn print(&self, out: &mut PrintItems) {188		if let Some(v) = self {189			v.print(out);190		} else {191			p!(192				out,193				string(format!(194					"/*missing {}*/",195					type_name::<P>().replace("jrsonnet_rowan_parser::generated::nodes::", "")196				),)197			);198		}199	}200}201202impl Printable for SyntaxToken {203	fn print(&self, out: &mut PrintItems) {204		p!(out, string(self.to_string()));205	}206}207208impl Printable for Text {209	fn print(&self, out: &mut PrintItems) {210		if matches!(self.kind(), TextKind::StringBlock) {211			let text = self.text();212			let mut text = collect_lexed_str_block(&text[3..])213				.expect("formatting is not performed on code with parsing errors");214215			if text.truncate && text.lines.ends_with(&[""]) {216				text.truncate = false;217				text.lines.pop();218			}219220			p!(out, str("|||"));221			if text.truncate {222				p!(out, str("-"));223			}224			p!(out, nl > i);225			for ele in text.lines {226				if ele.is_empty() {227					p!(out, >ii nl <ii);228				} else {229					p!(out, string(ele.to_string()) nl);230				}231			}232			p!(out, <i str("|||"));233234			return;235		}236		p!(out, string(format!("{}", self)));237	}238}239impl Printable for Number {240	fn print(&self, out: &mut PrintItems) {241		p!(out, string(format!("{}", self)));242	}243}244245impl Printable for Name {246	fn print(&self, out: &mut PrintItems) {247		p!(out, { self.ident_lit() });248	}249}250251impl Printable for DestructRest {252	fn print(&self, out: &mut PrintItems) {253		p!(out, str("..."));254		if let Some(name) = self.into() {255			p!(out, { name });256		}257	}258}259260impl Printable for Destruct {261	fn print(&self, out: &mut PrintItems) {262		match self {263			Self::DestructFull(f) => {264				p!(out, { f.name() });265			}266			Self::DestructSkip(_) => p!(out, str("?")),267			Self::DestructArray(a) => {268				p!(out, str("[") >i nl);269				for el in a.destruct_array_parts() {270					match el {271						DestructArrayPart::DestructArrayElement(e) => {272							p!(out, {e.destruct()} str(",") nl);273						}274						DestructArrayPart::DestructRest(d) => {275							p!(out, {d} str(",") nl);276						}277					}278				}279				p!(out, <i str("]"));280			}281			Self::DestructObject(o) => {282				p!(out, str("{") >i nl);283				for item in o.destruct_object_fields() {284					p!(out, { item.field() });285					if let Some(des) = item.destruct() {286						p!(out, str(": ") {des});287					}288					if let Some(def) = item.expr() {289						p!(out, str(" = ") {def});290					}291					p!(out, str(",") nl);292				}293				if let Some(rest) = o.destruct_rest() {294					p!(out, {rest} nl);295				}296				p!(out, <i str("}"));297			}298		}299	}300}301302impl Printable for FieldName {303	fn print(&self, out: &mut PrintItems) {304		match self {305			Self::FieldNameFixed(f) => {306				if let Some(id) = f.id() {307					p!(out, { id });308				} else if let Some(str) = f.text() {309					p!(out, { str });310				} else {311					p!(out, str("/*missing FieldName*/"));312				}313			}314			Self::FieldNameDynamic(d) => {315				p!(out, str("[") {d.expr()} str("]"));316			}317		}318	}319}320321impl Printable for Visibility {322	fn print(&self, out: &mut PrintItems) {323		p!(out, string(self.to_string()));324	}325}326327impl Printable for ObjLocal {328	fn print(&self, out: &mut PrintItems) {329		p!(out, str("local ") {self.bind()});330	}331}332333impl Printable for Assertion {334	fn print(&self, out: &mut PrintItems) {335		p!(out, str("assert ") {self.condition()});336		if self.colon_token().is_some() || self.message().is_some() {337			p!(out, str(": ") {self.message()});338		}339	}340}341342impl Printable for ParamsDesc {343	fn print(&self, out: &mut PrintItems) {344		p!(out, str("(") >i nl);345		for param in self.params() {346			p!(out, { param.destruct() });347			if param.assign_token().is_some() || param.expr().is_some() {348				p!(out, str(" = ") {param.expr()});349			}350			p!(out, str(",") nl);351		}352		p!(out, <i str(")"));353	}354}355impl Printable for ArgsDesc {356	fn print(&self, out: &mut PrintItems) {357		fn gen_args(children: Vec<Child<Arg>>, multi_line: ConditionResolver) -> PrintItems {358			let mut out = PrintItems::new();359360			let mut args = children.into_iter().peekable();361			while let Some(ele) = args.next() {362				if ele.should_start_with_newline {363					p!(out, nl);364				}365				format_comments(&ele.before_trivia, CommentLocation::AboveItem, &mut out);366				let arg = ele.value;367				if arg.name().is_some() || arg.assign_token().is_some() {368					p!(&mut out, {arg.name()} str(" = "));369				}370				p!(&mut out, { arg.expr() });371				let has_more = args.peek().is_some();372				if has_more {373					p!(out, str(","));374				} else {375					p!(out, if("trailing comma", multi_line, str(",")));376				}377				format_comments(&ele.inline_trivia, CommentLocation::ItemInline, &mut out);378				if has_more {379					p!(out, if_else("arg separator", multi_line, nl)(sonl));380				}381			}382383			out384		}385386		let start = LineNumber::new("args start line");387		let end = LineNumber::new("args end line");388		let multi_line = Rc::new(move |condition_context: &mut ConditionResolverContext| {389			is_multiple_lines(condition_context, start, end)390		});391392		let (children, end_comments) = children_between::<Arg>(393			self.syntax().clone(),394			self.l_paren_token().map(Into::into).as_ref(),395			self.r_paren_token().map(Into::into).as_ref(),396			None,397		);398399		let args_items = new_line_group(gen_args(children, multi_line.clone())).into_rc_path();400		let args_indented = with_indent(pi!(@i; nl items(args_items.into())));401402		p!(out, str("(") info(start));403		p!(out, if_else("args body", multi_line, items(args_indented) nl)(items(args_items.into())));404		if end_comments.should_start_with_newline {405			p!(out, nl);406		}407		format_comments(&end_comments.trivia, CommentLocation::EndOfItems, out);408		p!(out, str(")") info(end));409	}410}411impl Printable for SliceDesc {412	fn print(&self, out: &mut PrintItems) {413		p!(out, str("["));414		if self.from().is_some() {415			p!(out, { self.from() });416		}417		p!(out, str(":"));418		if self.end().is_some() {419			p!(out, { self.end().map(|e| e.expr()) });420		}421		// Keep only one : in case if we don't need step422		if self.step().is_some() {423			p!(out, str(":") {self.step().map(|e|e.expr())});424		}425		p!(out, str("]"));426	}427}428429impl Printable for Member {430	fn print(&self, out: &mut PrintItems) {431		match self {432			Self::MemberBindStmt(b) => {433				p!(out, { b.obj_local() });434			}435			Self::MemberAssertStmt(ass) => {436				p!(out, { ass.assertion() });437			}438			Self::MemberFieldNormal(n) => {439				p!(out, {n.field_name()} if(n.plus_token().is_some())({n.plus_token()}) {n.visibility()} str(" ") {n.expr()});440			}441			Self::MemberFieldMethod(m) => {442				p!(out, {m.field_name()} {m.params_desc()} {m.visibility()} str(" ") {m.expr()});443			}444		}445	}446}447448impl Printable for ObjBody {449	#[allow(clippy::too_many_lines)]450	fn print(&self, out: &mut PrintItems) {451		match self {452			Self::ObjBodyComp(l) => {453				fn gen_obj_comp(454					members: Vec<Child<Member>>,455					member_end_comments: EndingComments,456					compspecs: Vec<Child<CompSpec>>,457					multi_line: ConditionResolver,458				) -> PrintItems {459					let mut out = PrintItems::new();460					for mem in members {461						if mem.should_start_with_newline {462							p!(out, nl);463						}464						format_comments(&mem.before_trivia, CommentLocation::AboveItem, &mut out);465						p!(&mut out, { mem.value });466						p!(out, if("trailing comma", multi_line, str(",")));467						format_comments(&mem.inline_trivia, CommentLocation::ItemInline, &mut out);468						p!(out, if_else("member-comp sep", multi_line, nl)(sonl));469					}470471					if member_end_comments.should_start_with_newline {472						p!(out, nl);473					}474					format_comments(475						&member_end_comments.trivia,476						CommentLocation::EndOfItems,477						&mut out,478					);479480					let mut compspecs = compspecs.into_iter().peekable();481					while let Some(mem) = compspecs.next() {482						if mem.should_start_with_newline {483							p!(out, nl);484						}485						format_comments(&mem.before_trivia, CommentLocation::AboveItem, &mut out);486						p!(&mut out, { mem.value });487						format_comments(&mem.inline_trivia, CommentLocation::ItemInline, &mut out);488						p!(out, if_else("comp spec sep", multi_line, nl)(sonl));489					}490491					out492				}493494				let (children, mut end_comments) = children_between::<Member>(495					l.syntax().clone(),496					l.l_brace_token().map(Into::into).as_ref(),497					Some(498						&(l.comp_specs()499							.next()500							.expect("at least one spec is defined")501							.syntax()502							.clone())503						.into(),504					),505					None,506				);507				let trailing_for_comp = end_comments.extract_trailing();508509				let (compspecs, comp_end_comments) = children_between::<CompSpec>(510					l.syntax().clone(),511					l.member_comps()512						.last()513						.map(|m| m.syntax().clone())514						.map(Into::into)515						.or_else(|| l.l_brace_token().map(Into::into))516						.as_ref(),517					l.r_brace_token().map(Into::into).as_ref(),518					Some(trailing_for_comp),519				);520521				let source_is_multiline = children.iter().any(|c| c.triggers_multiline)522					|| compspecs.iter().any(|c| c.triggers_multiline)523					|| end_comments.should_start_with_newline524					|| comp_end_comments.should_start_with_newline;525526				let start = LineNumber::new("obj comp start line");527				let end = LineNumber::new("obj comp end line");528				let multi_line: ConditionResolver = if source_is_multiline {529					true_resolver()530				} else {531					Rc::new(move |ctx: &mut ConditionResolverContext| {532						is_multiple_lines(ctx, start, end)533					})534				};535536				let body = new_line_group(gen_obj_comp(537					children,538					end_comments,539					compspecs,540					multi_line.clone(),541				))542				.into_rc_path();543544				let body = with_indent_eoi(multi_line, body.into(), comp_end_comments);545546				p!(out, str("{") info(start));547				p!(out, items(body));548				p!(out, str("}") info(end));549			}550			Self::ObjBodyMemberList(l) => {551				fn gen_members(552					children: Vec<Child<Member>>,553					multi_line: ConditionResolver,554				) -> PrintItems {555					let mut out = PrintItems::new();556					let mut members = children.into_iter().peekable();557					while let Some(mem) = members.next() {558						if mem.should_start_with_newline {559							p!(out, nl);560						}561						format_comments(&mem.before_trivia, CommentLocation::AboveItem, &mut out);562						p!(&mut out, { mem.value });563						let has_more = members.peek().is_some();564						if has_more {565							p!(out, str(","));566						} else {567							p!(out, if("trailing comma", multi_line, str(",")));568						}569						format_comments(&mem.inline_trivia, CommentLocation::ItemInline, &mut out);570						p!(out, if_else("member separator", multi_line, nl)(sonl));571					}572					out573				}574575				let (children, end_comments) = children_between::<Member>(576					l.syntax().clone(),577					l.l_brace_token().map(Into::into).as_ref(),578					l.r_brace_token().map(Into::into).as_ref(),579					None,580				);581				if children.is_empty() && end_comments.is_empty() {582					p!(out, str("{ }"));583					return;584				}585586				let source_is_multiline = children.iter().any(|c| c.triggers_multiline)587					|| end_comments.should_start_with_newline;588589				let start = LineNumber::new("obj start line");590				let end = LineNumber::new("obj end line");591				let multi_line: ConditionResolver = if source_is_multiline {592					true_resolver()593				} else {594					Rc::new(move |ctx: &mut ConditionResolverContext| {595						is_multiple_lines(ctx, start, end)596					})597				};598599				let members_items =600					new_line_group(gen_members(children, multi_line.clone())).into_rc_path();601602				let members = with_indent_eoi(multi_line, members_items.into(), end_comments);603604				p!(out, str("{") info(start));605				p!(out, items(members));606				p!(out, str("}") info(end));607			}608		}609	}610}611impl Printable for UnaryOperator {612	fn print(&self, out: &mut PrintItems) {613		p!(out, string(self.text().to_string()));614	}615}616impl Printable for BinaryOperator {617	fn print(&self, out: &mut PrintItems) {618		p!(out, string(self.text().to_string()));619	}620}621impl Printable for Bind {622	fn print(&self, out: &mut PrintItems) {623		match self {624			Self::BindDestruct(d) => {625				p!(out, {d.into()} str(" = ") {d.value()});626			}627			Self::BindFunction(f) => {628				p!(out, {f.name()} {f.params()} str(" = ") {f.value()});629			}630		}631	}632}633impl Printable for Literal {634	fn print(&self, out: &mut PrintItems) {635		p!(out, string(self.syntax().to_string()));636	}637}638impl Printable for ImportKind {639	fn print(&self, out: &mut PrintItems) {640		p!(out, string(self.syntax().to_string()));641	}642}643impl Printable for ForSpec {644	fn print(&self, out: &mut PrintItems) {645		p!(out, str("for ") {self.bind()} str(" in ") {self.expr()});646	}647}648impl Printable for ForObjSpec {649	fn print(&self, out: &mut PrintItems) {650		p!(out, str("for [") {self.key()} str("]") {self.visibility()} str(" ") {self.value()} str(" in ") {self.expr()});651	}652}653impl Printable for IfSpec {654	fn print(&self, out: &mut PrintItems) {655		p!(out, str("if ") {self.expr()});656	}657}658impl Printable for CompSpec {659	fn print(&self, out: &mut PrintItems) {660		match self {661			Self::ForSpec(f) => f.print(out),662			Self::ForObjSpec(f) => f.print(out),663			Self::IfSpec(i) => i.print(out),664		}665	}666}667impl Printable for Expr {668	fn print(&self, out: &mut PrintItems) {669		let (stmts, _ending) = children_between::<Stmt>(670			self.syntax().clone(),671			None,672			self.expr_base()673				.as_ref()674				.map(ExprBase::syntax)675				.cloned()676				.map(Into::into)677				.as_ref(),678			None,679		);680		for stmt in stmts {681			p!(out, { stmt.value });682		}683		p!(out, { self.expr_base() });684		let (suffixes, _ending) = children_between::<Suffix>(685			self.syntax().clone(),686			self.expr_base()687				.as_ref()688				.map(ExprBase::syntax)689				.cloned()690				.map(Into::into)691				.as_ref(),692			None,693			None,694		);695		for suffix in suffixes {696			p!(out, { suffix.value });697		}698	}699}700impl Printable for Suffix {701	fn print(&self, out: &mut PrintItems) {702		match self {703			Self::SuffixIndex(i) => {704				if i.question_mark_token().is_some() {705					p!(out, str("?"));706				}707				p!(out, str(".") {i.index()});708			}709			Self::SuffixIndexExpr(e) => {710				if e.question_mark_token().is_some() {711					p!(out, str(".?"));712				}713				p!(out, str("[") {e.index()} str("]"));714			}715			Self::SuffixSlice(d) => {716				p!(out, { d.slice_desc() });717			}718			Self::SuffixApply(a) => {719				p!(out, { a.args_desc() });720			}721		}722	}723}724impl Printable for Stmt {725	fn print(&self, out: &mut PrintItems) {726		match self {727			Self::StmtLocal(l) => {728				let (binds, end_comments) = children_between::<Bind>(729					l.syntax().clone(),730					l.local_kw_token().map(Into::into).as_ref(),731					l.semi_token().map(Into::into).as_ref(),732					None,733				);734				if binds.len() == 1 {735					let bind = &binds[0];736					format_comments(&bind.before_trivia, CommentLocation::AboveItem, out);737					p!(out, str("local ") {bind.value});738				// TODO: keep end_comments, child.inline_trivia somehow, force multiple locals formatting in case of presence?739				} else {740					p!(out,str("local") >i nl);741					for bind in binds {742						if bind.should_start_with_newline {743							p!(out, nl);744						}745						format_comments(&bind.before_trivia, CommentLocation::AboveItem, out);746						p!(out, {bind.value} str(","));747						format_comments(&bind.inline_trivia, CommentLocation::ItemInline, out);748						p!(out, nl);749					}750					if end_comments.should_start_with_newline {751						p!(out, nl);752					}753					format_comments(&end_comments.trivia, CommentLocation::EndOfItems, out);754					p!(out,<i);755				}756				p!(out,str(";") nl);757			}758			Self::StmtAssert(a) => {759				p!(out, {a.assertion()} str(";") nl);760			}761		}762	}763}764765impl Printable for ExprArray {766	fn print(&self, out: &mut PrintItems) {767		fn gen_elements(children: Vec<Child<Expr>>, multi_line: ConditionResolver) -> PrintItems {768			let mut out = PrintItems::new();769			let mut els = children.into_iter().peekable();770			while let Some(el) = els.next() {771				if el.should_start_with_newline {772					p!(out, nl);773				}774				format_comments(&el.before_trivia, CommentLocation::AboveItem, &mut out);775				p!(&mut out, { el.value });776				let has_more = els.peek().is_some();777				if has_more {778					p!(out, str(","));779				} else {780					p!(out, if("trailing comma", multi_line, str(",")));781				}782				format_comments(&el.inline_trivia, CommentLocation::ItemInline, &mut out);783				p!(out, if_else("element separator", multi_line, nl)(sonl));784			}785			out786		}787788		let (children, end_comments) = children_between::<Expr>(789			self.syntax().clone(),790			self.l_brack_token().map(Into::into).as_ref(),791			self.r_brack_token().map(Into::into).as_ref(),792			None,793		);794		if children.is_empty() && end_comments.is_empty() {795			p!(out, str("[ ]"));796			return;797		}798799		let source_is_multiline =800			children.iter().any(|c| c.triggers_multiline) || end_comments.should_start_with_newline;801802		let start = LineNumber::new("arr start line");803		let end = LineNumber::new("arr end line");804		let multi_line: ConditionResolver = if source_is_multiline {805			true_resolver()806		} else {807			Rc::new(move |ctx: &mut ConditionResolverContext| is_multiple_lines(ctx, start, end))808		};809810		let els_items = new_line_group(gen_elements(children, multi_line.clone())).into_rc_path();811812		let els = with_indent_eoi(multi_line, els_items.into(), end_comments);813814		p!(out, str("[") info(start) items(els) str("]") info(end));815	}816}817818impl Printable for ExprBase {819	fn print(&self, out: &mut PrintItems) {820		match self {821			Self::ExprBinary(b) => {822				p!(out, {b.lhs()} str(" ") {b.binary_operator()} str(" ") {b.rhs()});823			}824			Self::ExprUnary(u) => p!(out, {u.unary_operator()} {u.rhs()}),825			// Self::ExprSlice(s) => {826			// 	p!(new: {s.expr()} {s.slice_desc()})827			// }828			// Self::ExprIndex(i) => {829			// 	p!(new: {i.expr()} str(".") {i.index()})830			// }831			// Self::ExprIndexExpr(i) => p!(new: {i.base()} str("[") {i.index()} str("]")),832			// Self::ExprApply(a) => {833			// 	let mut pi = p!(new: {a.expr()} {a.args_desc()});834			// 	if a.tailstrict_kw_token().is_some() {835			// 		p!(out,str(" tailstrict"));836			// 	}837			// 	pi838			// }839			Self::ExprObjExtend(ex) => {840				p!(out, {ex.lhs()} str(" ") {ex.rhs()});841			}842			Self::ExprParened(p) => {843				p!(out, str("(") {p.expr()} str(")"));844			}845			Self::ExprString(s) => p!(out, { s.text() }),846			Self::ExprNumber(n) => p!(out, { n.number() }),847			Self::ExprArray(a) => {848				p!(out, { a });849			}850			Self::ExprObject(obj) => {851				p!(out, { obj.obj_body() });852			}853			Self::ExprArrayComp(arr) => {854				p!(out, str("[") {arr.expr()});855				for spec in arr.comp_specs() {856					p!(out, str(" ") {spec});857				}858				p!(out, str("]"));859			}860			Self::ExprImport(v) => {861				p!(out, {v.import_kind()} str(" ") {v.text()});862			}863			Self::ExprVar(n) => p!(out, { n.name() }),864			// Self::ExprLocal(l) => {865			// }866			Self::ExprIfThenElse(ite) => {867				p!(out, str("if ") {ite.cond()} str(" then ") {ite.then().map(|t| t.expr())});868				if ite.else_kw_token().is_some() || ite.else_().is_some() {869					p!(out, str(" else ") {ite.else_().map(|t| t.expr())});870				}871			}872			Self::ExprFunction(f) => p!(out, str("function") {f.params_desc()} nl {f.expr()}),873			// Self::ExprAssert(a) => p!(new: {a.assertion()} str("; ") {a.expr()}),874			Self::ExprError(e) => p!(out, str("error ") {e.expr()}),875			Self::ExprLiteral(l) => {876				p!(out, { l.literal() });877			}878		}879	}880}881882impl Printable for SourceFile {883	fn print(&self, out: &mut PrintItems) {884		let before = trivia_before(885			self.syntax().clone(),886			self.expr()887				.map(|e| e.syntax().clone())888				.map(Into::into)889				.as_ref(),890		);891		let after = trivia_after(892			self.syntax().clone(),893			self.expr()894				.map(|e| e.syntax().clone())895				.map(Into::into)896				.as_ref(),897		);898		format_comments(&before, CommentLocation::AboveItem, out);899		p!(out, {self.expr()} nl);900		format_comments(&after, CommentLocation::EndOfItems, out);901	}902}903904pub struct FormatOptions {905	pub indent: u8,906	pub use_tabs: bool,907	pub max_width: u32,908}909910impl FormatOptions {911	pub fn new() -> Self {912		Self {913			indent: 4,914			use_tabs: true,915			max_width: 100,916		}917	}918}919920impl Default for FormatOptions {921	fn default() -> Self {922		Self::new()923	}924}925926#[allow(927	clippy::result_large_err,928	reason = "TODO: there should be an intermediate representation for such reports"929)]930pub fn format(input: &str, opts: &FormatOptions) -> Result<String, SnippetBuilder> {931	let (parsed, errors) = jrsonnet_rowan_parser::parse(input);932	if !errors.is_empty() {933		// Reserve one char for EOF display934		let input = format!("{input} ");935		let mut builder = hi_doc::SnippetBuilder::new(input);936		for error in errors {937			builder938				.error(hi_doc::Text::fragment(939					format!("{:?}", error.error),940					Formatting::default(),941				))942				.range(943					error.range.start().into()944						..=(usize::from(error.range.end()) - 1).max(error.range.start().into()),945				)946				.build();947		}948		// let snippet = builder.build();949		return Err(builder);950		// It is possible to recover from this failure, but the output may be broken, as formatter is free to skip951		// ERROR rowan nodes.952		// Recovery needs to be enabled for LSP, though.953	}954	Ok(dprint_core::formatting::format(955		|| {956			let mut out = PrintItems::new();957			parsed.print(&mut out);958			out959		},960		PrintOptions {961			indent_width: opts.indent,962			max_width: opts.max_width,963			use_tabs: opts.use_tabs,964			new_line_text: "\n",965		},966	))967}
after · crates/jrsonnet-formatter/src/lib.rs
1use std::{any::type_name, rc::Rc};23use children::{children_between, trivia_before};4use dprint_core::formatting::{5	ConditionResolver, ConditionResolverContext, LineNumber, PrintItems, PrintOptions,6	condition_helpers::is_multiple_lines,7	condition_resolvers::true_resolver,8	ir_helpers::{new_line_group, with_indent},9};10use hi_doc::{Formatting, SnippetBuilder};11use jrsonnet_lexer::collect_lexed_str_block;12use jrsonnet_rowan_parser::{13	AstNode, AstToken as _, SyntaxToken,14	nodes::{15		Arg, ArgsDesc, Assertion, BinaryOperator, Bind, CompSpec, Destruct, DestructArrayPart,16		DestructRest, Expr, ExprArray, ExprBase, FieldName, ForObjSpec, ForSpec, IfSpec,17		ImportKind, Literal, Member, Name, Number, ObjBody, ObjLocal, ParamsDesc, SliceDesc,18		SourceFile, Stmt, Suffix, Text, TextKind, UnaryOperator, Visibility,19	},20};2122use crate::{23	children::{Child, EndingComments, trivia_after},24	comments::{CommentLocation, format_comments},25};2627mod children;28mod comments;29mod tests;3031fn with_indent_eoi(cond: ConditionResolver, o: PrintItems, e: EndingComments) -> PrintItems {32	let end_comments_items = {33		let mut items = PrintItems::new();34		if e.should_start_with_newline {35			p!(&mut items, nl);36		}37		format_comments(&e.trivia, CommentLocation::EndOfItems, &mut items);38		items.into_rc_path()39	};40	let items = new_line_group(pi!(@i; items(o) items(end_comments_items.into()))).into_rc_path();4142	let indented = with_indent(pi!(@i; nl items(items.into())));4344	pi!(@i; if_else("indented body", cond, items(indented))(str(" ") items(items.into())))45}4647pub trait Printable {48	fn print(&self, out: &mut PrintItems);49}5051macro_rules! pi {52	(@i; $($t:tt)*) => {{53		#[allow(unused_mut)]54		let mut o = dprint_core::formatting::PrintItems::new();55		pi!(@s; o: $($t)*);56		o57	}};58	(@s; $o:ident: str($e:expr $(,)?) $($t:tt)*) => {{59		$o.push_string($e.to_owned());60		pi!(@s; $o: $($t)*);61	}};62	(@s; $o:ident: string($e:expr $(,)?) $($t:tt)*) => {{63		$o.push_string($e);64		pi!(@s; $o: $($t)*);65	}};66	(@s; $o:ident: nl $($t:tt)*) => {{67		$o.push_signal(dprint_core::formatting::Signal::NewLine);68		pi!(@s; $o: $($t)*);69	}};70	(@s; $o:ident: sonl $($t:tt)*) => {{71		$o.push_signal(dprint_core::formatting::Signal::SpaceOrNewLine);72		pi!(@s; $o: $($t)*);73	}};74	(@s; $o:ident: tab $($t:tt)*) => {{75		$o.push_signal(dprint_core::formatting::Signal::Tab);76		pi!(@s; $o: $($t)*);77	}};78	(@s; $o:ident: >i $($t:tt)*) => {{79		$o.push_signal(dprint_core::formatting::Signal::StartIndent);80		pi!(@s; $o: $($t)*);81	}};82	(@s; $o:ident: <i $($t:tt)*) => {{83		$o.push_signal(dprint_core::formatting::Signal::FinishIndent);84		pi!(@s; $o: $($t)*);85	}};86	(@s; $o:ident: >ii $($t:tt)*) => {{87		$o.push_signal(dprint_core::formatting::Signal::StartIgnoringIndent);88		pi!(@s; $o: $($t)*);89	}};90	(@s; $o:ident: <ii $($t:tt)*) => {{91		$o.push_signal(dprint_core::formatting::Signal::FinishIgnoringIndent);92		pi!(@s; $o: $($t)*);93	}};94	(@s; $o:ident: info($v:expr) $($t:tt)*) => {{95		$o.push_info($v);96		pi!(@s; $o: $($t)*);97	}};98	(@s; $o:ident: ln_anchor($v:expr) $($t:tt)*) => {{99		$o.push_anchor(LineNumberAnchor::new($v));100		pi!(@s; $o: $($t)*);101	}};102	(@s; $o:ident: if($s:literal, $cond:expr, $($i:tt)*) $($t:tt)*) => {{103		$o.push_condition(dprint_core::formatting::conditions::if_true(104			$s,105			$cond.clone(),106			{107				let mut o = PrintItems::new();108				p!(o, $($i)*);109				o110			},111		));112		pi!(@s; $o: $($t)*);113	}};114	(@s; $o:ident: if_else($s:literal, $cond:expr, $($i:tt)*)($($e:tt)+) $($t:tt)*) => {{115		$o.push_condition(dprint_core::formatting::conditions::if_true_or(116			$s,117			$cond.clone(),118			{119				let mut o = PrintItems::new();120				p!(o, $($i)*);121				o122			},123			{124				let mut o = PrintItems::new();125				p!(o, $($e)*);126				o127			},128		));129		pi!(@s; $o: $($t)*);130	}};131	(@s; $o:ident: if_not($s:literal, $cond:expr, $($e:tt)*) $($t:tt)*) => {{132		$o.push_condition(dprint_core::formatting::conditions::if_true_or(133			$s,134			$cond.clone(),135			{136				let o = PrintItems::new();137				o138			},139			{140				let mut o = PrintItems::new();141				p!(o, $($e)*);142				o143			},144		));145		pi!(@s; $o: $($t)*);146	}};147	(@s; $o:ident: {$expr:expr} $($t:tt)*) => {{148		$expr.print($o);149		pi!(@s; $o: $($t)*);150	}};151	(@s; $o:ident: items($expr:expr) $($t:tt)*) => {{152		$o.extend($expr);153		pi!(@s; $o: $($t)*);154	}};155	(@s; $o:ident: if ($e:expr)($($then:tt)*) $($t:tt)*) => {{156		if $e {157			pi!(@s; $o: $($then)*);158		}159		pi!(@s; $o: $($t)*);160	}};161	(@s; $o:ident: ifelse ($e:expr)($($then:tt)*)($($else:tt)*) $($t:tt)*) => {{162		if $e {163			pi!(@s; $o: $($then)*);164		} else {165			pi!(@s; $o: $($else)*);166		}167		pi!(@s; $o: $($t)*);168	}};169	(@s; $i:ident:) => {}170}171macro_rules! p {172	($o:ident, $($t:tt)*) => {173		pi!(@s; $o: $($t)*)174	};175	(&mut $o:ident, $($t:tt)*) => {176		let om = &mut $o;177		pi!(@s; om: $($t)*)178	};179}180pub(crate) use p;181pub(crate) use pi;182183impl<P> Printable for Option<P>184where185	P: Printable,186{187	fn print(&self, out: &mut PrintItems) {188		if let Some(v) = self {189			v.print(out);190		} else {191			p!(192				out,193				string(format!(194					"/*missing {}*/",195					type_name::<P>().replace("jrsonnet_rowan_parser::generated::nodes::", "")196				),)197			);198		}199	}200}201202impl Printable for SyntaxToken {203	fn print(&self, out: &mut PrintItems) {204		p!(out, string(self.to_string()));205	}206}207208impl Printable for Text {209	fn print(&self, out: &mut PrintItems) {210		if matches!(self.kind(), TextKind::StringBlock) {211			let text = self.text();212			let mut text = collect_lexed_str_block(&text[3..])213				.expect("formatting is not performed on code with parsing errors");214215			if text.truncate && text.lines.ends_with(&[""]) {216				text.truncate = false;217				text.lines.pop();218			}219220			p!(out, str("|||"));221			if text.truncate {222				p!(out, str("-"));223			}224			p!(out, nl > i);225			for ele in text.lines {226				if ele.is_empty() {227					p!(out, >ii nl <ii);228				} else {229					p!(out, string(ele.to_string()) nl);230				}231			}232			p!(out, <i str("|||"));233234			return;235		}236		p!(out, string(format!("{}", self)));237	}238}239impl Printable for Number {240	fn print(&self, out: &mut PrintItems) {241		p!(out, string(format!("{}", self)));242	}243}244245impl Printable for Name {246	fn print(&self, out: &mut PrintItems) {247		p!(out, { self.ident_lit() });248	}249}250251impl Printable for DestructRest {252	fn print(&self, out: &mut PrintItems) {253		p!(out, str("..."));254		if let Some(name) = self.into() {255			p!(out, { name });256		}257	}258}259260impl Printable for Destruct {261	fn print(&self, out: &mut PrintItems) {262		match self {263			Self::DestructFull(f) => {264				p!(out, { f.name() });265			}266			Self::DestructSkip(_) => p!(out, str("?")),267			Self::DestructArray(a) => {268				p!(out, str("[") >i nl);269				for el in a.destruct_array_parts() {270					match el {271						DestructArrayPart::DestructArrayElement(e) => {272							p!(out, {e.destruct()} str(",") nl);273						}274						DestructArrayPart::DestructRest(d) => {275							p!(out, {d} str(",") nl);276						}277					}278				}279				p!(out, <i str("]"));280			}281			Self::DestructObject(o) => {282				p!(out, str("{") >i nl);283				for item in o.destruct_object_fields() {284					p!(out, { item.field() });285					if let Some(des) = item.destruct() {286						p!(out, str(": ") {des});287					}288					if let Some(def) = item.expr() {289						p!(out, str(" = ") {def});290					}291					p!(out, str(",") nl);292				}293				if let Some(rest) = o.destruct_rest() {294					p!(out, {rest} nl);295				}296				p!(out, <i str("}"));297			}298		}299	}300}301302impl Printable for FieldName {303	fn print(&self, out: &mut PrintItems) {304		match self {305			Self::FieldNameFixed(f) => {306				if let Some(id) = f.id() {307					p!(out, { id });308				} else if let Some(str) = f.text() {309					p!(out, { str });310				} else {311					p!(out, str("/*missing FieldName*/"));312				}313			}314			Self::FieldNameDynamic(d) => {315				p!(out, str("[") {d.expr()} str("]"));316			}317		}318	}319}320321impl Printable for Visibility {322	fn print(&self, out: &mut PrintItems) {323		p!(out, string(self.to_string()));324	}325}326327impl Printable for ObjLocal {328	fn print(&self, out: &mut PrintItems) {329		p!(out, str("local ") {self.bind()});330	}331}332333impl Printable for Assertion {334	fn print(&self, out: &mut PrintItems) {335		p!(out, str("assert ") {self.condition()});336		if self.colon_token().is_some() || self.message().is_some() {337			p!(out, str(": ") {self.message()});338		}339	}340}341342impl Printable for ParamsDesc {343	fn print(&self, out: &mut PrintItems) {344		p!(out, str("(") >i nl);345		for param in self.params() {346			p!(out, { param.destruct() });347			if param.assign_token().is_some() || param.expr().is_some() {348				p!(out, str(" = ") {param.expr()});349			}350			p!(out, str(",") nl);351		}352		p!(out, <i str(")"));353	}354}355impl Printable for ArgsDesc {356	fn print(&self, out: &mut PrintItems) {357		fn gen_args(children: Vec<Child<Arg>>, multi_line: ConditionResolver) -> PrintItems {358			let mut out = PrintItems::new();359360			let mut args = children.into_iter().peekable();361			while let Some(ele) = args.next() {362				if ele.should_start_with_newline {363					p!(out, nl);364				}365				format_comments(&ele.before_trivia, CommentLocation::AboveItem, &mut out);366				let arg = ele.value;367				if arg.name().is_some() || arg.assign_token().is_some() {368					p!(&mut out, {arg.name()} str(" = "));369				}370				p!(&mut out, { arg.expr() });371				let has_more = args.peek().is_some();372				if has_more {373					p!(out, str(","));374				} else {375					p!(out, if("trailing comma", multi_line, str(",")));376				}377				format_comments(&ele.inline_trivia, CommentLocation::ItemInline, &mut out);378				if has_more {379					p!(out, if_else("arg separator", multi_line, nl)(sonl));380				}381			}382383			out384		}385386		let start = LineNumber::new("args start line");387		let end = LineNumber::new("args end line");388		let multi_line = Rc::new(move |condition_context: &mut ConditionResolverContext| {389			is_multiple_lines(condition_context, start, end)390		});391392		let (children, end_comments) = children_between::<Arg>(393			self.syntax().clone(),394			self.l_paren_token().map(Into::into).as_ref(),395			self.r_paren_token().map(Into::into).as_ref(),396			None,397		);398399		let args_items = new_line_group(gen_args(children, multi_line.clone())).into_rc_path();400		let args_indented = with_indent(pi!(@i; nl items(args_items.into())));401402		p!(out, str("(") info(start));403		p!(out, if_else("args body", multi_line, items(args_indented) nl)(items(args_items.into())));404		if end_comments.should_start_with_newline {405			p!(out, nl);406		}407		format_comments(&end_comments.trivia, CommentLocation::EndOfItems, out);408		p!(out, str(")") info(end));409	}410}411impl Printable for SliceDesc {412	fn print(&self, out: &mut PrintItems) {413		p!(out, str("["));414		if self.from().is_some() {415			p!(out, { self.from() });416		}417		p!(out, str(":"));418		if self.end().is_some() {419			p!(out, { self.end().map(|e| e.expr()) });420		}421		// Keep only one : in case if we don't need step422		if self.step().is_some() {423			p!(out, str(":") {self.step().map(|e|e.expr())});424		}425		p!(out, str("]"));426	}427}428429impl Printable for Member {430	fn print(&self, out: &mut PrintItems) {431		match self {432			Self::MemberBindStmt(b) => {433				p!(out, { b.obj_local() });434			}435			Self::MemberAssertStmt(ass) => {436				p!(out, { ass.assertion() });437			}438			Self::MemberFieldNormal(n) => {439				p!(out, {n.field_name()} if(n.plus_token().is_some())({n.plus_token()}) {n.visibility()} str(" ") {n.expr()});440			}441			Self::MemberFieldMethod(m) => {442				p!(out, {m.field_name()} {m.params_desc()} {m.visibility()} str(" ") {m.expr()});443			}444		}445	}446}447448impl Printable for ObjBody {449	#[allow(clippy::too_many_lines)]450	fn print(&self, out: &mut PrintItems) {451		match self {452			Self::ObjBodyComp(l) => {453				fn gen_obj_comp(454					members: Vec<Child<Member>>,455					member_end_comments: EndingComments,456					compspecs: Vec<Child<CompSpec>>,457					multi_line: ConditionResolver,458				) -> PrintItems {459					let mut out = PrintItems::new();460					for mem in members {461						if mem.should_start_with_newline {462							p!(out, nl);463						}464						format_comments(&mem.before_trivia, CommentLocation::AboveItem, &mut out);465						p!(&mut out, { mem.value });466						p!(out, if("trailing comma", multi_line, str(",")));467						format_comments(&mem.inline_trivia, CommentLocation::ItemInline, &mut out);468						p!(out, if_else("member-comp sep", multi_line, nl)(sonl));469					}470471					if member_end_comments.should_start_with_newline {472						p!(out, nl);473					}474					format_comments(475						&member_end_comments.trivia,476						CommentLocation::EndOfItems,477						&mut out,478					);479480					for mem in compspecs {481						if mem.should_start_with_newline {482							p!(out, nl);483						}484						format_comments(&mem.before_trivia, CommentLocation::AboveItem, &mut out);485						p!(&mut out, { mem.value });486						format_comments(&mem.inline_trivia, CommentLocation::ItemInline, &mut out);487						p!(out, if_else("comp spec sep", multi_line, nl)(sonl));488					}489490					out491				}492493				let (children, mut end_comments) = children_between::<Member>(494					l.syntax().clone(),495					l.l_brace_token().map(Into::into).as_ref(),496					Some(497						&(l.comp_specs()498							.next()499							.expect("at least one spec is defined")500							.syntax()501							.clone())502						.into(),503					),504					None,505				);506				let trailing_for_comp = end_comments.extract_trailing();507508				let (compspecs, comp_end_comments) = children_between::<CompSpec>(509					l.syntax().clone(),510					l.member_comps()511						.last()512						.map(|m| m.syntax().clone())513						.map(Into::into)514						.or_else(|| l.l_brace_token().map(Into::into))515						.as_ref(),516					l.r_brace_token().map(Into::into).as_ref(),517					Some(trailing_for_comp),518				);519520				let source_is_multiline = children.iter().any(|c| c.triggers_multiline)521					|| compspecs.iter().any(|c| c.triggers_multiline)522					|| end_comments.should_start_with_newline523					|| comp_end_comments.should_start_with_newline;524525				let start = LineNumber::new("obj comp start line");526				let end = LineNumber::new("obj comp end line");527				let multi_line: ConditionResolver = if source_is_multiline {528					true_resolver()529				} else {530					Rc::new(move |ctx: &mut ConditionResolverContext| {531						is_multiple_lines(ctx, start, end)532					})533				};534535				let body = new_line_group(gen_obj_comp(536					children,537					end_comments,538					compspecs,539					multi_line.clone(),540				))541				.into_rc_path();542543				let body = with_indent_eoi(multi_line, body.into(), comp_end_comments);544545				p!(out, str("{") info(start));546				p!(out, items(body));547				p!(out, str("}") info(end));548			}549			Self::ObjBodyMemberList(l) => {550				fn gen_members(551					children: Vec<Child<Member>>,552					multi_line: ConditionResolver,553				) -> PrintItems {554					let mut out = PrintItems::new();555					let mut members = children.into_iter().peekable();556					while let Some(mem) = members.next() {557						if mem.should_start_with_newline {558							p!(out, nl);559						}560						format_comments(&mem.before_trivia, CommentLocation::AboveItem, &mut out);561						p!(&mut out, { mem.value });562						let has_more = members.peek().is_some();563						if has_more {564							p!(out, str(","));565						} else {566							p!(out, if("trailing comma", multi_line, str(",")));567						}568						format_comments(&mem.inline_trivia, CommentLocation::ItemInline, &mut out);569						p!(out, if_else("member separator", multi_line, nl)(sonl));570					}571					out572				}573574				let (children, end_comments) = children_between::<Member>(575					l.syntax().clone(),576					l.l_brace_token().map(Into::into).as_ref(),577					l.r_brace_token().map(Into::into).as_ref(),578					None,579				);580				if children.is_empty() && end_comments.is_empty() {581					p!(out, str("{ }"));582					return;583				}584585				let source_is_multiline = children.iter().any(|c| c.triggers_multiline)586					|| end_comments.should_start_with_newline;587588				let start = LineNumber::new("obj start line");589				let end = LineNumber::new("obj end line");590				let multi_line: ConditionResolver = if source_is_multiline {591					true_resolver()592				} else {593					Rc::new(move |ctx: &mut ConditionResolverContext| {594						is_multiple_lines(ctx, start, end)595					})596				};597598				let members_items =599					new_line_group(gen_members(children, multi_line.clone())).into_rc_path();600601				let members = with_indent_eoi(multi_line, members_items.into(), end_comments);602603				p!(out, str("{") info(start));604				p!(out, items(members));605				p!(out, str("}") info(end));606			}607		}608	}609}610impl Printable for UnaryOperator {611	fn print(&self, out: &mut PrintItems) {612		p!(out, string(self.text().to_string()));613	}614}615impl Printable for BinaryOperator {616	fn print(&self, out: &mut PrintItems) {617		p!(out, string(self.text().to_string()));618	}619}620impl Printable for Bind {621	fn print(&self, out: &mut PrintItems) {622		match self {623			Self::BindDestruct(d) => {624				p!(out, {d.into()} str(" = ") {d.value()});625			}626			Self::BindFunction(f) => {627				p!(out, {f.name()} {f.params()} str(" = ") {f.value()});628			}629		}630	}631}632impl Printable for Literal {633	fn print(&self, out: &mut PrintItems) {634		p!(out, string(self.syntax().to_string()));635	}636}637impl Printable for ImportKind {638	fn print(&self, out: &mut PrintItems) {639		p!(out, string(self.syntax().to_string()));640	}641}642impl Printable for ForSpec {643	fn print(&self, out: &mut PrintItems) {644		p!(out, str("for ") {self.bind()} str(" in ") {self.expr()});645	}646}647impl Printable for ForObjSpec {648	fn print(&self, out: &mut PrintItems) {649		p!(out, str("for [") {self.key()} str("]") {self.visibility()} str(" ") {self.value()} str(" in ") {self.expr()});650	}651}652impl Printable for IfSpec {653	fn print(&self, out: &mut PrintItems) {654		p!(out, str("if ") {self.expr()});655	}656}657impl Printable for CompSpec {658	fn print(&self, out: &mut PrintItems) {659		match self {660			Self::ForSpec(f) => f.print(out),661			Self::ForObjSpec(f) => f.print(out),662			Self::IfSpec(i) => i.print(out),663		}664	}665}666impl Printable for Expr {667	fn print(&self, out: &mut PrintItems) {668		let (stmts, _ending) = children_between::<Stmt>(669			self.syntax().clone(),670			None,671			self.expr_base()672				.as_ref()673				.map(ExprBase::syntax)674				.cloned()675				.map(Into::into)676				.as_ref(),677			None,678		);679		for stmt in stmts {680			p!(out, { stmt.value });681		}682		p!(out, { self.expr_base() });683		let (suffixes, _ending) = children_between::<Suffix>(684			self.syntax().clone(),685			self.expr_base()686				.as_ref()687				.map(ExprBase::syntax)688				.cloned()689				.map(Into::into)690				.as_ref(),691			None,692			None,693		);694		for suffix in suffixes {695			p!(out, { suffix.value });696		}697	}698}699impl Printable for Suffix {700	fn print(&self, out: &mut PrintItems) {701		match self {702			Self::SuffixIndex(i) => {703				if i.question_mark_token().is_some() {704					p!(out, str("?"));705				}706				p!(out, str(".") {i.index()});707			}708			Self::SuffixIndexExpr(e) => {709				if e.question_mark_token().is_some() {710					p!(out, str(".?"));711				}712				p!(out, str("[") {e.index()} str("]"));713			}714			Self::SuffixSlice(d) => {715				p!(out, { d.slice_desc() });716			}717			Self::SuffixApply(a) => {718				p!(out, { a.args_desc() });719			}720		}721	}722}723impl Printable for Stmt {724	fn print(&self, out: &mut PrintItems) {725		match self {726			Self::StmtLocal(l) => {727				let (binds, end_comments) = children_between::<Bind>(728					l.syntax().clone(),729					l.local_kw_token().map(Into::into).as_ref(),730					l.semi_token().map(Into::into).as_ref(),731					None,732				);733				if binds.len() == 1 {734					let bind = &binds[0];735					format_comments(&bind.before_trivia, CommentLocation::AboveItem, out);736					p!(out, str("local ") {bind.value});737				// TODO: keep end_comments, child.inline_trivia somehow, force multiple locals formatting in case of presence?738				} else {739					p!(out,str("local") >i nl);740					for bind in binds {741						if bind.should_start_with_newline {742							p!(out, nl);743						}744						format_comments(&bind.before_trivia, CommentLocation::AboveItem, out);745						p!(out, {bind.value} str(","));746						format_comments(&bind.inline_trivia, CommentLocation::ItemInline, out);747						p!(out, nl);748					}749					if end_comments.should_start_with_newline {750						p!(out, nl);751					}752					format_comments(&end_comments.trivia, CommentLocation::EndOfItems, out);753					p!(out,<i);754				}755				p!(out,str(";") nl);756			}757			Self::StmtAssert(a) => {758				p!(out, {a.assertion()} str(";") nl);759			}760		}761	}762}763764impl Printable for ExprArray {765	fn print(&self, out: &mut PrintItems) {766		fn gen_elements(children: Vec<Child<Expr>>, multi_line: ConditionResolver) -> PrintItems {767			let mut out = PrintItems::new();768			let mut els = children.into_iter().peekable();769			while let Some(el) = els.next() {770				if el.should_start_with_newline {771					p!(out, nl);772				}773				format_comments(&el.before_trivia, CommentLocation::AboveItem, &mut out);774				p!(&mut out, { el.value });775				let has_more = els.peek().is_some();776				if has_more {777					p!(out, str(","));778				} else {779					p!(out, if("trailing comma", multi_line, str(",")));780				}781				format_comments(&el.inline_trivia, CommentLocation::ItemInline, &mut out);782				p!(out, if_else("element separator", multi_line, nl)(sonl));783			}784			out785		}786787		let (children, end_comments) = children_between::<Expr>(788			self.syntax().clone(),789			self.l_brack_token().map(Into::into).as_ref(),790			self.r_brack_token().map(Into::into).as_ref(),791			None,792		);793		if children.is_empty() && end_comments.is_empty() {794			p!(out, str("[ ]"));795			return;796		}797798		let source_is_multiline =799			children.iter().any(|c| c.triggers_multiline) || end_comments.should_start_with_newline;800801		let start = LineNumber::new("arr start line");802		let end = LineNumber::new("arr end line");803		let multi_line: ConditionResolver = if source_is_multiline {804			true_resolver()805		} else {806			Rc::new(move |ctx: &mut ConditionResolverContext| is_multiple_lines(ctx, start, end))807		};808809		let els_items = new_line_group(gen_elements(children, multi_line.clone())).into_rc_path();810811		let els = with_indent_eoi(multi_line, els_items.into(), end_comments);812813		p!(out, str("[") info(start) items(els) str("]") info(end));814	}815}816817impl Printable for ExprBase {818	fn print(&self, out: &mut PrintItems) {819		match self {820			Self::ExprBinary(b) => {821				p!(out, {b.lhs()} str(" ") {b.binary_operator()} str(" ") {b.rhs()});822			}823			Self::ExprUnary(u) => p!(out, {u.unary_operator()} {u.rhs()}),824			// Self::ExprSlice(s) => {825			// 	p!(new: {s.expr()} {s.slice_desc()})826			// }827			// Self::ExprIndex(i) => {828			// 	p!(new: {i.expr()} str(".") {i.index()})829			// }830			// Self::ExprIndexExpr(i) => p!(new: {i.base()} str("[") {i.index()} str("]")),831			// Self::ExprApply(a) => {832			// 	let mut pi = p!(new: {a.expr()} {a.args_desc()});833			// 	if a.tailstrict_kw_token().is_some() {834			// 		p!(out,str(" tailstrict"));835			// 	}836			// 	pi837			// }838			Self::ExprObjExtend(ex) => {839				p!(out, {ex.lhs()} str(" ") {ex.rhs()});840			}841			Self::ExprParened(p) => {842				p!(out, str("(") {p.expr()} str(")"));843			}844			Self::ExprString(s) => p!(out, { s.text() }),845			Self::ExprNumber(n) => p!(out, { n.number() }),846			Self::ExprArray(a) => {847				p!(out, { a });848			}849			Self::ExprObject(obj) => {850				p!(out, { obj.obj_body() });851			}852			Self::ExprArrayComp(arr) => {853				p!(out, str("[") {arr.expr()});854				for spec in arr.comp_specs() {855					p!(out, str(" ") {spec});856				}857				p!(out, str("]"));858			}859			Self::ExprImport(v) => {860				p!(out, {v.import_kind()} str(" ") {v.text()});861			}862			Self::ExprVar(n) => p!(out, { n.name() }),863			// Self::ExprLocal(l) => {864			// }865			Self::ExprIfThenElse(ite) => {866				p!(out, str("if ") {ite.cond()} str(" then ") {ite.then().map(|t| t.expr())});867				if ite.else_kw_token().is_some() || ite.else_().is_some() {868					p!(out, str(" else ") {ite.else_().map(|t| t.expr())});869				}870			}871			Self::ExprFunction(f) => p!(out, str("function") {f.params_desc()} nl {f.expr()}),872			// Self::ExprAssert(a) => p!(new: {a.assertion()} str("; ") {a.expr()}),873			Self::ExprError(e) => p!(out, str("error ") {e.expr()}),874			Self::ExprLiteral(l) => {875				p!(out, { l.literal() });876			}877		}878	}879}880881impl Printable for SourceFile {882	fn print(&self, out: &mut PrintItems) {883		let before = trivia_before(884			self.syntax().clone(),885			self.expr()886				.map(|e| e.syntax().clone())887				.map(Into::into)888				.as_ref(),889		);890		let after = trivia_after(891			self.syntax().clone(),892			self.expr()893				.map(|e| e.syntax().clone())894				.map(Into::into)895				.as_ref(),896		);897		format_comments(&before, CommentLocation::AboveItem, out);898		p!(out, {self.expr()} nl);899		format_comments(&after, CommentLocation::EndOfItems, out);900	}901}902903pub struct FormatOptions {904	pub indent: u8,905	pub use_tabs: bool,906	pub max_width: u32,907}908909impl FormatOptions {910	pub fn new() -> Self {911		Self {912			indent: 4,913			use_tabs: true,914			max_width: 100,915		}916	}917}918919impl Default for FormatOptions {920	fn default() -> Self {921		Self::new()922	}923}924925#[allow(926	clippy::result_large_err,927	reason = "TODO: there should be an intermediate representation for such reports"928)]929pub fn format(input: &str, opts: &FormatOptions) -> Result<String, SnippetBuilder> {930	let (parsed, errors) = jrsonnet_rowan_parser::parse(input);931	if !errors.is_empty() {932		// Reserve one char for EOF display933		let input = format!("{input} ");934		let mut builder = hi_doc::SnippetBuilder::new(input);935		for error in errors {936			builder937				.error(hi_doc::Text::fragment(938					format!("{:?}", error.error),939					Formatting::default(),940				))941				.range(942					error.range.start().into()943						..=(usize::from(error.range.end()) - 1).max(error.range.start().into()),944				)945				.build();946		}947		// let snippet = builder.build();948		return Err(builder);949		// It is possible to recover from this failure, but the output may be broken, as formatter is free to skip950		// ERROR rowan nodes.951		// Recovery needs to be enabled for LSP, though.952	}953	Ok(dprint_core::formatting::format(954		|| {955			let mut out = PrintItems::new();956			parsed.print(&mut out);957			out958		},959		PrintOptions {960			indent_width: opts.indent,961			max_width: opts.max_width,962			use_tabs: opts.use_tabs,963			new_line_text: "\n",964		},965	))966}
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));