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

difftreelog

refactor turn Thunk structure around to reduce allocations

ztvvmqptYaroslav Bolyukin2026-02-12parent: #d5d04bb.patch.diff
in: master

9 files changed

modified.gitignorediffbeforeafterboth
--- a/.gitignore
+++ b/.gitignore
@@ -4,6 +4,10 @@
 .vscode
 .direnv
 
+# Nix artifacts
+/result
+/result-*
+
 cache
 
 jsonnet-cpp
modifiedcrates/jrsonnet-evaluator/src/arr/spec.rsdiffbeforeafterboth
before · crates/jrsonnet-evaluator/src/arr/spec.rs
1use std::{any::Any, cell::RefCell, fmt::Debug, iter, mem::replace};23use jrsonnet_gcmodule::{Cc, Trace};4use jrsonnet_interner::{IBytes, IStr};5use jrsonnet_parser::LocExpr;67use super::ArrValue;8use crate::{9	error::ErrorKind::InfiniteRecursionDetected, evaluate, function::FuncVal, typed::Typed,10	Context, Error, ObjValue, Result, Thunk, Val,11};1213pub trait ArrayLike: Any + Trace + Debug {14	fn len(&self) -> usize;15	fn is_empty(&self) -> bool {16		self.len() == 017	}18	fn get(&self, index: usize) -> Result<Option<Val>>;19	fn get_lazy(&self, index: usize) -> Option<Thunk<Val>>;20	fn get_cheap(&self, index: usize) -> Option<Val>;2122	fn is_cheap(&self) -> bool;23}2425#[derive(Debug, Trace)]26pub struct SliceArray {27	pub(crate) inner: ArrValue,28	pub(crate) from: u32,29	pub(crate) to: u32,30	pub(crate) step: u32,31}3233impl SliceArray {34	fn iter(&self) -> impl Iterator<Item = Result<Val>> + '_ {35		self.inner36			.iter()37			.skip(self.from as usize)38			.take((self.to - self.from) as usize)39			.step_by(self.step as usize)40	}4142	fn iter_lazy(&self) -> impl Iterator<Item = Thunk<Val>> + '_ {43		self.inner44			.iter_lazy()45			.skip(self.from as usize)46			.take((self.to - self.from) as usize)47			.step_by(self.step as usize)48	}4950	fn iter_cheap(&self) -> Option<impl crate::arr::ArrayLikeIter<Val> + '_> {51		Some(52			self.inner53				.iter_cheap()?54				.skip(self.from as usize)55				.take((self.to - self.from) as usize)56				.step_by(self.step as usize),57		)58	}59}60impl ArrayLike for SliceArray {61	fn len(&self) -> usize {62		iter::repeat(())63			.take((self.to - self.from) as usize)64			.step_by(self.step as usize)65			.count()66	}6768	fn get(&self, index: usize) -> Result<Option<Val>> {69		self.iter().nth(index).transpose()70	}7172	fn get_lazy(&self, index: usize) -> Option<Thunk<Val>> {73		self.iter_lazy().nth(index)74	}7576	fn get_cheap(&self, index: usize) -> Option<Val> {77		self.iter_cheap()?.nth(index)78	}79	fn is_cheap(&self) -> bool {80		self.inner.is_cheap()81	}82}8384#[derive(Trace, Debug)]85pub struct CharArray(pub Vec<char>);86impl ArrayLike for CharArray {87	fn len(&self) -> usize {88		self.0.len()89	}9091	fn get(&self, index: usize) -> Result<Option<Val>> {92		Ok(self.get_cheap(index))93	}9495	fn get_lazy(&self, index: usize) -> Option<Thunk<Val>> {96		self.get_cheap(index).map(Thunk::evaluated)97	}9899	fn get_cheap(&self, index: usize) -> Option<Val> {100		self.0.get(index).map(|v| Val::string(*v))101	}102	fn is_cheap(&self) -> bool {103		true104	}105}106107#[derive(Trace, Debug)]108pub struct BytesArray(pub IBytes);109impl ArrayLike for BytesArray {110	fn len(&self) -> usize {111		self.0.len()112	}113114	fn get(&self, index: usize) -> Result<Option<Val>> {115		Ok(self.get_cheap(index))116	}117118	fn get_lazy(&self, index: usize) -> Option<Thunk<Val>> {119		self.get_cheap(index).map(Thunk::evaluated)120	}121122	fn get_cheap(&self, index: usize) -> Option<Val> {123		self.0.get(index).map(|v| Val::Num((*v).into()))124	}125	fn is_cheap(&self) -> bool {126		true127	}128}129130#[derive(Debug, Trace, Clone)]131enum ArrayThunk<T: 'static + Trace> {132	Computed(Val),133	Errored(Error),134	Waiting(T),135	Pending,136}137138#[derive(Debug, Trace, Clone)]139pub struct ExprArray {140	ctx: Context,141	cached: Cc<RefCell<Vec<ArrayThunk<LocExpr>>>>,142}143impl ExprArray {144	pub fn new(ctx: Context, items: impl IntoIterator<Item = LocExpr>) -> Self {145		Self {146			ctx,147			cached: Cc::new(RefCell::new(148				items.into_iter().map(ArrayThunk::Waiting).collect(),149			)),150		}151	}152}153impl ArrayLike for ExprArray {154	fn len(&self) -> usize {155		self.cached.borrow().len()156	}157	fn get(&self, index: usize) -> Result<Option<Val>> {158		if index >= self.len() {159			return Ok(None);160		}161		match &self.cached.borrow()[index] {162			ArrayThunk::Computed(c) => return Ok(Some(c.clone())),163			ArrayThunk::Errored(e) => return Err(e.clone()),164			ArrayThunk::Pending => return Err(InfiniteRecursionDetected.into()),165			ArrayThunk::Waiting(..) => {}166		};167168		let ArrayThunk::Waiting(expr) =169			replace(&mut self.cached.borrow_mut()[index], ArrayThunk::Pending)170		else {171			unreachable!()172		};173174		let new_value = match evaluate(self.ctx.clone(), &expr) {175			Ok(v) => v,176			Err(e) => {177				self.cached.borrow_mut()[index] = ArrayThunk::Errored(e.clone());178				return Err(e);179			}180		};181		self.cached.borrow_mut()[index] = ArrayThunk::Computed(new_value.clone());182		Ok(Some(new_value))183	}184	fn get_lazy(&self, index: usize) -> Option<Thunk<Val>> {185		if index >= self.len() {186			return None;187		}188		match &self.cached.borrow()[index] {189			ArrayThunk::Computed(c) => return Some(Thunk::evaluated(c.clone())),190			ArrayThunk::Errored(e) => return Some(Thunk::errored(e.clone())),191			ArrayThunk::Waiting(_) | ArrayThunk::Pending => {}192		};193194		let arr_thunk = self.clone();195		Some(Thunk!(move || {196			arr_thunk.get(index).transpose().expect("index checked")197		}))198	}199	fn get_cheap(&self, _index: usize) -> Option<Val> {200		None201	}202	fn is_cheap(&self) -> bool {203		false204	}205}206207#[derive(Trace, Debug)]208pub struct ExtendedArray {209	pub a: ArrValue,210	pub b: ArrValue,211	split: usize,212	len: usize,213}214impl ExtendedArray {215	pub fn new(a: ArrValue, b: ArrValue) -> Self {216		let a_len = a.len();217		let b_len = b.len();218		Self {219			a,220			b,221			split: a_len,222			len: a_len.checked_add(b_len).expect("too large array value"),223		}224	}225}226227struct WithExactSize<I>(I, usize);228impl<I, T> Iterator for WithExactSize<I>229where230	I: Iterator<Item = T>,231{232	type Item = T;233234	fn next(&mut self) -> Option<Self::Item> {235		self.0.next()236	}237	fn nth(&mut self, n: usize) -> Option<Self::Item> {238		self.0.nth(n)239	}240	fn size_hint(&self) -> (usize, Option<usize>) {241		(self.1, Some(self.1))242	}243}244impl<I> DoubleEndedIterator for WithExactSize<I>245where246	I: DoubleEndedIterator,247{248	fn next_back(&mut self) -> Option<Self::Item> {249		self.0.next_back()250	}251	fn nth_back(&mut self, n: usize) -> Option<Self::Item> {252		self.0.nth_back(n)253	}254}255impl<I> ExactSizeIterator for WithExactSize<I>256where257	I: Iterator,258{259	fn len(&self) -> usize {260		self.1261	}262}263impl ArrayLike for ExtendedArray {264	fn get(&self, index: usize) -> Result<Option<Val>> {265		if self.split > index {266			self.a.get(index)267		} else {268			self.b.get(index - self.split)269		}270	}271	fn get_lazy(&self, index: usize) -> Option<Thunk<Val>> {272		if self.split > index {273			self.a.get_lazy(index)274		} else {275			self.b.get_lazy(index - self.split)276		}277	}278279	fn len(&self) -> usize {280		self.len281	}282283	fn get_cheap(&self, index: usize) -> Option<Val> {284		if self.split > index {285			self.a.get_cheap(index)286		} else {287			self.b.get_cheap(index - self.split)288		}289	}290	fn is_cheap(&self) -> bool {291		self.a.is_cheap() && self.b.is_cheap()292	}293}294295#[derive(Trace, Debug)]296pub struct LazyArray(pub Vec<Thunk<Val>>);297impl ArrayLike for LazyArray {298	fn len(&self) -> usize {299		self.0.len()300	}301	fn get(&self, index: usize) -> Result<Option<Val>> {302		let Some(v) = self.0.get(index) else {303			return Ok(None);304		};305		v.evaluate().map(Some)306	}307	fn get_cheap(&self, _index: usize) -> Option<Val> {308		None309	}310	fn get_lazy(&self, index: usize) -> Option<Thunk<Val>> {311		self.0.get(index).cloned()312	}313	fn is_cheap(&self) -> bool {314		false315	}316}317318#[derive(Trace, Debug)]319pub struct EagerArray(pub Vec<Val>);320impl ArrayLike for EagerArray {321	fn len(&self) -> usize {322		self.0.len()323	}324325	fn get(&self, index: usize) -> Result<Option<Val>> {326		Ok(self.0.get(index).cloned())327	}328329	fn get_lazy(&self, index: usize) -> Option<Thunk<Val>> {330		self.0.get(index).cloned().map(Thunk::evaluated)331	}332333	fn get_cheap(&self, index: usize) -> Option<Val> {334		self.0.get(index).cloned()335	}336	fn is_cheap(&self) -> bool {337		true338	}339}340341/// Inclusive range type342#[derive(Debug, Trace, PartialEq, Eq)]343pub struct RangeArray {344	start: i32,345	end: i32,346}347impl RangeArray {348	pub fn empty() -> Self {349		Self::new_exclusive(0, 0)350	}351	pub fn new_exclusive(start: i32, end: i32) -> Self {352		end.checked_sub(1)353			.map_or_else(Self::empty, |end| Self { start, end })354	}355	pub fn new_inclusive(start: i32, end: i32) -> Self {356		Self { start, end }357	}358	fn range(&self) -> impl ExactSizeIterator<Item = i32> + DoubleEndedIterator {359		WithExactSize(360			self.start..=self.end,361			(self.end as usize)362				.wrapping_sub(self.start as usize)363				.wrapping_add(1),364		)365	}366}367368impl ArrayLike for RangeArray {369	fn len(&self) -> usize {370		self.range().len()371	}372	fn is_empty(&self) -> bool {373		self.range().len() == 0374	}375376	fn get(&self, index: usize) -> Result<Option<Val>> {377		Ok(self.get_cheap(index))378	}379380	fn get_lazy(&self, index: usize) -> Option<Thunk<Val>> {381		self.get_cheap(index).map(Thunk::evaluated)382	}383384	fn get_cheap(&self, index: usize) -> Option<Val> {385		self.range().nth(index).map(|i| Val::Num(i.into()))386	}387	fn is_cheap(&self) -> bool {388		true389	}390}391392#[derive(Debug, Trace)]393pub struct ReverseArray(pub ArrValue);394impl ArrayLike for ReverseArray {395	fn len(&self) -> usize {396		self.0.len()397	}398399	fn get(&self, index: usize) -> Result<Option<Val>> {400		self.0.get(self.0.len() - index - 1)401	}402403	fn get_lazy(&self, index: usize) -> Option<Thunk<Val>> {404		self.0.get_lazy(self.0.len() - index - 1)405	}406407	fn get_cheap(&self, index: usize) -> Option<Val> {408		self.0.get_cheap(self.0.len() - index - 1)409	}410	fn is_cheap(&self) -> bool {411		self.0.is_cheap()412	}413}414415#[derive(Trace, Debug, Clone)]416pub struct MappedArray<const WITH_INDEX: bool> {417	inner: ArrValue,418	cached: Cc<RefCell<Vec<ArrayThunk<()>>>>,419	mapper: FuncVal,420}421impl<const WITH_INDEX: bool> MappedArray<WITH_INDEX> {422	pub fn new(inner: ArrValue, mapper: FuncVal) -> Self {423		let len = inner.len();424		Self {425			inner,426			cached: Cc::new(RefCell::new(vec![ArrayThunk::Waiting(()); len])),427			mapper,428		}429	}430	fn evaluate(&self, index: usize, value: Val) -> Result<Val> {431		if WITH_INDEX {432			self.mapper.evaluate_simple(&(index, value), false)433		} else {434			self.mapper.evaluate_simple(&(value,), false)435		}436	}437}438impl<const WITH_INDEX: bool> ArrayLike for MappedArray<WITH_INDEX> {439	fn len(&self) -> usize {440		self.cached.borrow().len()441	}442443	fn get(&self, index: usize) -> Result<Option<Val>> {444		if index >= self.len() {445			return Ok(None);446		}447		match &self.cached.borrow()[index] {448			ArrayThunk::Computed(c) => return Ok(Some(c.clone())),449			ArrayThunk::Errored(e) => return Err(e.clone()),450			ArrayThunk::Pending => return Err(InfiniteRecursionDetected.into()),451			ArrayThunk::Waiting(..) => {}452		};453454		let ArrayThunk::Waiting(()) =455			replace(&mut self.cached.borrow_mut()[index], ArrayThunk::Pending)456		else {457			unreachable!()458		};459460		let val = self461			.inner462			.get(index)463			.transpose()464			.expect("index checked")465			.and_then(|r| self.evaluate(index, r));466467		let new_value = match val {468			Ok(v) => v,469			Err(e) => {470				self.cached.borrow_mut()[index] = ArrayThunk::Errored(e.clone());471				return Err(e);472			}473		};474		self.cached.borrow_mut()[index] = ArrayThunk::Computed(new_value.clone());475		Ok(Some(new_value))476	}477	fn get_lazy(&self, index: usize) -> Option<Thunk<Val>> {478		if index >= self.len() {479			return None;480		}481		match &self.cached.borrow()[index] {482			ArrayThunk::Computed(c) => return Some(Thunk::evaluated(c.clone())),483			ArrayThunk::Errored(e) => return Some(Thunk::errored(e.clone())),484			ArrayThunk::Waiting(()) | ArrayThunk::Pending => {}485		};486487		let arr_thunk = self.clone();488		Some(Thunk!(move || {489			arr_thunk.get(index).transpose().expect("index checked")490		}))491	}492493	fn get_cheap(&self, _index: usize) -> Option<Val> {494		None495	}496	fn is_cheap(&self) -> bool {497		false498	}499}500501#[derive(Trace, Debug)]502pub struct RepeatedArray {503	data: ArrValue,504	repeats: usize,505	total_len: usize,506}507impl RepeatedArray {508	pub fn new(data: ArrValue, repeats: usize) -> Option<Self> {509		let total_len = data.len().checked_mul(repeats)?;510		Some(Self {511			data,512			repeats,513			total_len,514		})515	}516}517518impl ArrayLike for RepeatedArray {519	fn len(&self) -> usize {520		self.total_len521	}522523	fn get(&self, index: usize) -> Result<Option<Val>> {524		if index > self.total_len {525			return Ok(None);526		}527		self.data.get(index % self.data.len())528	}529530	fn get_lazy(&self, index: usize) -> Option<Thunk<Val>> {531		if index > self.total_len {532			return None;533		}534		self.data.get_lazy(index % self.data.len())535	}536537	fn get_cheap(&self, index: usize) -> Option<Val> {538		if index > self.total_len {539			return None;540		}541		self.data.get_cheap(index % self.data.len())542	}543	fn is_cheap(&self) -> bool {544		self.data.is_cheap()545	}546}547548#[derive(Trace, Debug)]549pub struct PickObjectValues {550	obj: ObjValue,551	keys: Vec<IStr>,552}553554impl PickObjectValues {555	pub fn new(obj: ObjValue, keys: Vec<IStr>) -> Self {556		Self { obj, keys }557	}558}559560impl ArrayLike for PickObjectValues {561	fn len(&self) -> usize {562		self.keys.len()563	}564565	fn get(&self, index: usize) -> Result<Option<Val>> {566		let Some(key) = self.keys.get(index) else {567			return Ok(None);568		};569		Ok(Some(self.obj.get_or_bail(key.clone())?))570	}571572	fn get_lazy(&self, index: usize) -> Option<Thunk<Val>> {573		let key = self.keys.get(index)?;574		Some(self.obj.get_lazy_or_bail(key.clone()))575	}576577	fn get_cheap(&self, _index: usize) -> Option<Val> {578		None579	}580581	fn is_cheap(&self) -> bool {582		false583	}584}585586#[derive(Trace, Debug)]587pub struct PickObjectKeyValues {588	obj: ObjValue,589	keys: Vec<IStr>,590}591592impl PickObjectKeyValues {593	pub fn new(obj: ObjValue, keys: Vec<IStr>) -> Self {594		Self { obj, keys }595	}596}597598#[derive(Typed)]599pub struct KeyValue {600	key: IStr,601	value: Thunk<Val>,602}603604impl ArrayLike for PickObjectKeyValues {605	fn len(&self) -> usize {606		self.keys.len()607	}608609	fn get(&self, index: usize) -> Result<Option<Val>> {610		let Some(key) = self.keys.get(index) else {611			return Ok(None);612		};613		Ok(Some(614			KeyValue::into_untyped(KeyValue {615				key: key.clone(),616				value: Thunk::evaluated(self.obj.get_or_bail(key.clone())?),617			})618			.expect("convertible"),619		))620	}621622	fn get_lazy(&self, index: usize) -> Option<Thunk<Val>> {623		let key = self.keys.get(index)?;624		// Nothing can fail in the key part, yet value is still625		// lazy-evaluated626		Some(Thunk::evaluated(627			KeyValue::into_untyped(KeyValue {628				key: key.clone(),629				value: self.obj.get_lazy_or_bail(key.clone()),630			})631			.expect("convertible"),632		))633	}634635	fn get_cheap(&self, _index: usize) -> Option<Val> {636		None637	}638639	fn is_cheap(&self) -> bool {640		false641	}642}
modifiedcrates/jrsonnet-evaluator/src/dynamic.rsdiffbeforeafterboth
--- a/crates/jrsonnet-evaluator/src/dynamic.rs
+++ b/crates/jrsonnet-evaluator/src/dynamic.rs
@@ -40,8 +40,9 @@
 impl<T: Trace + Clone> ThunkValue for Pending<T> {
 	type Output = T;
 
-	fn get(self: Box<Self>) -> Result<Self::Output> {
+	fn get(&self) -> Result<Self::Output> {
 		let Some(value) = self.0.get() else {
+			// TODO: Other error?
 			bail!(InfiniteRecursionDetected);
 		};
 		Ok(value.clone())
modifiedcrates/jrsonnet-evaluator/src/obj.rsdiffbeforeafterboth
--- a/crates/jrsonnet-evaluator/src/obj.rs
+++ b/crates/jrsonnet-evaluator/src/obj.rs
@@ -23,7 +23,7 @@
 	gc::WithCapacityExt as _,
 	identity_hash, in_frame,
 	operator::evaluate_add_op,
-	val::ArrValue,
+	val::{ArrValue, ThunkValue},
 	CcUnbound, MaybeUnbound, Result, Thunk, Unbound, Val,
 };
 
@@ -753,13 +753,45 @@
 		if !self.has_field_ex(key.clone(), true) {
 			return None;
 		}
-		let obj = self.clone();
+		#[derive(Trace)]
+		struct ObjFieldThunk {
+			obj: ObjValue,
+			key: IStr,
+		}
+		impl ThunkValue for ObjFieldThunk {
+			type Output = Val;
 
-		Some(Thunk!(move || Ok(obj.get(key)?.expect("field exists"))))
+			fn get(&self) -> Result<Self::Output> {
+				self.obj
+					.get(self.key.clone())
+					.transpose()
+					.expect("field existence checked")
+			}
+		}
+
+		Some(Thunk::new(ObjFieldThunk {
+			obj: self.clone(),
+			key,
+		}))
 	}
 	pub fn get_lazy_or_bail(&self, key: IStr) -> Thunk<Val> {
-		let obj = self.clone();
-		Thunk!(move || obj.get_or_bail(key))
+		#[derive(Trace)]
+		struct ObjFieldThunk {
+			obj: ObjValue,
+			key: IStr,
+		}
+		impl ThunkValue for ObjFieldThunk {
+			type Output = Val;
+
+			fn get(&self) -> Result<Self::Output> {
+				self.obj.get_or_bail(self.key.clone())
+			}
+		}
+
+		Thunk::new(ObjFieldThunk {
+			obj: self.clone(),
+			key,
+		})
 	}
 	pub fn ptr_eq(a: &Self, b: &Self) -> bool {
 		Cc::ptr_eq(&a.0, &b.0)
modifiedcrates/jrsonnet-evaluator/src/val.rsdiffbeforeafterboth
--- a/crates/jrsonnet-evaluator/src/val.rs
+++ b/crates/jrsonnet-evaluator/src/val.rs
@@ -2,13 +2,14 @@
 	cell::RefCell,
 	cmp::Ordering,
 	fmt::{self, Debug, Display},
+	marker::PhantomData,
 	mem::replace,
 	num::NonZeroU32,
 	ops::Deref,
 	rc::Rc,
 };
 
-use jrsonnet_gcmodule::{Acyclic, Cc, Trace, TraceBox};
+use jrsonnet_gcmodule::{cc_dyn, Acyclic, Cc, Trace};
 use jrsonnet_interner::IStr;
 pub use jrsonnet_macros::Thunk;
 use jrsonnet_types::ValType;
@@ -28,56 +29,106 @@
 
 pub trait ThunkValue: Trace {
 	type Output;
-	fn get(self: Box<Self>) -> Result<Self::Output>;
+	fn get(&self) -> Result<Self::Output>;
 }
 
 #[derive(Trace)]
-pub struct ThunkValueClosure<D: Trace, O: 'static> {
-	env: D,
-	// Carries no data, as it is not a real closure, all the
-	// captured environment is stored in `env` field.
-	#[trace(skip)]
-	closure: fn(D) -> Result<O>,
+enum MemoizedClusureThunkInner<D: Trace, T: Trace> {
+	Computed(T),
+	Errored(Error),
+	Waiting {
+		env: D,
+		// Carries no data, as it is not a real closure, all the
+		// captured environment is stored in `env` field.
+		#[trace(skip)]
+		closure: fn(D) -> Result<T>,
+	},
+	Pending,
 }
-impl<D: Trace, O: 'static> ThunkValueClosure<D, O> {
-	pub fn new(env: D, closure: fn(D) -> Result<O>) -> Self {
-		Self { env, closure }
+#[derive(Trace)]
+pub struct MemoizedClosureThunk<D: Trace, T: Trace>(RefCell<MemoizedClusureThunkInner<D, T>>);
+impl<D: Trace, T: Trace> MemoizedClosureThunk<D, T> {
+	pub fn new(env: D, closure: fn(D) -> Result<T>) -> Self {
+		Self(RefCell::new(MemoizedClusureThunkInner::Waiting {
+			env,
+			closure,
+		}))
 	}
 }
-impl<D: Trace, O: 'static> ThunkValue for ThunkValueClosure<D, O> {
-	type Output = O;
 
-	fn get(self: Box<Self>) -> Result<Self::Output> {
-		(self.closure)(self.env)
-	}
-}
+impl<D: Trace, T: Trace + Clone> ThunkValue for MemoizedClosureThunk<D, T> {
+	type Output = T;
 
-#[derive(Trace)]
-enum ThunkInner<T: Trace> {
-	Computed(T),
-	Errored(Error),
-	Waiting(TraceBox<dyn ThunkValue<Output = T>>),
-	Pending,
+	fn get(&self) -> Result<Self::Output> {
+		match &*self.0.borrow() {
+			MemoizedClusureThunkInner::Computed(v) => return Ok(v.clone()),
+			MemoizedClusureThunkInner::Errored(e) => return Err(e.clone()),
+			MemoizedClusureThunkInner::Pending => return Err(InfiniteRecursionDetected.into()),
+			MemoizedClusureThunkInner::Waiting { .. } => (),
+		};
+		let MemoizedClusureThunkInner::Waiting { env, closure } = replace(
+			&mut *self.0.borrow_mut(),
+			MemoizedClusureThunkInner::Pending,
+		) else {
+			unreachable!();
+		};
+		let new_value = match closure(env) {
+			Ok(v) => v,
+			Err(e) => {
+				*self.0.borrow_mut() = MemoizedClusureThunkInner::Errored(e.clone());
+				return Err(e);
+			}
+		};
+		*self.0.borrow_mut() = MemoizedClusureThunkInner::Computed(new_value.clone());
+		Ok(new_value)
+	}
 }
 
-/// Lazily evaluated value
-#[allow(clippy::module_name_repetitions)]
-#[derive(Clone, Trace)]
-pub struct Thunk<T: Trace>(Cc<RefCell<ThunkInner<T>>>);
+cc_dyn!(
+	/// Lazily evaluated value
+	#[derive(Clone)] Thunk<V: Trace>,
+	ThunkValue<Output = V>,
+	pub fn new() {...}
+);
 
 impl<T: Trace> Thunk<T> {
-	pub fn evaluated(val: T) -> Self {
-		Self(Cc::new(RefCell::new(ThunkInner::Computed(val))))
-	}
-	pub fn new(f: impl ThunkValue<Output = T> + 'static) -> Self {
-		Self(Cc::new(RefCell::new(ThunkInner::Waiting(TraceBox(
-			Box::new(f),
-		)))))
+	pub fn evaluated(val: T) -> Self
+	where
+		T: Clone,
+	{
+		#[derive(Trace)]
+		struct EvaluatedThunk<T: Trace>(T);
+		impl<T> ThunkValue for EvaluatedThunk<T>
+		where
+			T: Clone + Trace,
+		{
+			type Output = T;
+
+			fn get(&self) -> Result<Self::Output> {
+				Ok(self.0.clone())
+			}
+		}
+		Self::new(EvaluatedThunk(val))
 	}
 	pub fn errored(e: Error) -> Self {
-		Self(Cc::new(RefCell::new(ThunkInner::Errored(e))))
+		#[derive(Trace)]
+		struct ErroredThunk<T: Trace>(Error, PhantomData<T>);
+		impl<T> ThunkValue for ErroredThunk<T>
+		where
+			T: Trace,
+		{
+			type Output = T;
+
+			fn get(&self) -> Result<Self::Output> {
+				Err(self.0.clone())
+			}
+		}
+		Self::new(ErroredThunk(e, PhantomData))
 	}
-	pub fn result(res: Result<T, Error>) -> Self {
+	pub fn result(res: Result<T, Error>) -> Self
+	where
+		T: Clone,
+	{
 		match res {
 			Ok(o) => Self::evaluated(o),
 			Err(e) => Self::errored(e),
@@ -101,25 +152,7 @@
 	/// - Lazy value evaluation returned error
 	/// - This method was called during inner value evaluation
 	pub fn evaluate(&self) -> Result<T> {
-		match &*self.0.borrow() {
-			ThunkInner::Computed(v) => return Ok(v.clone()),
-			ThunkInner::Errored(e) => return Err(e.clone()),
-			ThunkInner::Pending => return Err(InfiniteRecursionDetected.into()),
-			ThunkInner::Waiting(..) => (),
-		};
-		let ThunkInner::Waiting(value) = replace(&mut *self.0.borrow_mut(), ThunkInner::Pending)
-		else {
-			unreachable!();
-		};
-		let new_value = match value.0.get() {
-			Ok(v) => v,
-			Err(e) => {
-				*self.0.borrow_mut() = ThunkInner::Errored(e.clone());
-				return Err(e);
-			}
-		};
-		*self.0.borrow_mut() = ThunkInner::Computed(new_value.clone());
-		Ok(new_value)
+		self.0.get()
 	}
 }
 
@@ -134,7 +167,7 @@
 	pub fn map<M>(self, mapper: M) -> Thunk<M::Output>
 	where
 		M: ThunkMapper<Input>,
-		M::Output: Trace,
+		M::Output: Trace + Clone,
 	{
 		let inner = self;
 		Thunk!(move || {
@@ -145,7 +178,7 @@
 	}
 }
 
-impl<T: Trace> From<Result<T>> for Thunk<T> {
+impl<T: Trace + Clone> From<Result<T>> for Thunk<T> {
 	fn from(value: Result<T>) -> Self {
 		match value {
 			Ok(o) => Self::evaluated(o),
@@ -162,7 +195,7 @@
 	}
 }
 
-impl<T: Trace + Default> Default for Thunk<T> {
+impl<T: Trace + Default + Clone> Default for Thunk<T> {
 	fn default() -> Self {
 		Self::evaluated(T::default())
 	}
modifiedcrates/jrsonnet-formatter/src/comments.rsdiffbeforeafterboth
--- a/crates/jrsonnet-formatter/src/comments.rs
+++ b/crates/jrsonnet-formatter/src/comments.rs
@@ -73,7 +73,10 @@
 						p!(out, str(" "));
 					}
 					p!(out, str("/* ") string(lines[0].trim().to_string()) str(" */"));
-					if matches!(loc, CommentLocation::AboveItem | CommentLocation::EndOfItems) {
+					if matches!(
+						loc,
+						CommentLocation::AboveItem | CommentLocation::EndOfItems
+					) {
 						p!(out, nl);
 					}
 				} else if !lines.is_empty() {
modifiedcrates/jrsonnet-macros/src/lib.rsdiffbeforeafterboth
--- a/crates/jrsonnet-macros/src/lib.rs
+++ b/crates/jrsonnet-macros/src/lib.rs
@@ -879,6 +879,6 @@
 	quote! {{
 		#move_check
 		#(#trace_check)*
-		::jrsonnet_evaluator::Thunk::new(::jrsonnet_evaluator::val::ThunkValueClosure::new(#env, #closure))
+		::jrsonnet_evaluator::Thunk::new(::jrsonnet_evaluator::val::MemoizedClosureThunk::new(#env, #closure))
 	}}.into()
 }
deletedresultdiffbeforeafterboth
--- a/result
+++ /dev/null
@@ -1 +0,0 @@
-/nix/store/nd6v7jksg1dqhpx4x4vqgy5ry1nkb9lk-jrsonnet-current
\ No newline at end of file
modifiedxtask/src/sourcegen/mod.rsdiffbeforeafterboth
--- a/xtask/src/sourcegen/mod.rs
+++ b/xtask/src/sourcegen/mod.rs
@@ -203,49 +203,57 @@
 			});
 
 			let mut type_positions: HashMap<String, usize> = HashMap::new();
-			let field_positions: Vec<_> = node.fields.iter().map(|field| {
-				let ty_str = field.ty().to_string();
-				let pos = *type_positions.get(&ty_str).unwrap_or(&0);
-				type_positions.insert(ty_str, pos + 1);
-				pos
-			}).collect();
+			let field_positions: Vec<_> = node
+				.fields
+				.iter()
+				.map(|field| {
+					let ty_str = field.ty().to_string();
+					let pos = *type_positions.get(&ty_str).unwrap_or(&0);
+					type_positions.insert(ty_str, pos + 1);
+					pos
+				})
+				.collect();
 
-			let methods = node.fields.iter().zip(field_positions.iter()).map(|(field, &pos)| {
-				let method_name = field.method_name(kinds);
-				let ty = field.ty();
+			let methods = node
+				.fields
+				.iter()
+				.zip(field_positions.iter())
+				.map(|(field, &pos)| {
+					let method_name = field.method_name(kinds);
+					let ty = field.ty();
 
-				if field.is_many() {
-					quote! {
-						pub fn #method_name(&self) -> AstChildren<#ty> {
-							support::children(&self.syntax)
+					if field.is_many() {
+						quote! {
+							pub fn #method_name(&self) -> AstChildren<#ty> {
+								support::children(&self.syntax)
+							}
 						}
-					}
-				} else if let Some(token_kind) = field.token_kind(kinds) {
-					quote! {
-						pub fn #method_name(&self) -> Option<#ty> {
-							support::token(&self.syntax, #token_kind)
+					} else if let Some(token_kind) = field.token_kind(kinds) {
+						quote! {
+							pub fn #method_name(&self) -> Option<#ty> {
+								support::token(&self.syntax, #token_kind)
+							}
 						}
-					}
-				} else if field.is_token_enum(grammar) {
-					quote! {
-						pub fn #method_name(&self) -> Option<#ty> {
-							support::token_child(&self.syntax)
+					} else if field.is_token_enum(grammar) {
+						quote! {
+							pub fn #method_name(&self) -> Option<#ty> {
+								support::token_child(&self.syntax)
+							}
 						}
-					}
-				} else if pos == 0 {
-					quote! {
-						pub fn #method_name(&self) -> Option<#ty> {
-							support::children(&self.syntax).next()
+					} else if pos == 0 {
+						quote! {
+							pub fn #method_name(&self) -> Option<#ty> {
+								support::children(&self.syntax).next()
+							}
 						}
-					}
-				} else {
-					quote! {
-						pub fn #method_name(&self) -> Option<#ty> {
-							support::children(&self.syntax).nth(#pos)
+					} else {
+						quote! {
+							pub fn #method_name(&self) -> Option<#ty> {
+								support::children(&self.syntax).nth(#pos)
+							}
 						}
 					}
-				}
-			});
+				});
 			(
 				quote! {
 					#[pretty_doc_comment_placeholder_workaround]