git.delta.rocks / jrsonnet / refs/commits / 8db09e1bbe2e

difftreelog

Merge pull request #45 from CertainLach/gc-v2

Yaroslav Bolyukin2021-07-04parents: #1f2f94e #56cee93.patch.diff
in: master
Implement tracing Gc with rust-gc

35 files changed

modifiedCargo.lockdiffbeforeafterboth
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -100,12 +100,6 @@
 ]
 
 [[package]]
-name = "closure"
-version = "0.3.0"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "d6173fd61b610d15a7566dd7b7620775627441c4ab9dac8906e17cb93a24b782"
-
-[[package]]
 name = "hashbrown"
 version = "0.9.1"
 source = "registry+https://github.com/rust-lang/crates.io-index"
@@ -164,6 +158,7 @@
 dependencies = [
  "clap",
  "jrsonnet-evaluator",
+ "jrsonnet-gc",
  "jrsonnet-parser",
 ]
 
@@ -175,7 +170,7 @@
  "anyhow",
  "base64",
  "bincode",
- "closure",
+ "jrsonnet-gc",
  "jrsonnet-interner",
  "jrsonnet-parser",
  "jrsonnet-stdlib",
@@ -189,9 +184,31 @@
 ]
 
 [[package]]
+name = "jrsonnet-gc"
+version = "0.4.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "68da8bc2f00117b1373bb8877af03b1d391e4c4800e6585d7279e5b99c919dde"
+dependencies = [
+ "jrsonnet-gc-derive",
+]
+
+[[package]]
+name = "jrsonnet-gc-derive"
+version = "0.4.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "adcba9c387b64b054f06cc4d724905296e21edeeb7506847f3299117a2d92d12"
+dependencies = [
+ "proc-macro2",
+ "quote",
+ "syn",
+ "synstructure",
+]
+
+[[package]]
 name = "jrsonnet-interner"
 version = "0.3.8"
 dependencies = [
+ "jrsonnet-gc",
  "rustc-hash",
  "serde",
 ]
@@ -200,6 +217,7 @@
 name = "jrsonnet-parser"
 version = "0.3.8"
 dependencies = [
+ "jrsonnet-gc",
  "jrsonnet-interner",
  "jrsonnet-stdlib",
  "peg",
@@ -215,6 +233,7 @@
 name = "jrsonnet-types"
 version = "0.3.8"
 dependencies = [
+ "jrsonnet-gc",
  "peg",
 ]
 
@@ -223,6 +242,7 @@
 version = "0.3.8"
 dependencies = [
  "jrsonnet-evaluator",
+ "jrsonnet-gc",
  "jrsonnet-parser",
 ]
 
@@ -405,6 +425,18 @@
 ]
 
 [[package]]
+name = "synstructure"
+version = "0.12.4"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "b834f2d66f734cb897113e34aaff2f1ab4719ca946f9a7358dba8f8064148701"
+dependencies = [
+ "proc-macro2",
+ "quote",
+ "syn",
+ "unicode-xid",
+]
+
+[[package]]
 name = "termcolor"
 version = "1.1.2"
 source = "registry+https://github.com/rust-lang/crates.io-index"
modifiedbindings/jsonnet/Cargo.tomldiffbeforeafterboth
--- a/bindings/jsonnet/Cargo.toml
+++ b/bindings/jsonnet/Cargo.toml
@@ -10,6 +10,7 @@
 [dependencies]
 jrsonnet-evaluator = { path = "../../crates/jrsonnet-evaluator", version = "0.3.8" }
 jrsonnet-parser = { path = "../../crates/jrsonnet-parser", version = "0.3.8" }
+jrsonnet-gc = { version = "0.4.2", features = ["derive"] }
 
 [lib]
 crate-type = ["cdylib"]
modifiedbindings/jsonnet/src/native.rsdiffbeforeafterboth
--- a/bindings/jsonnet/src/native.rs
+++ b/bindings/jsonnet/src/native.rs
@@ -1,8 +1,14 @@
-use jrsonnet_evaluator::{error::Error, native::NativeCallback, EvaluationState, Val};
+use jrsonnet_evaluator::{
+	error::{Error, LocError},
+	native::{NativeCallback, NativeCallbackHandler},
+	EvaluationState, Val,
+};
+use jrsonnet_gc::{unsafe_empty_trace, Finalize, Gc, Trace};
 use jrsonnet_parser::{Param, ParamsDesc};
 use std::{
 	ffi::{c_void, CStr},
 	os::raw::{c_char, c_int},
+	path::Path,
 	rc::Rc,
 };
 
@@ -12,6 +18,39 @@
 	success: *mut c_int,
 ) -> *mut Val;
 
+struct JsonnetNativeCallbackHandler {
+	ctx: *const c_void,
+	cb: JsonnetNativeCallback,
+}
+impl Finalize for JsonnetNativeCallbackHandler {}
+unsafe impl Trace for JsonnetNativeCallbackHandler {
+	unsafe_empty_trace!();
+}
+impl NativeCallbackHandler for JsonnetNativeCallbackHandler {
+	fn call(&self, _from: Option<Rc<Path>>, args: &[Val]) -> Result<Val, LocError> {
+		let mut n_args = Vec::new();
+		for a in args {
+			n_args.push(Some(Box::new(a.clone())));
+		}
+		n_args.push(None);
+		let mut success = 1;
+		let v = unsafe {
+			(self.cb)(
+				self.ctx,
+				&n_args as *const _ as *const *const Val,
+				&mut success,
+			)
+		};
+		let v = unsafe { *Box::from_raw(v) };
+		if success == 1 {
+			Ok(v)
+		} else {
+			let e = v.try_cast_str("native error").expect("error msg");
+			Err(Error::RuntimeError(e).into())
+		}
+	}
+}
+
 /// # Safety
 #[no_mangle]
 pub unsafe extern "C" fn jsonnet_native_callback(
@@ -35,21 +74,9 @@
 
 	vm.add_native(
 		name,
-		Rc::new(NativeCallback::new(params, move |_caller, args| {
-			let mut n_args = Vec::new();
-			for a in args {
-				n_args.push(Some(Box::new(a.clone())));
-			}
-			n_args.push(None);
-			let mut success = 1;
-			let v = cb(ctx, &n_args as *const _ as *const *const Val, &mut success);
-			let v = *Box::from_raw(v);
-			if success == 1 {
-				Ok(v)
-			} else {
-				let e = v.try_cast_str("native error").expect("error msg");
-				Err(Error::RuntimeError(e).into())
-			}
-		})),
+		Gc::new(NativeCallback::new(
+			params,
+			Box::new(JsonnetNativeCallbackHandler { ctx, cb }),
+		)),
 	)
 }
modifiedbindings/jsonnet/src/val_make.rsdiffbeforeafterboth
--- a/bindings/jsonnet/src/val_make.rs
+++ b/bindings/jsonnet/src/val_make.rs
@@ -1,10 +1,10 @@
 //! Create values in VM
 
 use jrsonnet_evaluator::{ArrValue, EvaluationState, ObjValue, Val};
+use jrsonnet_gc::Gc;
 use std::{
 	ffi::CStr,
 	os::raw::{c_char, c_double, c_int},
-	rc::Rc,
 };
 
 /// # Safety
@@ -38,7 +38,7 @@
 
 #[no_mangle]
 pub extern "C" fn jsonnet_json_make_array(_vm: &EvaluationState) -> *mut Val {
-	Box::into_raw(Box::new(Val::Arr(ArrValue::Eager(Rc::new(Vec::new())))))
+	Box::into_raw(Box::new(Val::Arr(ArrValue::Eager(Gc::new(Vec::new())))))
 }
 
 #[no_mangle]
modifiedbindings/jsonnet/src/val_modify.rsdiffbeforeafterboth
--- a/bindings/jsonnet/src/val_modify.rs
+++ b/bindings/jsonnet/src/val_modify.rs
@@ -3,8 +3,9 @@
 //! In jrsonnet every value is immutable, and this code is probally broken
 
 use jrsonnet_evaluator::{ArrValue, EvaluationState, LazyBinding, LazyVal, ObjMember, Val};
+use jrsonnet_gc::Gc;
 use jrsonnet_parser::Visibility;
-use std::{ffi::CStr, os::raw::c_char, rc::Rc};
+use std::{ffi::CStr, os::raw::c_char};
 
 /// # Safety
 ///
@@ -22,7 +23,7 @@
 				new.push(item);
 			}
 			new.push(LazyVal::new_resolved(val.clone()));
-			*arr = Val::Arr(ArrValue::Lazy(Rc::new(new)));
+			*arr = Val::Arr(ArrValue::Lazy(Gc::new(new)));
 		}
 		_ => panic!("should receive array"),
 	}
modifiedcmds/jrsonnet/Cargo.tomldiffbeforeafterboth
--- a/cmds/jrsonnet/Cargo.toml
+++ b/cmds/jrsonnet/Cargo.toml
@@ -8,15 +8,14 @@
 publish = false
 
 [features]
-default = []
+default = ["mimalloc"]
 # Use mimalloc as allocator
-mimalloc = []
+mimalloc = ["mimallocator"]
 
 [dependencies]
 jrsonnet-evaluator = { path = "../../crates/jrsonnet-evaluator", version = "0.3.8" }
 jrsonnet-parser = { path = "../../crates/jrsonnet-parser", version = "0.3.8" }
 jrsonnet-cli = { path = "../../crates/jrsonnet-cli", version = "0.3.8" }
-# TODO: Fix mimalloc compile errors, and use them
 mimallocator = { version = "0.1.3", optional = true }
 thiserror = "1.0"
 
modifiedcmds/jrsonnet/src/main.rsdiffbeforeafterboth
--- a/cmds/jrsonnet/src/main.rs
+++ b/cmds/jrsonnet/src/main.rs
@@ -1,5 +1,5 @@
 use clap::{AppSettings, Clap, IntoApp};
-use jrsonnet_cli::{ConfigureState, GeneralOpts, InputOpts, ManifestOpts, OutputOpts};
+use jrsonnet_cli::{ConfigureState, GcOpts, GeneralOpts, InputOpts, ManifestOpts, OutputOpts};
 use jrsonnet_evaluator::{error::LocError, EvaluationState, ManifestFormat};
 use std::{
 	fs::{create_dir_all, File},
@@ -61,6 +61,8 @@
 	output: OutputOpts,
 	#[clap(flatten)]
 	debug: DebugOpts,
+	#[clap(flatten)]
+	gc: GcOpts,
 }
 
 fn main() {
@@ -114,6 +116,7 @@
 }
 
 fn main_catch(opts: Opts) -> bool {
+	let _printer = opts.gc.stats_printer();
 	let state = EvaluationState::default();
 	if let Err(e) = main_real(&state, opts) {
 		if let Error::Evaluation(e) = e {
@@ -127,6 +130,7 @@
 }
 
 fn main_real(state: &EvaluationState, opts: Opts) -> Result<(), Error> {
+	opts.gc.configure_global();
 	opts.general.configure(&state)?;
 	opts.manifest.configure(&state)?;
 
modifiedcrates/jrsonnet-cli/Cargo.tomldiffbeforeafterboth
--- a/crates/jrsonnet-cli/Cargo.toml
+++ b/crates/jrsonnet-cli/Cargo.toml
@@ -10,6 +10,7 @@
 [dependencies]
 jrsonnet-evaluator = { path = "../../crates/jrsonnet-evaluator", version = "0.3.6", features = ["explaining-traces"] }
 jrsonnet-parser = { path = "../../crates/jrsonnet-parser", version = "0.3.6" }
+jrsonnet-gc = { version = "0.4.2", features = ["derive", "unstable-config", "unstable-stats"] }
 
 [dependencies.clap]
 git = "https://github.com/clap-rs/clap"
modifiedcrates/jrsonnet-cli/src/lib.rsdiffbeforeafterboth
--- a/crates/jrsonnet-cli/src/lib.rs
+++ b/crates/jrsonnet-cli/src/lib.rs
@@ -95,3 +95,55 @@
 		Ok(())
 	}
 }
+
+#[derive(Clap)]
+#[clap(help_heading = "GARBAGE COLLECTION")]
+pub struct GcOpts {
+	/// Min bytes allocated to start garbage collection
+	#[clap(long, default_value = "20000000")]
+	gc_initial_threshold: usize,
+	/// How much heap should grow after unsuccessful garbage collection
+	#[clap(long)]
+	gc_used_space_ratio: Option<f64>,
+	/// Do not skip gc on exit
+	#[clap(long)]
+	gc_collect_on_exit: bool,
+	/// Print gc stats before exit
+	#[clap(long)]
+	gc_print_stats: bool,
+	/// Force garbage collection before printing stats
+	/// Useful for checking for memory leaks
+	/// Does nothing useless --gc-print-stats is specified
+	#[clap(long)]
+	gc_collect_before_printing_stats: bool,
+}
+impl GcOpts {
+	pub fn stats_printer(&self) -> Option<GcStatsPrinter> {
+		self.gc_print_stats
+			.then(|| GcStatsPrinter(self.gc_collect_before_printing_stats))
+	}
+	pub fn configure_global(&self) {
+		jrsonnet_gc::configure(|config| {
+			config.leak_on_drop = !self.gc_collect_on_exit;
+			config.threshold = self.gc_initial_threshold;
+			if let Some(used_space_ratio) = self.gc_used_space_ratio {
+				config.used_space_ratio = used_space_ratio;
+			}
+		});
+	}
+}
+pub struct GcStatsPrinter(bool);
+impl Drop for GcStatsPrinter {
+	fn drop(&mut self) {
+		if self.0 {
+			jrsonnet_gc::force_collect()
+		}
+		eprintln!("=== GC STATS ===");
+		jrsonnet_gc::configure(|c| {
+			eprintln!("Final threshold: {:?}", c.threshold);
+		});
+		let stats = jrsonnet_gc::stats();
+		eprintln!("Collections performed: {}", stats.collections_performed);
+		eprintln!("Bytes still allocated: {}", stats.bytes_allocated);
+	}
+}
modifiedcrates/jrsonnet-evaluator/Cargo.tomldiffbeforeafterboth
--- a/crates/jrsonnet-evaluator/Cargo.toml
+++ b/crates/jrsonnet-evaluator/Cargo.toml
@@ -30,13 +30,12 @@
 jrsonnet-types = { path = "../jrsonnet-types", version = "0.3.8" }
 pathdiff = "0.2.0"
 
-closure = "0.3.0"
-
 md5 = "0.7.0"
 base64 = "0.13.0"
 rustc-hash = "1.1.0"
 
 thiserror = "1.0"
+jrsonnet-gc = { version = "0.4.2", features = ["derive"] }
 
 [dependencies.anyhow]
 version = "1.0"
modifiedcrates/jrsonnet-evaluator/README.mddiffbeforeafterboth
--- a/crates/jrsonnet-evaluator/README.md
+++ b/crates/jrsonnet-evaluator/README.md
@@ -6,9 +6,6 @@
 
 jsonnet stdlib is embedded into evaluator, but there is different modes for this:
 
-- `codegenerated-stdlib`
-  - generates source code for reproducing stdlib AST ([Example](https://gist.githubusercontent.com/CertainLach/7b3149df556f3406f5e9368aaa9f32ec/raw/0c80d8ab9aa7b9288c6219a2779cb2ab37287669/a.rs))
-  - fastest on interpretation, slowest on compilation (it takes more than 5 minutes to optimize them by llvm)
 - `serialized-stdlib`
   - serializes standard library AST using serde
   - slower than `codegenerated-stdlib` at runtime, but have no compilation speed penality
@@ -23,8 +20,6 @@
 Can also be run via `cargo bench`
 
 ```markdown
-# codegenerated-stdlib
-test tests::bench_codegen   ... bench:     401,696 ns/iter (+/- 38,521)
 # serialized-stdlib
 test tests::bench_serialize ... bench:   1,763,999 ns/iter (+/- 76,211)
 # none
@@ -34,7 +29,3 @@
 ## Intrinsics
 
 Some functions from stdlib are implemented as intrinsics
-
-### Intrinsic handling
-
-If indexed jsonnet object has field '__intrinsic_namespace__' of type 'string', then any not found field/method is resolved as `Val::Intrinsic(__intrinsic_namespace__, name)`
modifiedcrates/jrsonnet-evaluator/src/builtin/format.rsdiffbeforeafterboth
--- a/crates/jrsonnet-evaluator/src/builtin/format.rs
+++ b/crates/jrsonnet-evaluator/src/builtin/format.rs
@@ -2,11 +2,13 @@
 #![allow(clippy::too_many_arguments)]
 
 use crate::{error::Error::*, throw, LocError, ObjValue, Result, Val};
+use jrsonnet_gc::Trace;
 use jrsonnet_interner::IStr;
 use jrsonnet_types::ValType;
 use thiserror::Error;
 
-#[derive(Debug, Clone, Error)]
+#[derive(Debug, Clone, Error, Trace)]
+#[trivially_drop]
 pub enum FormatError {
 	#[error("truncated format code")]
 	TruncatedFormatCode,
modifiedcrates/jrsonnet-evaluator/src/builtin/manifest.rsdiffbeforeafterboth
--- a/crates/jrsonnet-evaluator/src/builtin/manifest.rs
+++ b/crates/jrsonnet-evaluator/src/builtin/manifest.rs
@@ -126,6 +126,7 @@
 			buf.push('}');
 		}
 		Val::Func(_) => throw!(RuntimeError("tried to manifest function".into())),
+		Val::DebugGcTraceValue(v) => manifest_json_ex_buf(&v.value, buf, cur_padding, options)?,
 	};
 	Ok(())
 }
modifiedcrates/jrsonnet-evaluator/src/builtin/mod.rsdiffbeforeafterboth
before · crates/jrsonnet-evaluator/src/builtin/mod.rs
1use crate::{2	equals,3	error::{Error::*, Result},4	parse_args, primitive_equals, push, throw, with_state, ArrValue, Context, EvaluationState,5	FuncVal, LazyVal, Val,6};7use format::{format_arr, format_obj};8use jrsonnet_interner::IStr;9use jrsonnet_parser::{ArgsDesc, BinaryOpType, ExprLocation};10use jrsonnet_types::ty;11use std::{collections::HashMap, path::PathBuf, rc::Rc};1213pub mod stdlib;14pub use stdlib::*;1516use self::manifest::{escape_string_json, manifest_json_ex, ManifestJsonOptions, ManifestType};1718pub mod format;19pub mod manifest;20pub mod sort;2122fn std_format(str: IStr, vals: Val) -> Result<Val> {23	push(24		Some(&ExprLocation(Rc::from(PathBuf::from("std.jsonnet")), 0, 0)),25		|| format!("std.format of {}", str),26		|| {27			Ok(match vals {28				Val::Arr(vals) => Val::Str(format_arr(&str, &vals.evaluated()?)?.into()),29				Val::Obj(obj) => Val::Str(format_obj(&str, &obj)?.into()),30				o => Val::Str(format_arr(&str, &[o])?.into()),31			})32		},33	)34}3536type Builtin = fn(context: Context, loc: Option<&ExprLocation>, args: &ArgsDesc) -> Result<Val>;3738type BuiltinsType = HashMap<Box<str>, Builtin>;3940thread_local! {41	static BUILTINS: BuiltinsType = {42		[43			("length".into(), builtin_length as Builtin),44			("type".into(), builtin_type),45			("makeArray".into(), builtin_make_array),46			("codepoint".into(), builtin_codepoint),47			("objectFieldsEx".into(), builtin_object_fields_ex),48			("objectHasEx".into(), builtin_object_has_ex),49			("slice".into(), builtin_slice),50			("primitiveEquals".into(), builtin_primitive_equals),51			("equals".into(), builtin_equals),52			("modulo".into(), builtin_modulo),53			("mod".into(), builtin_mod),54			("floor".into(), builtin_floor),55			("log".into(), builtin_log),56			("pow".into(), builtin_pow),57			("extVar".into(), builtin_ext_var),58			("native".into(), builtin_native),59			("filter".into(), builtin_filter),60			("map".into(), builtin_map),61			("foldl".into(), builtin_foldl),62			("foldr".into(), builtin_foldr),63			("sortImpl".into(), builtin_sort_impl),64			("format".into(), builtin_format),65			("range".into(), builtin_range),66			("char".into(), builtin_char),67			("encodeUTF8".into(), builtin_encode_utf8),68			("md5".into(), builtin_md5),69			("base64".into(), builtin_base64),70			("trace".into(), builtin_trace),71			("join".into(), builtin_join),72			("escapeStringJson".into(), builtin_escape_string_json),73			("manifestJsonEx".into(), builtin_manifest_json_ex),74			("reverse".into(), builtin_reverse),75			("id".into(), builtin_id),76			("strReplace".into(), builtin_str_replace),77			("parseJson".into(), builtin_parse_json),78		].iter().cloned().collect()79	};80}8182fn builtin_length(context: Context, _loc: Option<&ExprLocation>, args: &ArgsDesc) -> Result<Val> {83	parse_args!(context, "length", args, 1, [84		0, x: ty!((string | object | array));85	], {86		Ok(match x {87			Val::Str(n) => Val::Num(n.chars().count() as f64),88			Val::Arr(a) => Val::Num(a.len() as f64),89			Val::Obj(o) => Val::Num(90				o.fields_visibility()91					.into_iter()92					.filter(|(_k, v)| *v)93					.count() as f64,94			),95			_ => unreachable!(),96		})97	})98}99100fn builtin_type(context: Context, _loc: Option<&ExprLocation>, args: &ArgsDesc) -> Result<Val> {101	parse_args!(context, "type", args, 1, [102		0, x: ty!(any);103	], {104		Ok(Val::Str(x.value_type().name().into()))105	})106}107108fn builtin_make_array(109	context: Context,110	_loc: Option<&ExprLocation>,111	args: &ArgsDesc,112) -> Result<Val> {113	parse_args!(context, "makeArray", args, 2, [114		0, sz: ty!(BoundedNumber<(Some(0.0)), (None)>) => Val::Num;115		1, func: ty!(function) => Val::Func;116	], {117		let mut out = Vec::with_capacity(sz as usize);118		for i in 0..sz as usize {119			out.push(LazyVal::new_resolved(func.evaluate_values(120				context.clone(),121				&[Val::Num(i as f64)]122			)?))123		}124		Ok(Val::Arr(out.into()))125	})126}127128fn builtin_codepoint(129	context: Context,130	_loc: Option<&ExprLocation>,131	args: &ArgsDesc,132) -> Result<Val> {133	parse_args!(context, "codepoint", args, 1, [134		0, str: ty!(char) => Val::Str;135	], {136		Ok(Val::Num(str.chars().next().unwrap() as u32 as f64))137	})138}139140fn builtin_object_fields_ex(141	context: Context,142	_loc: Option<&ExprLocation>,143	args: &ArgsDesc,144) -> Result<Val> {145	parse_args!(context, "objectFieldsEx", args, 2, [146		0, obj: ty!(object) => Val::Obj;147		1, inc_hidden: ty!(boolean) => Val::Bool;148	], {149		let out = obj.fields_ex(inc_hidden);150		Ok(Val::Arr(out.into_iter().map(Val::Str).collect::<Vec<_>>().into()))151	})152}153154fn builtin_object_has_ex(155	context: Context,156	_loc: Option<&ExprLocation>,157	args: &ArgsDesc,158) -> Result<Val> {159	parse_args!(context, "objectHasEx", args, 3, [160		0, obj: ty!(object) => Val::Obj;161		1, f: ty!(string) => Val::Str;162		2, inc_hidden: ty!(boolean) => Val::Bool;163	], {164		Ok(Val::Bool(obj.has_field_ex(f, inc_hidden)))165	})166}167168fn builtin_parse_json(169	context: Context,170	_loc: Option<&ExprLocation>,171	args: &ArgsDesc,172) -> Result<Val> {173	parse_args!(context, "parseJson", args, 1, [174		0, s: ty!(string) => Val::Str;175	], {176		let state = EvaluationState::default();177		let path = PathBuf::from("std.parseJson").into();178		state.evaluate_snippet_raw(path ,s)179	})180}181182// faster183fn builtin_slice(context: Context, _loc: Option<&ExprLocation>, args: &ArgsDesc) -> Result<Val> {184	parse_args!(context, "slice", args, 4, [185		0, indexable: ty!((string | array));186		1, index: ty!((number | null));187		2, end: ty!((number | null));188		3, step: ty!((number | null));189	], {190		let index = match index {191			Val::Num(v) => v as usize,192			Val::Null => 0,193			_ => unreachable!(),194		};195		let end = match end {196			Val::Num(v) => v as usize,197			Val::Null => match &indexable {198				Val::Str(s) => s.chars().count(),199				Val::Arr(v) => v.len(),200				_ => unreachable!()201			},202			_ => unreachable!()203		};204		let step = match step {205			Val::Num(v) => v as usize,206			Val::Null => 1,207			_ => unreachable!()208		};209		match &indexable {210			Val::Str(s) => {211				Ok(Val::Str((s.chars().skip(index).take(end-index).step_by(step).collect::<String>()).into()))212			}213			Val::Arr(arr) => {214				Ok(Val::Arr((arr.iter().skip(index).take(end-index).step_by(step).collect::<Result<Vec<Val>>>()?).into()))215			}216			_ => unreachable!()217		}218	})219}220221// faster222fn builtin_primitive_equals(223	context: Context,224	_loc: Option<&ExprLocation>,225	args: &ArgsDesc,226) -> Result<Val> {227	parse_args!(context, "primitiveEquals", args, 2, [228		0, a: ty!(any);229		1, b: ty!(any);230	], {231		Ok(Val::Bool(primitive_equals(&a, &b)?))232	})233}234235// faster236fn builtin_equals(context: Context, _loc: Option<&ExprLocation>, args: &ArgsDesc) -> Result<Val> {237	parse_args!(context, "equals", args, 2, [238		0, a: ty!(any);239		1, b: ty!(any);240	], {241		Ok(Val::Bool(equals(&a, &b)?))242	})243}244245fn builtin_modulo(context: Context, _loc: Option<&ExprLocation>, args: &ArgsDesc) -> Result<Val> {246	parse_args!(context, "modulo", args, 2, [247		0, a: ty!(number) => Val::Num;248		1, b: ty!(number) => Val::Num;249	], {250		Ok(Val::Num(a % b))251	})252}253254fn builtin_mod(context: Context, _loc: Option<&ExprLocation>, args: &ArgsDesc) -> Result<Val> {255	parse_args!(context, "mod", args, 2, [256		0, a: ty!((number | string));257		1, b: ty!(any);258	], {259		match (a, b) {260			(Val::Num(a), Val::Num(b)) => Ok(Val::Num(a % b)),261			(Val::Str(str), vals) => std_format(str, vals),262			(a, b) => throw!(BinaryOperatorDoesNotOperateOnValues(BinaryOpType::Mod, a.value_type(), b.value_type()))263		}264	})265}266267fn builtin_floor(context: Context, _loc: Option<&ExprLocation>, args: &ArgsDesc) -> Result<Val> {268	parse_args!(context, "floor", args, 1, [269		0, x: ty!(number) => Val::Num;270	], {271		Ok(Val::Num(x.floor()))272	})273}274275fn builtin_log(context: Context, _loc: Option<&ExprLocation>, args: &ArgsDesc) -> Result<Val> {276	parse_args!(context, "log", args, 1, [277		0, n: ty!(number) => Val::Num;278	], {279		Ok(Val::Num(n.ln()))280	})281}282283fn builtin_pow(context: Context, _loc: Option<&ExprLocation>, args: &ArgsDesc) -> Result<Val> {284	parse_args!(context, "pow", args, 2, [285		0, x: ty!(number) => Val::Num;286		1, n: ty!(number) => Val::Num;287	], {288		Ok(Val::Num(x.powf(n)))289	})290}291292fn builtin_ext_var(context: Context, _loc: Option<&ExprLocation>, args: &ArgsDesc) -> Result<Val> {293	parse_args!(context, "extVar", args, 1, [294		0, x: ty!(string) => Val::Str;295	], {296		Ok(with_state(|s| s.settings().ext_vars.get(&x).cloned()).ok_or(UndefinedExternalVariable(x))?)297	})298}299300fn builtin_native(context: Context, _loc: Option<&ExprLocation>, args: &ArgsDesc) -> Result<Val> {301	parse_args!(context, "native", args, 1, [302		0, x: ty!(string) => Val::Str;303	], {304		Ok(with_state(|s| s.settings().ext_natives.get(&x).cloned()).map(|v| Val::Func(Rc::new(FuncVal::NativeExt(x.clone(), v)))).ok_or(UndefinedExternalFunction(x))?)305	})306}307308fn builtin_filter(context: Context, _loc: Option<&ExprLocation>, args: &ArgsDesc) -> Result<Val> {309	parse_args!(context, "filter", args, 2, [310		0, func: ty!(function) => Val::Func;311		1, arr: ty!(array) => Val::Arr;312	], {313		Ok(Val::Arr(arr.filter(|val| func314			.evaluate_values(context.clone(), &[val.clone()])?315			.try_cast_bool("filter predicate"))?))316	})317}318319fn builtin_map(context: Context, _loc: Option<&ExprLocation>, args: &ArgsDesc) -> Result<Val> {320	parse_args!(context, "map", args, 2, [321		0, func: ty!(function) => Val::Func;322		1, arr: ty!(array) => Val::Arr;323	], {324		Ok(Val::Arr(arr.map(|val| func325			.evaluate_values(context.clone(), &[val]))?))326	})327}328329fn builtin_foldl(context: Context, _loc: Option<&ExprLocation>, args: &ArgsDesc) -> Result<Val> {330	parse_args!(context, "foldl", args, 3, [331		0, func: ty!(function) => Val::Func;332		1, arr: ty!(array) => Val::Arr;333		2, init: ty!(any);334	], {335		let mut acc = init;336		for i in arr.iter() {337			acc = func.evaluate_values(context.clone(), &[acc, i?])?;338		}339		Ok(acc)340	})341}342343fn builtin_foldr(context: Context, _loc: Option<&ExprLocation>, args: &ArgsDesc) -> Result<Val> {344	parse_args!(context, "foldr", args, 3, [345		0, func: ty!(function) => Val::Func;346		1, arr: ty!(array) => Val::Arr;347		2, init: ty!(any);348	], {349		let mut acc = init;350		for i in arr.iter().rev() {351			acc = func.evaluate_values(context.clone(), &[acc, i?])?;352		}353		Ok(acc)354	})355}356357#[allow(non_snake_case)]358fn builtin_sort_impl(359	context: Context,360	_loc: Option<&ExprLocation>,361	args: &ArgsDesc,362) -> Result<Val> {363	parse_args!(context, "sort", args, 2, [364		0, arr: ty!(array) => Val::Arr;365		1, keyF: ty!(function) => Val::Func;366	], {367		if arr.len() <= 1 {368			return Ok(Val::Arr(arr))369		}370		Ok(Val::Arr(ArrValue::Eager(sort::sort(context, arr.evaluated()?, &keyF)?)))371	})372}373374// faster375fn builtin_format(context: Context, _loc: Option<&ExprLocation>, args: &ArgsDesc) -> Result<Val> {376	parse_args!(context, "format", args, 2, [377		0, str: ty!(string) => Val::Str;378		1, vals: ty!(any)379	], {380		std_format(str, vals)381	})382}383384fn builtin_range(context: Context, _loc: Option<&ExprLocation>, args: &ArgsDesc) -> Result<Val> {385	parse_args!(context, "range", args, 2, [386		0, from: ty!(number) => Val::Num;387		1, to: ty!(number) => Val::Num;388	], {389		if to < from {390			return Ok(Val::Arr(ArrValue::new_eager()))391		}392		let mut out = Vec::with_capacity((1+to as usize-from as usize).max(0));393		for i in from as usize..=to as usize {394			out.push(Val::Num(i as f64));395		}396		Ok(Val::Arr(out.into()))397	})398}399400fn builtin_char(context: Context, _loc: Option<&ExprLocation>, args: &ArgsDesc) -> Result<Val> {401	parse_args!(context, "char", args, 1, [402		0, n: ty!(number) => Val::Num;403	], {404		let mut out = String::new();405		out.push(std::char::from_u32(n as u32).ok_or_else(||406			InvalidUnicodeCodepointGot(n as u32)407		)?);408		Ok(Val::Str(out.into()))409	})410}411412fn builtin_encode_utf8(413	context: Context,414	_loc: Option<&ExprLocation>,415	args: &ArgsDesc,416) -> Result<Val> {417	parse_args!(context, "encodeUTF8", args, 1, [418		0, str: ty!(string) => Val::Str;419	], {420		Ok(Val::Arr((str.bytes().map(|b| Val::Num(b as f64)).collect::<Vec<Val>>()).into()))421	})422}423424fn builtin_md5(context: Context, _loc: Option<&ExprLocation>, args: &ArgsDesc) -> Result<Val> {425	parse_args!(context, "md5", args, 1, [426		0, str: ty!(string) => Val::Str;427	], {428		Ok(Val::Str(format!("{:x}", md5::compute(&str.as_bytes())).into()))429	})430}431432fn builtin_trace(context: Context, loc: Option<&ExprLocation>, args: &ArgsDesc) -> Result<Val> {433	parse_args!(context, "trace", args, 2, [434		0, str: ty!(string) => Val::Str;435		1, rest: ty!(any);436	], {437		eprint!("TRACE:");438		if let Some(loc) = loc {439			with_state(|s|{440				let locs = s.map_source_locations(&loc.0, &[loc.1]);441				eprint!(" {}:{}", loc.0.file_name().unwrap().to_str().unwrap(), locs[0].line);442			});443		}444		eprintln!(" {}", str);445		Ok(rest)446	})447}448449fn builtin_base64(context: Context, _loc: Option<&ExprLocation>, args: &ArgsDesc) -> Result<Val> {450	parse_args!(context, "base64", args, 1, [451		0, input: ty!((string | (Array<number>)));452	], {453		Ok(Val::Str(match input {454			Val::Str(s) => {455				base64::encode(s.bytes().collect::<Vec<_>>()).into()456			},457			Val::Arr(a) => {458				base64::encode(a.iter().map(|v| {459					Ok(v?.unwrap_num()? as u8)460				}).collect::<Result<Vec<_>>>()?).into()461			},462			_ => unreachable!()463		}))464	})465}466467fn builtin_join(context: Context, _loc: Option<&ExprLocation>, args: &ArgsDesc) -> Result<Val> {468	parse_args!(context, "join", args, 2, [469		0, sep: ty!((string | array));470		1, arr: ty!(array) => Val::Arr;471	], {472		Ok(match sep {473			Val::Arr(joiner_items) => {474				let mut out = Vec::new();475476				let mut first = true;477				for item in arr.iter() {478					let item = item?.clone();479					if let Val::Arr(items) = item {480						if !first {481							out.reserve(joiner_items.len());482							// TODO: extend483							for item in joiner_items.iter() {484								out.push(item?);485							}486						}487						first = false;488						out.reserve(items.len());489						// TODO: extend490						for item in items.iter() {491							out.push(item?);492						}493					} else {494						throw!(RuntimeError("in std.join all items should be arrays".into()));495					}496				}497498				Val::Arr(out.into())499			},500			Val::Str(sep) => {501				let mut out = String::new();502503				let mut first = true;504				for item in arr.iter() {505					let item = item?.clone();506					if let Val::Str(item) = item {507						if !first {508							out += &sep;509						}510						first = false;511						out += &item;512					} else {513						throw!(RuntimeError("in std.join all items should be strings".into()));514					}515				}516517				Val::Str(out.into())518			},519			_ => unreachable!()520		})521	})522}523524// faster525fn builtin_escape_string_json(526	context: Context,527	_loc: Option<&ExprLocation>,528	args: &ArgsDesc,529) -> Result<Val> {530	parse_args!(context, "escapeStringJson", args, 1, [531		0, str_: ty!(string) => Val::Str;532	], {533		Ok(Val::Str(escape_string_json(&str_).into()))534	})535}536537// faster538fn builtin_manifest_json_ex(539	context: Context,540	_loc: Option<&ExprLocation>,541	args: &ArgsDesc,542) -> Result<Val> {543	parse_args!(context, "manifestJsonEx", args, 2, [544		0, value: ty!(any);545		1, indent: ty!(string) => Val::Str;546	], {547		Ok(Val::Str(manifest_json_ex(&value, &ManifestJsonOptions {548			padding: &indent,549			mtype: ManifestType::Std,550		})?.into()))551	})552}553554// faster555fn builtin_reverse(context: Context, _loc: Option<&ExprLocation>, args: &ArgsDesc) -> Result<Val> {556	parse_args!(context, "reverse", args, 1, [557		0, value: ty!(array) => Val::Arr;558	], {559		Ok(Val::Arr(value.reversed()))560	})561}562563fn builtin_id(context: Context, _loc: Option<&ExprLocation>, args: &ArgsDesc) -> Result<Val> {564	parse_args!(context, "id", args, 1, [565		0, v: ty!(any);566	], {567		Ok(v)568	})569}570571// faster572fn builtin_str_replace(573	context: Context,574	_loc: Option<&ExprLocation>,575	args: &ArgsDesc,576) -> Result<Val> {577	parse_args!(context, "strReplace", args, 3, [578		0, str: ty!(string) => Val::Str;579		1, from: ty!(string) => Val::Str;580		2, to: ty!(string) => Val::Str;581	], {582		let mut out = String::new();583		let mut last_idx = 0;584		while let Some(idx) = (&str[last_idx..]).find(&from as &str) {585			out.push_str(&str[last_idx..last_idx+idx]);586			out.push_str(&to);587			last_idx += idx + from.len();588		}589		if last_idx == 0 {590			return Ok(Val::Str(str))591		}592		out.push_str(&str[last_idx..]);593		Ok(Val::Str(out.into()))594	})595}596597pub fn call_builtin(598	context: Context,599	loc: Option<&ExprLocation>,600	name: &str,601	args: &ArgsDesc,602) -> Result<Val> {603	BUILTINS604		.with(|builtins| builtins.get(name).copied())605		.ok_or_else(|| IntrinsicNotFound(name.into()))?(context, loc, args)606}
after · crates/jrsonnet-evaluator/src/builtin/mod.rs
1use crate::{2	equals,3	error::{Error::*, Result},4	parse_args, primitive_equals, push, throw, with_state, ArrValue, Context, DebugGcTraceValue,5	EvaluationState, FuncVal, LazyVal, Val,6};7use format::{format_arr, format_obj};8use jrsonnet_gc::Gc;9use jrsonnet_interner::IStr;10use jrsonnet_parser::{ArgsDesc, BinaryOpType, ExprLocation};11use jrsonnet_types::ty;12use std::{collections::HashMap, path::PathBuf, rc::Rc};1314pub mod stdlib;15pub use stdlib::*;1617use self::manifest::{escape_string_json, manifest_json_ex, ManifestJsonOptions, ManifestType};1819pub mod format;20pub mod manifest;21pub mod sort;2223fn std_format(str: IStr, vals: Val) -> Result<Val> {24	push(25		Some(&ExprLocation(Rc::from(PathBuf::from("std.jsonnet")), 0, 0)),26		|| format!("std.format of {}", str),27		|| {28			Ok(match vals {29				Val::Arr(vals) => Val::Str(format_arr(&str, &vals.evaluated()?)?.into()),30				Val::Obj(obj) => Val::Str(format_obj(&str, &obj)?.into()),31				o => Val::Str(format_arr(&str, &[o])?.into()),32			})33		},34	)35}3637type Builtin = fn(context: Context, loc: Option<&ExprLocation>, args: &ArgsDesc) -> Result<Val>;3839type BuiltinsType = HashMap<Box<str>, Builtin>;4041thread_local! {42	static BUILTINS: BuiltinsType = {43		[44			("length".into(), builtin_length as Builtin),45			("type".into(), builtin_type),46			("makeArray".into(), builtin_make_array),47			("codepoint".into(), builtin_codepoint),48			("objectFieldsEx".into(), builtin_object_fields_ex),49			("objectHasEx".into(), builtin_object_has_ex),50			("slice".into(), builtin_slice),51			("primitiveEquals".into(), builtin_primitive_equals),52			("equals".into(), builtin_equals),53			("modulo".into(), builtin_modulo),54			("mod".into(), builtin_mod),55			("floor".into(), builtin_floor),56			("log".into(), builtin_log),57			("pow".into(), builtin_pow),58			("extVar".into(), builtin_ext_var),59			("native".into(), builtin_native),60			("filter".into(), builtin_filter),61			("map".into(), builtin_map),62			("foldl".into(), builtin_foldl),63			("foldr".into(), builtin_foldr),64			("sortImpl".into(), builtin_sort_impl),65			("format".into(), builtin_format),66			("range".into(), builtin_range),67			("char".into(), builtin_char),68			("encodeUTF8".into(), builtin_encode_utf8),69			("md5".into(), builtin_md5),70			("base64".into(), builtin_base64),71			("trace".into(), builtin_trace),72			("gc".into(), builtin_gc),73			("gcTrace".into(), builtin_gc_trace),74			("join".into(), builtin_join),75			("escapeStringJson".into(), builtin_escape_string_json),76			("manifestJsonEx".into(), builtin_manifest_json_ex),77			("reverse".into(), builtin_reverse),78			("id".into(), builtin_id),79			("strReplace".into(), builtin_str_replace),80			("parseJson".into(), builtin_parse_json),81		].iter().cloned().collect()82	};83}8485fn builtin_length(context: Context, _loc: Option<&ExprLocation>, args: &ArgsDesc) -> Result<Val> {86	parse_args!(context, "length", args, 1, [87		0, x: ty!((string | object | array));88	], {89		Ok(match x {90			Val::Str(n) => Val::Num(n.chars().count() as f64),91			Val::Arr(a) => Val::Num(a.len() as f64),92			Val::Obj(o) => Val::Num(93				o.fields_visibility()94					.into_iter()95					.filter(|(_k, v)| *v)96					.count() as f64,97			),98			_ => unreachable!(),99		})100	})101}102103fn builtin_type(context: Context, _loc: Option<&ExprLocation>, args: &ArgsDesc) -> Result<Val> {104	parse_args!(context, "type", args, 1, [105		0, x: ty!(any);106	], {107		Ok(Val::Str(x.value_type().name().into()))108	})109}110111fn builtin_make_array(112	context: Context,113	_loc: Option<&ExprLocation>,114	args: &ArgsDesc,115) -> Result<Val> {116	parse_args!(context, "makeArray", args, 2, [117		0, sz: ty!(BoundedNumber<(Some(0.0)), (None)>) => Val::Num;118		1, func: ty!(function) => Val::Func;119	], {120		let mut out = Vec::with_capacity(sz as usize);121		for i in 0..sz as usize {122			out.push(LazyVal::new_resolved(func.evaluate_values(123				context.clone(),124				&[Val::Num(i as f64)]125			)?))126		}127		Ok(Val::Arr(out.into()))128	})129}130131fn builtin_codepoint(132	context: Context,133	_loc: Option<&ExprLocation>,134	args: &ArgsDesc,135) -> Result<Val> {136	parse_args!(context, "codepoint", args, 1, [137		0, str: ty!(char) => Val::Str;138	], {139		Ok(Val::Num(str.chars().next().unwrap() as u32 as f64))140	})141}142143fn builtin_object_fields_ex(144	context: Context,145	_loc: Option<&ExprLocation>,146	args: &ArgsDesc,147) -> Result<Val> {148	parse_args!(context, "objectFieldsEx", args, 2, [149		0, obj: ty!(object) => Val::Obj;150		1, inc_hidden: ty!(boolean) => Val::Bool;151	], {152		let out = obj.fields_ex(inc_hidden);153		Ok(Val::Arr(out.into_iter().map(Val::Str).collect::<Vec<_>>().into()))154	})155}156157fn builtin_object_has_ex(158	context: Context,159	_loc: Option<&ExprLocation>,160	args: &ArgsDesc,161) -> Result<Val> {162	parse_args!(context, "objectHasEx", args, 3, [163		0, obj: ty!(object) => Val::Obj;164		1, f: ty!(string) => Val::Str;165		2, inc_hidden: ty!(boolean) => Val::Bool;166	], {167		Ok(Val::Bool(obj.has_field_ex(f, inc_hidden)))168	})169}170171fn builtin_parse_json(172	context: Context,173	_loc: Option<&ExprLocation>,174	args: &ArgsDesc,175) -> Result<Val> {176	parse_args!(context, "parseJson", args, 1, [177		0, s: ty!(string) => Val::Str;178	], {179		let state = EvaluationState::default();180		let path = PathBuf::from("std.parseJson").into();181		state.evaluate_snippet_raw(path ,s)182	})183}184185// faster186fn builtin_slice(context: Context, _loc: Option<&ExprLocation>, args: &ArgsDesc) -> Result<Val> {187	parse_args!(context, "slice", args, 4, [188		0, indexable: ty!((string | array));189		1, index: ty!((number | null));190		2, end: ty!((number | null));191		3, step: ty!((number | null));192	], {193		let index = match index {194			Val::Num(v) => v as usize,195			Val::Null => 0,196			_ => unreachable!(),197		};198		let end = match end {199			Val::Num(v) => v as usize,200			Val::Null => match &indexable {201				Val::Str(s) => s.chars().count(),202				Val::Arr(v) => v.len(),203				_ => unreachable!()204			},205			_ => unreachable!()206		};207		let step = match step {208			Val::Num(v) => v as usize,209			Val::Null => 1,210			_ => unreachable!()211		};212		match &indexable {213			Val::Str(s) => {214				Ok(Val::Str((s.chars().skip(index).take(end-index).step_by(step).collect::<String>()).into()))215			}216			Val::Arr(arr) => {217				Ok(Val::Arr((arr.iter().skip(index).take(end-index).step_by(step).collect::<Result<Vec<Val>>>()?).into()))218			}219			_ => unreachable!()220		}221	})222}223224// faster225fn builtin_primitive_equals(226	context: Context,227	_loc: Option<&ExprLocation>,228	args: &ArgsDesc,229) -> Result<Val> {230	parse_args!(context, "primitiveEquals", args, 2, [231		0, a: ty!(any);232		1, b: ty!(any);233	], {234		Ok(Val::Bool(primitive_equals(&a, &b)?))235	})236}237238// faster239fn builtin_equals(context: Context, _loc: Option<&ExprLocation>, args: &ArgsDesc) -> Result<Val> {240	parse_args!(context, "equals", args, 2, [241		0, a: ty!(any);242		1, b: ty!(any);243	], {244		Ok(Val::Bool(equals(&a, &b)?))245	})246}247248fn builtin_modulo(context: Context, _loc: Option<&ExprLocation>, args: &ArgsDesc) -> Result<Val> {249	parse_args!(context, "modulo", args, 2, [250		0, a: ty!(number) => Val::Num;251		1, b: ty!(number) => Val::Num;252	], {253		Ok(Val::Num(a % b))254	})255}256257fn builtin_mod(context: Context, _loc: Option<&ExprLocation>, args: &ArgsDesc) -> Result<Val> {258	parse_args!(context, "mod", args, 2, [259		0, a: ty!((number | string));260		1, b: ty!(any);261	], {262		match (a, b) {263			(Val::Num(a), Val::Num(b)) => Ok(Val::Num(a % b)),264			(Val::Str(str), vals) => std_format(str, vals),265			(a, b) => throw!(BinaryOperatorDoesNotOperateOnValues(BinaryOpType::Mod, a.value_type(), b.value_type()))266		}267	})268}269270fn builtin_floor(context: Context, _loc: Option<&ExprLocation>, args: &ArgsDesc) -> Result<Val> {271	parse_args!(context, "floor", args, 1, [272		0, x: ty!(number) => Val::Num;273	], {274		Ok(Val::Num(x.floor()))275	})276}277278fn builtin_log(context: Context, _loc: Option<&ExprLocation>, args: &ArgsDesc) -> Result<Val> {279	parse_args!(context, "log", args, 1, [280		0, n: ty!(number) => Val::Num;281	], {282		Ok(Val::Num(n.ln()))283	})284}285286fn builtin_pow(context: Context, _loc: Option<&ExprLocation>, args: &ArgsDesc) -> Result<Val> {287	parse_args!(context, "pow", args, 2, [288		0, x: ty!(number) => Val::Num;289		1, n: ty!(number) => Val::Num;290	], {291		Ok(Val::Num(x.powf(n)))292	})293}294295fn builtin_ext_var(context: Context, _loc: Option<&ExprLocation>, args: &ArgsDesc) -> Result<Val> {296	parse_args!(context, "extVar", args, 1, [297		0, x: ty!(string) => Val::Str;298	], {299		Ok(with_state(|s| s.settings().ext_vars.get(&x).cloned()).ok_or(UndefinedExternalVariable(x))?)300	})301}302303fn builtin_native(context: Context, _loc: Option<&ExprLocation>, args: &ArgsDesc) -> Result<Val> {304	parse_args!(context, "native", args, 1, [305		0, x: ty!(string) => Val::Str;306	], {307		Ok(with_state(|s| s.settings().ext_natives.get(&x).cloned()).map(|v| Val::Func(Gc::new(FuncVal::NativeExt(x.clone(), v)))).ok_or(UndefinedExternalFunction(x))?)308	})309}310311fn builtin_filter(context: Context, _loc: Option<&ExprLocation>, args: &ArgsDesc) -> Result<Val> {312	parse_args!(context, "filter", args, 2, [313		0, func: ty!(function) => Val::Func;314		1, arr: ty!(array) => Val::Arr;315	], {316		Ok(Val::Arr(arr.filter(|val| func317			.evaluate_values(context.clone(), &[val.clone()])?318			.try_cast_bool("filter predicate"))?))319	})320}321322fn builtin_map(context: Context, _loc: Option<&ExprLocation>, args: &ArgsDesc) -> Result<Val> {323	parse_args!(context, "map", args, 2, [324		0, func: ty!(function) => Val::Func;325		1, arr: ty!(array) => Val::Arr;326	], {327		Ok(Val::Arr(arr.map(|val| func328			.evaluate_values(context.clone(), &[val]))?))329	})330}331332fn builtin_foldl(context: Context, _loc: Option<&ExprLocation>, args: &ArgsDesc) -> Result<Val> {333	parse_args!(context, "foldl", args, 3, [334		0, func: ty!(function) => Val::Func;335		1, arr: ty!(array) => Val::Arr;336		2, init: ty!(any);337	], {338		let mut acc = init;339		for i in arr.iter() {340			acc = func.evaluate_values(context.clone(), &[acc, i?])?;341		}342		Ok(acc)343	})344}345346fn builtin_foldr(context: Context, _loc: Option<&ExprLocation>, args: &ArgsDesc) -> Result<Val> {347	parse_args!(context, "foldr", args, 3, [348		0, func: ty!(function) => Val::Func;349		1, arr: ty!(array) => Val::Arr;350		2, init: ty!(any);351	], {352		let mut acc = init;353		for i in arr.iter().rev() {354			acc = func.evaluate_values(context.clone(), &[acc, i?])?;355		}356		Ok(acc)357	})358}359360#[allow(non_snake_case)]361fn builtin_sort_impl(362	context: Context,363	_loc: Option<&ExprLocation>,364	args: &ArgsDesc,365) -> Result<Val> {366	parse_args!(context, "sort", args, 2, [367		0, arr: ty!(array) => Val::Arr;368		1, keyF: ty!(function) => Val::Func;369	], {370		if arr.len() <= 1 {371			return Ok(Val::Arr(arr))372		}373		Ok(Val::Arr(ArrValue::Eager(sort::sort(context, arr.evaluated()?, &keyF)?)))374	})375}376377// faster378fn builtin_format(context: Context, _loc: Option<&ExprLocation>, args: &ArgsDesc) -> Result<Val> {379	parse_args!(context, "format", args, 2, [380		0, str: ty!(string) => Val::Str;381		1, vals: ty!(any)382	], {383		std_format(str, vals)384	})385}386387fn builtin_range(context: Context, _loc: Option<&ExprLocation>, args: &ArgsDesc) -> Result<Val> {388	parse_args!(context, "range", args, 2, [389		0, from: ty!(number) => Val::Num;390		1, to: ty!(number) => Val::Num;391	], {392		if to < from {393			return Ok(Val::Arr(ArrValue::new_eager()))394		}395		let mut out = Vec::with_capacity((1+to as usize-from as usize).max(0));396		for i in from as usize..=to as usize {397			out.push(Val::Num(i as f64));398		}399		Ok(Val::Arr(out.into()))400	})401}402403fn builtin_char(context: Context, _loc: Option<&ExprLocation>, args: &ArgsDesc) -> Result<Val> {404	parse_args!(context, "char", args, 1, [405		0, n: ty!(number) => Val::Num;406	], {407		let mut out = String::new();408		out.push(std::char::from_u32(n as u32).ok_or_else(||409			InvalidUnicodeCodepointGot(n as u32)410		)?);411		Ok(Val::Str(out.into()))412	})413}414415fn builtin_encode_utf8(416	context: Context,417	_loc: Option<&ExprLocation>,418	args: &ArgsDesc,419) -> Result<Val> {420	parse_args!(context, "encodeUTF8", args, 1, [421		0, str: ty!(string) => Val::Str;422	], {423		Ok(Val::Arr((str.bytes().map(|b| Val::Num(b as f64)).collect::<Vec<Val>>()).into()))424	})425}426427fn builtin_md5(context: Context, _loc: Option<&ExprLocation>, args: &ArgsDesc) -> Result<Val> {428	parse_args!(context, "md5", args, 1, [429		0, str: ty!(string) => Val::Str;430	], {431		Ok(Val::Str(format!("{:x}", md5::compute(&str.as_bytes())).into()))432	})433}434435fn builtin_trace(context: Context, loc: Option<&ExprLocation>, args: &ArgsDesc) -> Result<Val> {436	parse_args!(context, "trace", args, 2, [437		0, str: ty!(string) => Val::Str;438		1, rest: ty!(any);439	], {440		eprint!("TRACE:");441		if let Some(loc) = loc {442			with_state(|s|{443				let locs = s.map_source_locations(&loc.0, &[loc.1]);444				eprint!(" {}:{}", loc.0.file_name().unwrap().to_str().unwrap(), locs[0].line);445			});446		}447		eprintln!(" {}", str);448		Ok(rest)449	})450}451452fn builtin_gc(context: Context, _loc: Option<&ExprLocation>, args: &ArgsDesc) -> Result<Val> {453	parse_args!(context, "gc", args, 1, [454		0, rest: ty!(any);455	], {456		println!("GC start");457		jrsonnet_gc::force_collect();458		println!("GC done");459460		Ok(rest)461	})462}463464fn builtin_gc_trace(context: Context, _loc: Option<&ExprLocation>, args: &ArgsDesc) -> Result<Val> {465	parse_args!(context, "gcTrace", args, 2, [466		0, name: ty!(string) => Val::Str;467		1, rest: ty!(any);468	], {469		Ok(DebugGcTraceValue::create(name, rest))470	})471}472473fn builtin_base64(context: Context, _loc: Option<&ExprLocation>, args: &ArgsDesc) -> Result<Val> {474	parse_args!(context, "base64", args, 1, [475		0, input: ty!((string | (Array<number>)));476	], {477		Ok(Val::Str(match input {478			Val::Str(s) => {479				base64::encode(s.bytes().collect::<Vec<_>>()).into()480			},481			Val::Arr(a) => {482				base64::encode(a.iter().map(|v| {483					Ok(v?.unwrap_num()? as u8)484				}).collect::<Result<Vec<_>>>()?).into()485			},486			_ => unreachable!()487		}))488	})489}490491fn builtin_join(context: Context, _loc: Option<&ExprLocation>, args: &ArgsDesc) -> Result<Val> {492	parse_args!(context, "join", args, 2, [493		0, sep: ty!((string | array));494		1, arr: ty!(array) => Val::Arr;495	], {496		Ok(match sep {497			Val::Arr(joiner_items) => {498				let mut out = Vec::new();499500				let mut first = true;501				for item in arr.iter() {502					let item = item?.clone();503					if let Val::Arr(items) = item {504						if !first {505							out.reserve(joiner_items.len());506							// TODO: extend507							for item in joiner_items.iter() {508								out.push(item?);509							}510						}511						first = false;512						out.reserve(items.len());513						// TODO: extend514						for item in items.iter() {515							out.push(item?);516						}517					} else {518						throw!(RuntimeError("in std.join all items should be arrays".into()));519					}520				}521522				Val::Arr(out.into())523			},524			Val::Str(sep) => {525				let mut out = String::new();526527				let mut first = true;528				for item in arr.iter() {529					let item = item?.clone();530					if let Val::Str(item) = item {531						if !first {532							out += &sep;533						}534						first = false;535						out += &item;536					} else {537						throw!(RuntimeError("in std.join all items should be strings".into()));538					}539				}540541				Val::Str(out.into())542			},543			_ => unreachable!()544		})545	})546}547548// faster549fn builtin_escape_string_json(550	context: Context,551	_loc: Option<&ExprLocation>,552	args: &ArgsDesc,553) -> Result<Val> {554	parse_args!(context, "escapeStringJson", args, 1, [555		0, str_: ty!(string) => Val::Str;556	], {557		Ok(Val::Str(escape_string_json(&str_).into()))558	})559}560561// faster562fn builtin_manifest_json_ex(563	context: Context,564	_loc: Option<&ExprLocation>,565	args: &ArgsDesc,566) -> Result<Val> {567	parse_args!(context, "manifestJsonEx", args, 2, [568		0, value: ty!(any);569		1, indent: ty!(string) => Val::Str;570	], {571		Ok(Val::Str(manifest_json_ex(&value, &ManifestJsonOptions {572			padding: &indent,573			mtype: ManifestType::Std,574		})?.into()))575	})576}577578// faster579fn builtin_reverse(context: Context, _loc: Option<&ExprLocation>, args: &ArgsDesc) -> Result<Val> {580	parse_args!(context, "reverse", args, 1, [581		0, value: ty!(array) => Val::Arr;582	], {583		Ok(Val::Arr(value.reversed()))584	})585}586587fn builtin_id(context: Context, _loc: Option<&ExprLocation>, args: &ArgsDesc) -> Result<Val> {588	parse_args!(context, "id", args, 1, [589		0, v: ty!(any);590	], {591		Ok(v)592	})593}594595// faster596fn builtin_str_replace(597	context: Context,598	_loc: Option<&ExprLocation>,599	args: &ArgsDesc,600) -> Result<Val> {601	parse_args!(context, "strReplace", args, 3, [602		0, str: ty!(string) => Val::Str;603		1, from: ty!(string) => Val::Str;604		2, to: ty!(string) => Val::Str;605	], {606		let mut out = String::new();607		let mut last_idx = 0;608		while let Some(idx) = (&str[last_idx..]).find(&from as &str) {609			out.push_str(&str[last_idx..last_idx+idx]);610			out.push_str(&to);611			last_idx += idx + from.len();612		}613		if last_idx == 0 {614			return Ok(Val::Str(str))615		}616		out.push_str(&str[last_idx..]);617		Ok(Val::Str(out.into()))618	})619}620621pub fn call_builtin(622	context: Context,623	loc: Option<&ExprLocation>,624	name: &str,625	args: &ArgsDesc,626) -> Result<Val> {627	BUILTINS628		.with(|builtins| builtins.get(name).copied())629		.ok_or_else(|| IntrinsicNotFound(name.into()))?(context, loc, args)630}
modifiedcrates/jrsonnet-evaluator/src/builtin/sort.rsdiffbeforeafterboth
--- a/crates/jrsonnet-evaluator/src/builtin/sort.rs
+++ b/crates/jrsonnet-evaluator/src/builtin/sort.rs
@@ -2,9 +2,9 @@
 	error::{Error, LocError, Result},
 	throw, Context, FuncVal, Val,
 };
-use std::rc::Rc;
+use jrsonnet_gc::{Finalize, Gc, Trace};
 
-#[derive(Debug, Clone, thiserror::Error)]
+#[derive(Debug, Clone, thiserror::Error, Trace, Finalize)]
 pub enum SortError {
 	#[error("sort key should be string or number")]
 	SortKeyShouldBeStringOrNumber,
@@ -59,13 +59,13 @@
 	Ok(sort_type)
 }
 
-pub fn sort(ctx: Context, mut values: Rc<Vec<Val>>, key_getter: &FuncVal) -> Result<Rc<Vec<Val>>> {
+pub fn sort(ctx: Context, values: Gc<Vec<Val>>, key_getter: &FuncVal) -> Result<Gc<Vec<Val>>> {
 	if values.len() <= 1 {
 		return Ok(values);
 	}
 	if key_getter.is_ident() {
-		let mvalues = Rc::make_mut(&mut values);
-		let sort_type = get_sort_type(mvalues, |k| k)?;
+		let mut mvalues = (*values).clone();
+		let sort_type = get_sort_type(&mut mvalues, |k| k)?;
 		match sort_type {
 			SortKeyType::Number => mvalues.sort_by_key(|v| match v {
 				Val::Num(n) => NonNaNf64(*n),
@@ -77,7 +77,7 @@
 			}),
 			SortKeyType::Unknown => unreachable!(),
 		};
-		Ok(values)
+		Ok(Gc::new(mvalues))
 	} else {
 		let mut vk = Vec::with_capacity(values.len());
 		for value in values.iter() {
@@ -98,6 +98,6 @@
 			}),
 			SortKeyType::Unknown => unreachable!(),
 		};
-		Ok(Rc::new(vk.into_iter().map(|v| v.0).collect()))
+		Ok(Gc::new(vk.into_iter().map(|v| v.0).collect()))
 	}
 }
modifiedcrates/jrsonnet-evaluator/src/ctx.rsdiffbeforeafterboth
--- a/crates/jrsonnet-evaluator/src/ctx.rs
+++ b/crates/jrsonnet-evaluator/src/ctx.rs
@@ -1,13 +1,15 @@
 use crate::{
-	error::Error::*, map::LayeredHashMap, resolved_lazy_val, FutureWrapper, LazyBinding, LazyVal,
-	ObjValue, Result, Val,
+	error::Error::*, map::LayeredHashMap, FutureWrapper, LazyBinding, LazyVal, ObjValue, Result,
+	Val,
 };
+use jrsonnet_gc::{Gc, Trace};
 use jrsonnet_interner::IStr;
 use rustc_hash::FxHashMap;
+use std::fmt::Debug;
 use std::hash::BuildHasherDefault;
-use std::{fmt::Debug, rc::Rc};
 
-#[derive(Clone)]
+#[derive(Clone, Trace)]
+#[trivially_drop]
 pub struct ContextCreator(pub Context, pub FutureWrapper<FxHashMap<IStr, LazyBinding>>);
 impl ContextCreator {
 	pub fn create(&self, this: Option<ObjValue>, super_obj: Option<ObjValue>) -> Result<Context> {
@@ -20,23 +22,23 @@
 	}
 }
 
+#[derive(Trace)]
+#[trivially_drop]
 struct ContextInternals {
 	dollar: Option<ObjValue>,
 	this: Option<ObjValue>,
 	super_obj: Option<ObjValue>,
-	bindings: LayeredHashMap<LazyVal>,
+	bindings: LayeredHashMap,
 }
 impl Debug for ContextInternals {
 	fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
-		f.debug_struct("Context")
-			.field("this", &self.this.as_ref().map(|e| Rc::as_ptr(&e.0)))
-			.field("bindings", &self.bindings)
-			.finish()
+		f.debug_struct("Context").finish()
 	}
 }
 
-#[derive(Debug, Clone)]
-pub struct Context(Rc<ContextInternals>);
+#[derive(Debug, Clone, Trace)]
+#[trivially_drop]
+pub struct Context(Gc<ContextInternals>);
 impl Context {
 	pub fn new_future() -> FutureWrapper<Self> {
 		FutureWrapper::new()
@@ -55,7 +57,7 @@
 	}
 
 	pub fn new() -> Self {
-		Self(Rc::new(ContextInternals {
+		Self(Gc::new(ContextInternals {
 			dollar: None,
 			this: None,
 			super_obj: None,
@@ -81,7 +83,7 @@
 	pub fn with_var(self, name: IStr, value: Val) -> Self {
 		let mut new_bindings =
 			FxHashMap::with_capacity_and_hasher(1, BuildHasherDefault::default());
-		new_bindings.insert(name, resolved_lazy_val!(value));
+		new_bindings.insert(name, LazyVal::new_resolved(value));
 		self.extend(new_bindings, None, None, None)
 	}
 
@@ -96,40 +98,21 @@
 		new_this: Option<ObjValue>,
 		new_super_obj: Option<ObjValue>,
 	) -> Self {
-		match Rc::try_unwrap(self.0) {
-			Ok(mut ctx) => {
-				// Extended context aren't used by anything else, we can freely mutate it without cloning
-				if let Some(dollar) = new_dollar {
-					ctx.dollar = Some(dollar);
-				}
-				if let Some(this) = new_this {
-					ctx.this = Some(this);
-				}
-				if let Some(super_obj) = new_super_obj {
-					ctx.super_obj = Some(super_obj);
-				}
-				if !new_bindings.is_empty() {
-					ctx.bindings = ctx.bindings.extend(new_bindings);
-				}
-				Self(Rc::new(ctx))
-			}
-			Err(ctx) => {
-				let dollar = new_dollar.or_else(|| ctx.dollar.clone());
-				let this = new_this.or_else(|| ctx.this.clone());
-				let super_obj = new_super_obj.or_else(|| ctx.super_obj.clone());
-				let bindings = if new_bindings.is_empty() {
-					ctx.bindings.clone()
-				} else {
-					ctx.bindings.clone().extend(new_bindings)
-				};
-				Self(Rc::new(ContextInternals {
-					dollar,
-					this,
-					super_obj,
-					bindings,
-				}))
-			}
-		}
+		let ctx = &self.0;
+		let dollar = new_dollar.or_else(|| ctx.dollar.clone());
+		let this = new_this.or_else(|| ctx.this.clone());
+		let super_obj = new_super_obj.or_else(|| ctx.super_obj.clone());
+		let bindings = if new_bindings.is_empty() {
+			ctx.bindings.clone()
+		} else {
+			ctx.bindings.clone().extend(new_bindings)
+		};
+		Self(Gc::new(ContextInternals {
+			dollar,
+			this,
+			super_obj,
+			bindings,
+		}))
 	}
 	pub fn extend_bound(self, new_bindings: FxHashMap<IStr, LazyVal>) -> Self {
 		let new_this = self.0.this.clone();
@@ -166,22 +149,6 @@
 
 impl PartialEq for Context {
 	fn eq(&self, other: &Self) -> bool {
-		Rc::ptr_eq(&self.0, &other.0)
-	}
-}
-
-#[cfg(feature = "unstable")]
-#[derive(Debug, Clone)]
-pub struct WeakContext(std::rc::Weak<ContextInternals>);
-#[cfg(feature = "unstable")]
-impl WeakContext {
-	pub fn upgrade(&self) -> Context {
-		Context(self.0.upgrade().expect("context is removed"))
-	}
-}
-#[cfg(feature = "unstable")]
-impl PartialEq for WeakContext {
-	fn eq(&self, other: &Self) -> bool {
-		self.0.ptr_eq(&other.0)
+		Gc::ptr_eq(&self.0, &other.0)
 	}
 }
modifiedcrates/jrsonnet-evaluator/src/dynamic.rsdiffbeforeafterboth
--- a/crates/jrsonnet-evaluator/src/dynamic.rs
+++ b/crates/jrsonnet-evaluator/src/dynamic.rs
@@ -1,23 +1,24 @@
-use std::{cell::RefCell, rc::Rc};
+use jrsonnet_gc::{Gc, GcCell, Trace};
 
-#[derive(Clone)]
-pub struct FutureWrapper<V>(pub Rc<RefCell<Option<V>>>);
-impl<T> FutureWrapper<T> {
+#[derive(Clone, Trace)]
+#[trivially_drop]
+pub struct FutureWrapper<V: Trace + 'static>(pub Gc<GcCell<Option<V>>>);
+impl<T: Trace + 'static> FutureWrapper<T> {
 	pub fn new() -> Self {
-		Self(Rc::new(RefCell::new(None)))
+		Self(Gc::new(GcCell::new(None)))
 	}
 	pub fn fill(self, value: T) {
 		assert!(self.0.borrow().is_none(), "wrapper is filled already");
 		self.0.borrow_mut().replace(value);
 	}
 }
-impl<T: Clone> FutureWrapper<T> {
+impl<T: Clone + Trace + 'static> FutureWrapper<T> {
 	pub fn unwrap(&self) -> T {
 		self.0.borrow().as_ref().cloned().unwrap()
 	}
 }
 
-impl<T> Default for FutureWrapper<T> {
+impl<T: Trace + 'static> Default for FutureWrapper<T> {
 	fn default() -> Self {
 		Self::new()
 	}
modifiedcrates/jrsonnet-evaluator/src/error.rsdiffbeforeafterboth
--- a/crates/jrsonnet-evaluator/src/error.rs
+++ b/crates/jrsonnet-evaluator/src/error.rs
@@ -2,6 +2,7 @@
 	builtin::{format::FormatError, sort::SortError},
 	typed::TypeLocError,
 };
+use jrsonnet_gc::Trace;
 use jrsonnet_interner::IStr;
 use jrsonnet_parser::{BinaryOpType, ExprLocation, UnaryOpType};
 use jrsonnet_types::ValType;
@@ -11,7 +12,8 @@
 };
 use thiserror::Error;
 
-#[derive(Error, Debug, Clone)]
+#[derive(Error, Debug, Clone, Trace)]
+#[trivially_drop]
 pub enum Error {
 	#[error("intrinsic not found: {0}")]
 	IntrinsicNotFound(IStr),
@@ -91,6 +93,7 @@
 	ImportSyntaxError {
 		path: Rc<Path>,
 		source_code: IStr,
+		#[unsafe_ignore_trace]
 		error: Box<jrsonnet_parser::ParseError>,
 	},
 
@@ -98,6 +101,8 @@
 	RuntimeError(IStr),
 	#[error("stack overflow, try to reduce recursion, or set --max-stack to bigger value")]
 	StackOverflow,
+	#[error("infinite recursion detected")]
+	RecursiveLazyValueEvaluation,
 	#[error("tried to index by fractional value")]
 	FractionalIndex,
 	#[error("attempted to divide by zero")]
@@ -145,15 +150,18 @@
 	}
 }
 
-#[derive(Clone, Debug)]
+#[derive(Clone, Debug, Trace)]
+#[trivially_drop]
 pub struct StackTraceElement {
 	pub location: Option<ExprLocation>,
 	pub desc: String,
 }
-#[derive(Debug, Clone)]
+#[derive(Debug, Clone, Trace)]
+#[trivially_drop]
 pub struct StackTrace(pub Vec<StackTraceElement>);
 
-#[derive(Debug, Clone)]
+#[derive(Debug, Clone, Trace)]
+#[trivially_drop]
 pub struct LocError(Box<(Error, StackTrace)>);
 impl LocError {
 	pub fn new(e: Error) -> Self {
modifiedcrates/jrsonnet-evaluator/src/evaluate.rsdiffbeforeafterboth
--- a/crates/jrsonnet-evaluator/src/evaluate.rs
+++ b/crates/jrsonnet-evaluator/src/evaluate.rs
@@ -1,8 +1,9 @@
 use crate::{
-	equals, error::Error::*, lazy_val, push, throw, with_state, ArrValue, Context, ContextCreator,
-	FuncDesc, FuncVal, FutureWrapper, LazyBinding, LazyVal, ObjMember, ObjValue, Result, Val,
+	equals, error::Error::*, push, throw, with_state, ArrValue, Bindable, Context, ContextCreator,
+	FuncDesc, FuncVal, FutureWrapper, LazyBinding, LazyVal, LazyValValue, ObjMember, ObjValue,
+	ObjectAssertion, Result, Val,
 };
-use closure::closure;
+use jrsonnet_gc::{Gc, Trace};
 use jrsonnet_interner::IStr;
 use jrsonnet_parser::{
 	ArgsDesc, AssertStmt, BinaryOpType, BindSpec, CompSpec, Expr, ExprLocation, FieldMember,
@@ -11,7 +12,7 @@
 };
 use jrsonnet_types::ValType;
 use rustc_hash::{FxHashMap, FxHasher};
-use std::{collections::HashMap, hash::BuildHasherDefault, rc::Rc};
+use std::{collections::HashMap, hash::BuildHasherDefault};
 
 pub fn evaluate_binding_in_future(
 	b: &BindSpec,
@@ -20,17 +21,49 @@
 	let b = b.clone();
 	if let Some(params) = &b.params {
 		let params = params.clone();
-		LazyVal::new(Box::new(move || {
-			Ok(evaluate_method(
-				context_creator.unwrap(),
-				b.name.clone(),
-				params.clone(),
-				b.value.clone(),
-			))
+
+		#[derive(Trace)]
+		#[trivially_drop]
+		struct LazyMethodBinding {
+			context_creator: FutureWrapper<Context>,
+			name: IStr,
+			params: ParamsDesc,
+			value: LocExpr,
+		}
+		impl LazyValValue for LazyMethodBinding {
+			fn get(self: Box<Self>) -> Result<Val> {
+				Ok(evaluate_method(
+					self.context_creator.unwrap(),
+					self.name,
+					self.params,
+					self.value,
+				))
+			}
+		}
+
+		LazyVal::new(Box::new(LazyMethodBinding {
+			context_creator,
+			name: b.name.clone(),
+			params,
+			value: b.value.clone(),
 		}))
 	} else {
-		LazyVal::new(Box::new(move || {
-			evaluate_named(context_creator.unwrap(), &b.value, b.name.clone())
+		#[derive(Trace)]
+		#[trivially_drop]
+		struct LazyNamedBinding {
+			context_creator: FutureWrapper<Context>,
+			name: IStr,
+			value: LocExpr,
+		}
+		impl LazyValValue for LazyNamedBinding {
+			fn get(self: Box<Self>) -> Result<Val> {
+				evaluate_named(self.context_creator.unwrap(), &self.value, self.name)
+			}
+		}
+		LazyVal::new(Box::new(LazyNamedBinding {
+			context_creator,
+			name: b.name.clone(),
+			value: b.value,
 		}))
 	}
 }
@@ -39,37 +72,114 @@
 	let b = b.clone();
 	if let Some(params) = &b.params {
 		let params = params.clone();
+
+		#[derive(Trace)]
+		#[trivially_drop]
+		struct BindableMethodLazyVal {
+			this: Option<ObjValue>,
+			super_obj: Option<ObjValue>,
+
+			context_creator: ContextCreator,
+			name: IStr,
+			params: ParamsDesc,
+			value: LocExpr,
+		}
+		impl LazyValValue for BindableMethodLazyVal {
+			fn get(self: Box<Self>) -> Result<Val> {
+				Ok(evaluate_method(
+					self.context_creator.create(self.this, self.super_obj)?,
+					self.name,
+					self.params,
+					self.value,
+				))
+			}
+		}
+
+		#[derive(Trace)]
+		#[trivially_drop]
+		struct BindableMethod {
+			context_creator: ContextCreator,
+			name: IStr,
+			params: ParamsDesc,
+			value: LocExpr,
+		}
+		impl Bindable for BindableMethod {
+			fn bind(&self, this: Option<ObjValue>, super_obj: Option<ObjValue>) -> Result<LazyVal> {
+				Ok(LazyVal::new(Box::new(BindableMethodLazyVal {
+					this,
+					super_obj,
+
+					context_creator: self.context_creator.clone(),
+					name: self.name.clone(),
+					params: self.params.clone(),
+					value: self.value.clone(),
+				})))
+			}
+		}
+
 		(
 			b.name.clone(),
-			LazyBinding::Bindable(Rc::new(move |this, super_obj| {
-				Ok(lazy_val!(
-					closure!(clone b, clone params, clone context_creator, || Ok(evaluate_method(
-						context_creator.create(this.clone(), super_obj.clone())?,
-						b.name.clone(),
-						params.clone(),
-						b.value.clone(),
-					)))
-				))
-			})),
+			LazyBinding::Bindable(Gc::new(Box::new(BindableMethod {
+				context_creator,
+				name: b.name.clone(),
+				params,
+				value: b.value.clone(),
+			}))),
 		)
 	} else {
+		#[derive(Trace)]
+		#[trivially_drop]
+		struct BindableNamedLazyVal {
+			this: Option<ObjValue>,
+			super_obj: Option<ObjValue>,
+
+			context_creator: ContextCreator,
+			name: IStr,
+			value: LocExpr,
+		}
+		impl LazyValValue for BindableNamedLazyVal {
+			fn get(self: Box<Self>) -> Result<Val> {
+				evaluate_named(
+					self.context_creator.create(self.this, self.super_obj)?,
+					&self.value,
+					self.name,
+				)
+			}
+		}
+
+		#[derive(Trace)]
+		#[trivially_drop]
+		struct BindableNamed {
+			context_creator: ContextCreator,
+			name: IStr,
+			value: LocExpr,
+		}
+		impl Bindable for BindableNamed {
+			fn bind(&self, this: Option<ObjValue>, super_obj: Option<ObjValue>) -> Result<LazyVal> {
+				Ok(LazyVal::new(Box::new(BindableNamedLazyVal {
+					this,
+					super_obj,
+
+					context_creator: self.context_creator.clone(),
+					name: self.name.clone(),
+					value: self.value.clone(),
+				})))
+			}
+		}
+
 		(
 			b.name.clone(),
-			LazyBinding::Bindable(Rc::new(move |this, super_obj| {
-				Ok(lazy_val!(closure!(clone context_creator, clone b, ||
-					evaluate_named(
-						context_creator.create(this.clone(), super_obj.clone())?,
-						&b.value,
-						b.name.clone()
-					)
-				)))
-			})),
+			LazyBinding::Bindable(Gc::new(Box::new(BindableNamed {
+				context_creator,
+				name: b.name.clone(),
+				value: b.value.clone(),
+			}))),
 		)
 	}
 }
 
 pub fn evaluate_method(ctx: Context, name: IStr, params: ParamsDesc, body: LocExpr) -> Val {
-	Val::Func(Rc::new(FuncVal::Normal(FuncDesc {
+	Val::Func(Gc::new(FuncVal::Normal(FuncDesc {
 		name,
 		ctx,
 		params,
@@ -105,6 +215,9 @@
 
 pub fn evaluate_add_op(a: &Val, b: &Val) -> Result<Val> {
 	Ok(match (a, b) {
+		(Val::DebugGcTraceValue(v1), Val::DebugGcTraceValue(v2)) => {
+			evaluate_add_op(&v1.value, &v2.value)?
+		}
 		(Val::Str(v1), Val::Str(v2)) => Val::Str(((**v1).to_owned() + v2).into()),
 
 		// Can't use generic json serialization way, because it depends on number to string concatenation (std.jsonnet:890)
@@ -257,7 +370,7 @@
 	}
 
 	let mut new_members = FxHashMap::default();
-	let mut assertions = Vec::new();
+	let mut assertions: Vec<Box<dyn ObjectAssertion>> = Vec::new();
 	for member in members.iter() {
 		match member {
 			Member::Field(FieldMember {
@@ -272,20 +385,37 @@
 					continue;
 				}
 				let name = name.unwrap();
+
+				#[derive(Trace)]
+				#[trivially_drop]
+				struct ObjMemberBinding {
+					context_creator: ContextCreator,
+					value: LocExpr,
+					name: IStr,
+				}
+				impl Bindable for ObjMemberBinding {
+					fn bind(
+						&self,
+						this: Option<ObjValue>,
+						super_obj: Option<ObjValue>,
+					) -> Result<LazyVal> {
+						Ok(LazyVal::new_resolved(evaluate_named(
+							self.context_creator.create(this, super_obj)?,
+							&self.value,
+							self.name.clone(),
+						)?))
+					}
+				}
 				new_members.insert(
 					name.clone(),
 					ObjMember {
 						add: *plus,
 						visibility: *visibility,
-						invoke: LazyBinding::Bindable(Rc::new(
-							closure!(clone name, clone value, clone context_creator, |this, super_obj| {
-								Ok(LazyVal::new_resolved(evaluate_named(
-									context_creator.create(this, super_obj)?,
-									&value,
-									name.clone(),
-								)?))
-							}),
-						)),
+						invoke: LazyBinding::Bindable(Gc::new(Box::new(ObjMemberBinding {
+							context_creator: context_creator.clone(),
+							value: value.clone(),
+							name,
+						}))),
 						location: value.1.clone(),
 					},
 				);
@@ -301,33 +431,69 @@
 					continue;
 				}
 				let name = name.unwrap();
+				#[derive(Trace)]
+				#[trivially_drop]
+				struct ObjMemberBinding {
+					context_creator: ContextCreator,
+					value: LocExpr,
+					params: ParamsDesc,
+					name: IStr,
+				}
+				impl Bindable for ObjMemberBinding {
+					fn bind(
+						&self,
+						this: Option<ObjValue>,
+						super_obj: Option<ObjValue>,
+					) -> Result<LazyVal> {
+						Ok(LazyVal::new_resolved(evaluate_method(
+							self.context_creator.create(this, super_obj)?,
+							self.name.clone(),
+							self.params.clone(),
+							self.value.clone(),
+						)))
+					}
+				}
 				new_members.insert(
 					name.clone(),
 					ObjMember {
 						add: false,
 						visibility: Visibility::Hidden,
-						invoke: LazyBinding::Bindable(Rc::new(
-							closure!(clone value, clone context_creator, clone params, clone name, |this, super_obj| {
-								// TODO: Assert
-								Ok(LazyVal::new_resolved(evaluate_method(
-									context_creator.create(this, super_obj)?,
-									name.clone(),
-									params.clone(),
-									value.clone(),
-								)))
-							}),
-						)),
+						invoke: LazyBinding::Bindable(Gc::new(Box::new(ObjMemberBinding {
+							context_creator: context_creator.clone(),
+							value: value.clone(),
+							params: params.clone(),
+							name,
+						}))),
 						location: value.1.clone(),
 					},
 				);
 			}
 			Member::BindStmt(_) => {}
 			Member::AssertStmt(stmt) => {
-				assertions.push(stmt.clone());
+				#[derive(Trace)]
+				#[trivially_drop]
+				struct ObjectAssert {
+					context_creator: ContextCreator,
+					assert: AssertStmt,
+				}
+				impl ObjectAssertion for ObjectAssert {
+					fn run(
+						&self,
+						this: Option<ObjValue>,
+						super_obj: Option<ObjValue>,
+					) -> Result<()> {
+						let ctx = self.context_creator.create(this, super_obj)?;
+						evaluate_assert(ctx, &self.assert)
+					}
+				}
+				assertions.push(Box::new(ObjectAssert {
+					context_creator: context_creator.clone(),
+					assert: stmt.clone(),
+				}));
 			}
 		}
 	}
-	let this = ObjValue::new(context, None, Rc::new(new_members), Rc::new(assertions));
+	let this = ObjValue::new(None, Gc::new(new_members), Gc::new(assertions));
 	future_this.fill(this.clone());
 	Ok(this)
 }
@@ -361,16 +527,38 @@
 				match key {
 					Val::Null => {}
 					Val::Str(n) => {
+						#[derive(Trace)]
+						#[trivially_drop]
+						struct ObjCompBinding {
+							context: Context,
+							value: LocExpr,
+						}
+						impl Bindable for ObjCompBinding {
+							fn bind(
+								&self,
+								this: Option<ObjValue>,
+								_super_obj: Option<ObjValue>,
+							) -> Result<LazyVal> {
+								Ok(LazyVal::new_resolved(evaluate(
+									self.context.clone().extend(
+										FxHashMap::default(),
+										None,
+										this,
+										None,
+									),
+									&self.value,
+								)?))
+							}
+						}
 						new_members.insert(
 							n,
 							ObjMember {
 								add: false,
 								visibility: Visibility::Normal,
-								invoke: LazyBinding::Bindable(Rc::new(
-									closure!(clone ctx, clone obj.value, |this, _super_obj| {
-										Ok(LazyVal::new_resolved(evaluate(ctx.clone().extend(FxHashMap::default(), None, this, None), &value)?))
-									}),
-								)),
+								invoke: LazyBinding::Bindable(Gc::new(Box::new(ObjCompBinding {
+									context: ctx,
+									value: obj.value.clone(),
+								}))),
 								location: obj.value.1.clone(),
 							},
 						);
@@ -381,7 +569,7 @@
 				Ok(())
 			})?;
 
-			let this = ObjValue::new(context, None, Rc::new(new_members), Rc::new(Vec::new()));
+			let this = ObjValue::new(None, Gc::new(new_members), Gc::new(Vec::new()));
 			future_this.fill(this.clone());
 			this
 		}
@@ -486,7 +674,7 @@
 							if let Some(v) = v.get(s.clone())? {
 								Ok(v)
 							} else if v.get("__intrinsic_namespace__".into())?.is_some() {
-								Ok(Val::Func(Rc::new(FuncVal::Intrinsic(s))))
+								Ok(Val::Func(Gc::new(FuncVal::Intrinsic(s))))
 							} else {
 								throw!(NoSuchField(s))
 							}
@@ -549,11 +737,22 @@
 		Arr(items) => {
 			let mut out = Vec::with_capacity(items.len());
 			for item in items {
-				out.push(LazyVal::new(Box::new(
-					closure!(clone context, clone item, || {
-						evaluate(context.clone(), &item)
-					}),
-				)));
+				// TODO: Implement ArrValue::Lazy with same context for every element?
+				#[derive(Trace)]
+				#[trivially_drop]
+				struct ArrayElement {
+					context: Context,
+					item: LocExpr,
+				}
+				impl LazyValValue for ArrayElement {
+					fn get(self: Box<Self>) -> Result<Val> {
+						evaluate(self.context, &self.item)
+					}
+				}
+				out.push(LazyVal::new(Box::new(ArrayElement {
+					context: context.clone(),
+					item: item.clone(),
+				})));
 			}
 			Val::Arr(out.into())
 		}
@@ -563,7 +762,7 @@
 				out.push(evaluate(ctx, expr)?);
 				Ok(())
 			})?;
-			Val::Arr(ArrValue::Eager(Rc::new(out)))
+			Val::Arr(ArrValue::Eager(Gc::new(out)))
 		}
 		Obj(body) => Val::Obj(evaluate_object(context, body)?),
 		ObjExtend(s, t) => evaluate_add_op(
@@ -576,7 +775,7 @@
 		Function(params, body) => {
 			evaluate_method(context, "anonymous".into(), params.clone(), body.clone())
 		}
-		Intrinsic(name) => Val::Func(Rc::new(FuncVal::Intrinsic(name.clone()))),
+		Intrinsic(name) => Val::Func(Gc::new(FuncVal::Intrinsic(name.clone()))),
 		AssertExpr(assert, returned) => {
 			evaluate_assert(context.clone(), assert)?;
 			evaluate(context, returned)?
modifiedcrates/jrsonnet-evaluator/src/function.rsdiffbeforeafterboth
--- a/crates/jrsonnet-evaluator/src/function.rs
+++ b/crates/jrsonnet-evaluator/src/function.rs
@@ -1,7 +1,7 @@
-use crate::{error::Error::*, evaluate, lazy_val, resolved_lazy_val, throw, Context, Result, Val};
-use closure::closure;
+use crate::{error::Error::*, evaluate, throw, Context, LazyVal, LazyValValue, Result, Val};
+use jrsonnet_gc::Trace;
 use jrsonnet_interner::IStr;
-use jrsonnet_parser::{ArgsDesc, ParamsDesc};
+use jrsonnet_parser::{ArgsDesc, LocExpr, ParamsDesc};
 use rustc_hash::FxHashMap;
 use std::{collections::HashMap, hash::BuildHasherDefault};
 
@@ -53,9 +53,24 @@
 			throw!(FunctionParameterNotBoundInCall(p.0.clone()));
 		};
 		let val = if tailstrict {
-			resolved_lazy_val!(evaluate(ctx, expr)?)
+			LazyVal::new_resolved(evaluate(ctx, expr)?)
 		} else {
-			lazy_val!(closure!(clone ctx, clone expr, ||evaluate(ctx.clone(), &expr)))
+			#[derive(Trace)]
+			#[trivially_drop]
+			struct EvaluateLazyVal {
+				context: Context,
+				expr: LocExpr,
+			}
+			impl LazyValValue for EvaluateLazyVal {
+				fn get(self: Box<Self>) -> Result<Val> {
+					evaluate(self.context, &self.expr)
+				}
+			}
+
+			LazyVal::new(Box::new(EvaluateLazyVal {
+				context: ctx.clone(),
+				expr: expr.clone(),
+			}))
 		};
 		out.insert(p.0.clone(), val);
 	}
@@ -89,19 +104,31 @@
 	// Fill defaults
 	for (id, p) in params.iter().enumerate() {
 		let val = if let Some(arg) = positioned_args[id].take() {
-			resolved_lazy_val!(arg)
+			LazyVal::new_resolved(arg)
 		} else if let Some(default) = &p.1 {
 			if tailstrict {
-				resolved_lazy_val!(evaluate(
+				LazyVal::new_resolved(evaluate(
 					body_ctx.clone().expect(NO_DEFAULT_CONTEXT),
-					default
+					default,
 				)?)
 			} else {
 				let body_ctx = body_ctx.clone();
 				let default = default.clone();
-				lazy_val!(move || {
-					evaluate(body_ctx.clone().expect(NO_DEFAULT_CONTEXT), &default)
-				})
+				#[derive(Trace)]
+				#[trivially_drop]
+				struct EvaluateLazyVal {
+					body_ctx: Option<Context>,
+					default: LocExpr,
+				}
+				impl LazyValValue for EvaluateLazyVal {
+					fn get(self: Box<Self>) -> Result<Val> {
+						evaluate(
+							self.body_ctx.clone().expect(NO_DEFAULT_CONTEXT),
+							&self.default,
+						)
+					}
+				}
+				LazyVal::new(Box::new(EvaluateLazyVal { body_ctx, default }))
 			}
 		} else {
 			throw!(FunctionParameterNotBoundInCall(p.0.clone()));
@@ -135,7 +162,7 @@
 		} else {
 			throw!(FunctionParameterNotBoundInCall(p.0.clone()));
 		};
-		out.insert(p.0.clone(), resolved_lazy_val!(val));
+		out.insert(p.0.clone(), LazyVal::new_resolved(val));
 	}
 
 	Ok(body_ctx.unwrap_or(ctx).extend(out, None, None, None))
modifiedcrates/jrsonnet-evaluator/src/integrations/serde.rsdiffbeforeafterboth
--- a/crates/jrsonnet-evaluator/src/integrations/serde.rs
+++ b/crates/jrsonnet-evaluator/src/integrations/serde.rs
@@ -1,7 +1,8 @@
 use crate::{
 	error::{Error::*, LocError, Result},
-	throw, Context, LazyBinding, LazyVal, ObjMember, ObjValue, Val,
+	throw, LazyBinding, LazyVal, ObjMember, ObjValue, Val,
 };
+use jrsonnet_gc::Gc;
 use jrsonnet_parser::Visibility;
 use rustc_hash::FxHasher;
 use serde_json::{Map, Number, Value};
@@ -9,7 +10,6 @@
 	collections::HashMap,
 	convert::{TryFrom, TryInto},
 	hash::BuildHasherDefault,
-	rc::Rc,
 };
 
 impl TryFrom<&Val> for Value {
@@ -42,6 +42,7 @@
 				Self::Object(out)
 			}
 			Val::Func(_) => throw!(RuntimeError("tried to manifest function".into())),
+			Val::DebugGcTraceValue(v) => Self::try_from(&*v.value as &Val)?,
 		})
 	}
 }
@@ -76,12 +77,7 @@
 						},
 					);
 				}
-				Self::Obj(ObjValue::new(
-					Context::new(),
-					None,
-					Rc::new(entries),
-					Rc::new(Vec::new()),
-				))
+				Self::Obj(ObjValue::new(None, Gc::new(entries), Gc::new(Vec::new())))
 			}
 		}
 	}
modifiedcrates/jrsonnet-evaluator/src/lib.rsdiffbeforeafterboth
--- a/crates/jrsonnet-evaluator/src/lib.rs
+++ b/crates/jrsonnet-evaluator/src/lib.rs
@@ -26,6 +26,8 @@
 pub use evaluate::*;
 pub use function::parse_function_call;
 pub use import::*;
+use jrsonnet_gc::{Finalize, Gc, Trace};
+pub use jrsonnet_interner::IStr;
 use jrsonnet_parser::*;
 use native::NativeCallback;
 pub use obj::*;
@@ -41,13 +43,12 @@
 use trace::{offset_to_location, CodeLocation, CompactFormat, TraceFormat};
 pub use val::*;
 
-// Re-exports
-pub use jrsonnet_interner::IStr;
-
-type BindableFn = dyn Fn(Option<ObjValue>, Option<ObjValue>) -> Result<LazyVal>;
-#[derive(Clone)]
+pub trait Bindable: Trace {
+	fn bind(&self, this: Option<ObjValue>, super_obj: Option<ObjValue>) -> Result<LazyVal>;
+}
+#[derive(Trace, Finalize, Clone)]
 pub enum LazyBinding {
-	Bindable(Rc<BindableFn>),
+	Bindable(Gc<Box<dyn Bindable>>),
 	Bound(LazyVal),
 }
 
@@ -59,7 +60,7 @@
 impl LazyBinding {
 	pub fn evaluate(&self, this: Option<ObjValue>, super_obj: Option<ObjValue>) -> Result<LazyVal> {
 		match self {
-			Self::Bindable(v) => v(this, super_obj),
+			Self::Bindable(v) => v.bind(this, super_obj),
 			Self::Bound(v) => Ok(v.clone()),
 		}
 	}
@@ -73,7 +74,7 @@
 	/// Used for s`td.extVar`
 	pub ext_vars: HashMap<IStr, Val>,
 	/// Used for ext.native
-	pub ext_natives: HashMap<IStr, Rc<NativeCallback>>,
+	pub ext_natives: HashMap<IStr, Gc<NativeCallback>>,
 	/// TLA vars
 	pub tla_vars: HashMap<IStr, Val>,
 	/// Global variables are inserted in default context
@@ -272,7 +273,7 @@
 		let mut new_bindings: FxHashMap<IStr, LazyVal> =
 			FxHashMap::with_capacity_and_hasher(globals.len(), BuildHasherDefault::default());
 		for (name, value) in globals.iter() {
-			new_bindings.insert(name.clone(), resolved_lazy_val!(value.clone()));
+			new_bindings.insert(name.clone(), LazyVal::new_resolved(value.clone()));
 		}
 		Context::new().extend_bound(new_bindings)
 	}
@@ -451,7 +452,7 @@
 		self.settings_mut().import_resolver = resolver;
 	}
 
-	pub fn add_native(&self, name: IStr, cb: Rc<NativeCallback>) {
+	pub fn add_native(&self, name: IStr, cb: Gc<NativeCallback>) {
 		self.settings_mut().ext_natives.insert(name, cb);
 	}
 
@@ -487,7 +488,10 @@
 #[cfg(test)]
 pub mod tests {
 	use super::Val;
-	use crate::{error::Error::*, primitive_equals, EvaluationState};
+	use crate::{
+		error::Error::*, native::NativeCallbackHandler, primitive_equals, EvaluationState,
+	};
+	use jrsonnet_gc::{Finalize, Gc, Trace};
 	use jrsonnet_interner::IStr;
 	use jrsonnet_parser::*;
 	use std::{
@@ -919,23 +923,29 @@
 		let evaluator = EvaluationState::default();
 
 		evaluator.with_stdlib();
+
+		#[derive(Trace, Finalize)]
+		struct NativeAdd;
+		impl NativeCallbackHandler for NativeAdd {
+			fn call(&self, from: Option<Rc<Path>>, args: &[Val]) -> crate::error::Result<Val> {
+				assert_eq!(
+					&from.unwrap() as &Path,
+					&PathBuf::from("native_caller.jsonnet")
+				);
+				match (&args[0], &args[1]) {
+					(Val::Num(a), Val::Num(b)) => Ok(Val::Num(a + b)),
+					(_, _) => unreachable!(),
+				}
+			}
+		}
 		evaluator.settings_mut().ext_natives.insert(
 			"native_add".into(),
-			Rc::new(NativeCallback::new(
+			Gc::new(NativeCallback::new(
 				ParamsDesc(Rc::new(vec![
 					Param("a".into(), None),
 					Param("b".into(), None),
 				])),
-				|caller, args| {
-					assert_eq!(
-						&caller.unwrap() as &Path,
-						&PathBuf::from("native_caller.jsonnet")
-					);
-					match (&args[0], &args[1]) {
-						(Val::Num(a), Val::Num(b)) => Ok(Val::Num(a + b)),
-						(_, _) => unreachable!(),
-					}
-				},
+				Box::new(NativeAdd),
 			)),
 		);
 		evaluator.evaluate_snippet_raw(
modifiedcrates/jrsonnet-evaluator/src/map.rsdiffbeforeafterboth
--- a/crates/jrsonnet-evaluator/src/map.rs
+++ b/crates/jrsonnet-evaluator/src/map.rs
@@ -1,31 +1,29 @@
+use jrsonnet_gc::{Gc, Trace};
 use jrsonnet_interner::IStr;
 use rustc_hash::FxHashMap;
-use std::rc::Rc;
 
-#[derive(Default, Debug)]
-struct LayeredHashMapInternals<V> {
-	parent: Option<LayeredHashMap<V>>,
-	current: FxHashMap<IStr, V>,
+use crate::LazyVal;
+
+#[derive(Trace)]
+#[trivially_drop]
+pub struct LayeredHashMapInternals {
+	parent: Option<LayeredHashMap>,
+	current: FxHashMap<IStr, LazyVal>,
 }
 
-#[derive(Debug)]
-pub struct LayeredHashMap<V>(Rc<LayeredHashMapInternals<V>>);
+#[derive(Trace)]
+#[trivially_drop]
+pub struct LayeredHashMap(Gc<LayeredHashMapInternals>);
 
-impl<V> LayeredHashMap<V> {
-	pub fn extend(self, new_layer: FxHashMap<IStr, V>) -> Self {
-		match Rc::try_unwrap(self.0) {
-			Ok(mut map) => {
-				map.current.extend(new_layer);
-				Self(Rc::new(map))
-			}
-			Err(this) => Self(Rc::new(LayeredHashMapInternals {
-				parent: Some(Self(this)),
-				current: new_layer,
-			})),
-		}
+impl LayeredHashMap {
+	pub fn extend(self, new_layer: FxHashMap<IStr, LazyVal>) -> Self {
+		Self(Gc::new(LayeredHashMapInternals {
+			parent: Some(self),
+			current: new_layer,
+		}))
 	}
 
-	pub fn get(&self, key: &IStr) -> Option<&V> {
+	pub fn get(&self, key: &IStr) -> Option<&LazyVal> {
 		(self.0)
 			.current
 			.get(key)
@@ -33,15 +31,15 @@
 	}
 }
 
-impl<V> Clone for LayeredHashMap<V> {
+impl Clone for LayeredHashMap {
 	fn clone(&self) -> Self {
 		Self(self.0.clone())
 	}
 }
 
-impl<V> Default for LayeredHashMap<V> {
+impl Default for LayeredHashMap {
 	fn default() -> Self {
-		Self(Rc::new(LayeredHashMapInternals {
+		Self(Gc::new(LayeredHashMapInternals {
 			parent: None,
 			current: FxHashMap::default(),
 		}))
modifiedcrates/jrsonnet-evaluator/src/native.rsdiffbeforeafterboth
--- a/crates/jrsonnet-evaluator/src/native.rs
+++ b/crates/jrsonnet-evaluator/src/native.rs
@@ -1,27 +1,28 @@
 #![allow(clippy::type_complexity)]
 
 use crate::{error::Result, Val};
+use jrsonnet_gc::Trace;
 use jrsonnet_parser::ParamsDesc;
 use std::fmt::Debug;
 use std::path::Path;
 use std::rc::Rc;
 
+pub trait NativeCallbackHandler: Trace {
+	fn call(&self, from: Option<Rc<Path>>, args: &[Val]) -> Result<Val>;
+}
+
+#[derive(Trace)]
+#[trivially_drop]
 pub struct NativeCallback {
 	pub params: ParamsDesc,
-	handler: Box<dyn Fn(Option<Rc<Path>>, &[Val]) -> Result<Val>>,
+	handler: Box<dyn NativeCallbackHandler>,
 }
 impl NativeCallback {
-	pub fn new(
-		params: ParamsDesc,
-		handler: impl Fn(Option<Rc<Path>>, &[Val]) -> Result<Val> + 'static,
-	) -> Self {
-		Self {
-			params,
-			handler: Box::new(handler),
-		}
+	pub fn new(params: ParamsDesc, handler: Box<dyn NativeCallbackHandler>) -> Self {
+		Self { params, handler }
 	}
 	pub fn call(&self, caller: Option<Rc<Path>>, args: &[Val]) -> Result<Val> {
-		(self.handler)(caller, args)
+		self.handler.call(caller, args)
 	}
 }
 impl Debug for NativeCallback {
modifiedcrates/jrsonnet-evaluator/src/obj.rsdiffbeforeafterboth
--- a/crates/jrsonnet-evaluator/src/obj.rs
+++ b/crates/jrsonnet-evaluator/src/obj.rs
@@ -1,11 +1,13 @@
-use crate::{evaluate_add_op, evaluate_assert, Context, LazyBinding, Result, Val};
+use crate::{evaluate_add_op, LazyBinding, Result, Val};
+use jrsonnet_gc::{Gc, GcCell, Trace};
 use jrsonnet_interner::IStr;
-use jrsonnet_parser::{AssertStmt, ExprLocation, Visibility};
+use jrsonnet_parser::{ExprLocation, Visibility};
 use rustc_hash::{FxHashMap, FxHashSet};
 use std::hash::{Hash, Hasher};
-use std::{cell::RefCell, fmt::Debug, hash::BuildHasherDefault, rc::Rc};
+use std::{fmt::Debug, hash::BuildHasherDefault};
 
-#[derive(Debug)]
+#[derive(Debug, Trace)]
+#[trivially_drop]
 pub struct ObjMember {
 	pub add: bool,
 	pub visibility: Visibility,
@@ -13,21 +15,26 @@
 	pub location: Option<ExprLocation>,
 }
 
+pub trait ObjectAssertion: Trace {
+	fn run(&self, this: Option<ObjValue>, super_obj: Option<ObjValue>) -> Result<()>;
+}
+
 // Field => This
 type CacheKey = (IStr, ObjValue);
-#[derive(Debug)]
+#[derive(Trace)]
+#[trivially_drop]
 pub struct ObjValueInternals {
-	context: Context,
 	super_obj: Option<ObjValue>,
-	assertions: Rc<Vec<AssertStmt>>,
-	assertions_ran: RefCell<FxHashSet<ObjValue>>,
+	assertions: Gc<Vec<Box<dyn ObjectAssertion>>>,
+	assertions_ran: GcCell<FxHashSet<ObjValue>>,
 	this_obj: Option<ObjValue>,
-	this_entries: Rc<FxHashMap<IStr, ObjMember>>,
-	value_cache: RefCell<FxHashMap<CacheKey, Option<Val>>>,
+	this_entries: Gc<FxHashMap<IStr, ObjMember>>,
+	value_cache: GcCell<FxHashMap<CacheKey, Option<Val>>>,
 }
 
-#[derive(Clone)]
-pub struct ObjValue(pub(crate) Rc<ObjValueInternals>);
+#[derive(Clone, Trace)]
+#[trivially_drop]
+pub struct ObjValue(pub(crate) Gc<ObjValueInternals>);
 impl Debug for ObjValue {
 	fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
 		if let Some(super_obj) = self.0.super_obj.as_ref() {
@@ -55,39 +62,30 @@
 
 impl ObjValue {
 	pub fn new(
-		context: Context,
 		super_obj: Option<Self>,
-		this_entries: Rc<FxHashMap<IStr, ObjMember>>,
-		assertions: Rc<Vec<AssertStmt>>,
+		this_entries: Gc<FxHashMap<IStr, ObjMember>>,
+		assertions: Gc<Vec<Box<dyn ObjectAssertion>>>,
 	) -> Self {
-		Self(Rc::new(ObjValueInternals {
-			context,
+		Self(Gc::new(ObjValueInternals {
 			super_obj,
 			assertions,
-			assertions_ran: RefCell::new(FxHashSet::default()),
+			assertions_ran: GcCell::new(FxHashSet::default()),
 			this_obj: None,
 			this_entries,
-			value_cache: RefCell::new(FxHashMap::default()),
+			value_cache: GcCell::new(FxHashMap::default()),
 		}))
 	}
 	pub fn new_empty() -> Self {
-		Self::new(
-			Context::new(),
-			None,
-			Rc::new(FxHashMap::default()),
-			Rc::new(Vec::new()),
-		)
+		Self::new(None, Gc::new(FxHashMap::default()), Gc::new(Vec::new()))
 	}
 	pub fn extend_from(&self, super_obj: Self) -> Self {
 		match &self.0.super_obj {
 			None => Self::new(
-				self.0.context.clone(),
 				Some(super_obj),
 				self.0.this_entries.clone(),
 				self.0.assertions.clone(),
 			),
 			Some(v) => Self::new(
-				self.0.context.clone(),
 				Some(v.extend_from(super_obj)),
 				self.0.this_entries.clone(),
 				self.0.assertions.clone(),
@@ -95,14 +93,13 @@
 		}
 	}
 	pub fn with_this(&self, this_obj: Self) -> Self {
-		Self(Rc::new(ObjValueInternals {
-			context: self.0.context.clone(),
+		Self(Gc::new(ObjValueInternals {
 			super_obj: self.0.super_obj.clone(),
 			assertions: self.0.assertions.clone(),
-			assertions_ran: RefCell::new(FxHashSet::default()),
+			assertions_ran: GcCell::new(FxHashSet::default()),
 			this_obj: Some(this_obj),
 			this_entries: self.0.this_entries.clone(),
-			value_cache: RefCell::new(FxHashMap::default()),
+			value_cache: GcCell::new(FxHashMap::default()),
 		}))
 	}
 
@@ -203,12 +200,7 @@
 	pub fn extend_with_field(self, key: IStr, value: ObjMember) -> Self {
 		let mut new = FxHashMap::with_capacity_and_hasher(1, BuildHasherDefault::default());
 		new.insert(key, value);
-		Self::new(
-			Context::new(),
-			Some(self),
-			Rc::new(new),
-			Rc::new(Vec::new()),
-		)
+		Self::new(Some(self), Gc::new(new), Gc::new(Vec::new()))
 	}
 
 	fn get_raw(&self, key: IStr, real_this: Option<&Self>) -> Result<Option<Val>> {
@@ -249,13 +241,7 @@
 	fn run_assertions_raw(&self, real_this: &Self) -> Result<()> {
 		if self.0.assertions_ran.borrow_mut().insert(real_this.clone()) {
 			for assertion in self.0.assertions.iter() {
-				if let Err(e) = evaluate_assert(
-					self.0
-						.context
-						.clone()
-						.with_this_super(real_this.clone(), self.0.super_obj.clone()),
-					assertion,
-				) {
+				if let Err(e) = assertion.run(Some(real_this.clone()), self.0.super_obj.clone()) {
 					self.0.assertions_ran.borrow_mut().remove(real_this);
 					return Err(e);
 				}
@@ -271,19 +257,19 @@
 	}
 
 	pub fn ptr_eq(a: &Self, b: &Self) -> bool {
-		Rc::ptr_eq(&a.0, &b.0)
+		Gc::ptr_eq(&a.0, &b.0)
 	}
 }
 
 impl PartialEq for ObjValue {
 	fn eq(&self, other: &Self) -> bool {
-		Rc::ptr_eq(&self.0, &other.0)
+		Gc::ptr_eq(&self.0, &other.0)
 	}
 }
 
 impl Eq for ObjValue {}
 impl Hash for ObjValue {
-	fn hash<H: Hasher>(&self, state: &mut H) {
-		state.write_usize(Rc::as_ptr(&self.0) as usize)
+	fn hash<H: Hasher>(&self, hasher: &mut H) {
+		hasher.write_usize(&*self.0 as *const _ as usize)
 	}
 }
modifiedcrates/jrsonnet-evaluator/src/typed.rsdiffbeforeafterboth
--- a/crates/jrsonnet-evaluator/src/typed.rs
+++ b/crates/jrsonnet-evaluator/src/typed.rs
@@ -4,6 +4,7 @@
 	error::{Error, LocError, Result},
 	push, Val,
 };
+use jrsonnet_gc::Trace;
 use jrsonnet_parser::ExprLocation;
 use jrsonnet_types::{ComplexValType, ValType};
 use thiserror::Error;
@@ -20,7 +21,8 @@
 	}};
 }
 
-#[derive(Debug, Error, Clone)]
+#[derive(Debug, Error, Clone, Trace)]
+#[trivially_drop]
 pub enum TypeError {
 	#[error("expected {0}, got {1}")]
 	ExpectedGot(ComplexValType, ValType),
@@ -37,7 +39,8 @@
 	}
 }
 
-#[derive(Debug, Clone)]
+#[derive(Debug, Clone, Trace)]
+#[trivially_drop]
 pub struct TypeLocError(Box<TypeError>, ValuePathStack);
 impl From<TypeError> for TypeLocError {
 	fn from(e: TypeError) -> Self {
@@ -59,7 +62,8 @@
 	}
 }
 
-#[derive(Debug, Clone)]
+#[derive(Debug, Clone, Trace)]
+#[trivially_drop]
 pub struct TypeLocErrorList(Vec<TypeLocError>);
 impl Display for TypeLocErrorList {
 	fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
@@ -122,7 +126,8 @@
 	}
 }
 
-#[derive(Clone, Debug)]
+#[derive(Clone, Debug, Trace)]
+#[trivially_drop]
 enum ValuePathItem {
 	Field(Rc<str>),
 	Index(u64),
@@ -137,7 +142,8 @@
 	}
 }
 
-#[derive(Clone, Debug)]
+#[derive(Clone, Debug, Trace)]
+#[trivially_drop]
 struct ValuePathStack(Vec<ValuePathItem>);
 impl Display for ValuePathStack {
 	fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
modifiedcrates/jrsonnet-evaluator/src/val.rsdiffbeforeafterboth
--- a/crates/jrsonnet-evaluator/src/val.rs
+++ b/crates/jrsonnet-evaluator/src/val.rs
@@ -3,52 +3,67 @@
 		call_builtin,
 		manifest::{manifest_json_ex, ManifestJsonOptions, ManifestType},
 	},
-	error::Error::*,
+	error::{Error::*, LocError},
 	evaluate,
 	function::{parse_function_call, parse_function_call_map, place_args},
 	native::NativeCallback,
 	throw, with_state, Context, ObjValue, Result,
 };
+use jrsonnet_gc::{Finalize, Gc, GcCell, Trace};
 use jrsonnet_interner::IStr;
 use jrsonnet_parser::{el, Arg, ArgsDesc, Expr, ExprLocation, LiteralType, LocExpr, ParamsDesc};
 use jrsonnet_types::ValType;
-use std::{cell::RefCell, collections::HashMap, fmt::Debug, rc::Rc};
+use std::{collections::HashMap, fmt::Debug, rc::Rc};
 
+pub trait LazyValValue: Trace {
+	fn get(self: Box<Self>) -> Result<Val>;
+}
+
+#[derive(Trace)]
+#[trivially_drop]
 enum LazyValInternals {
 	Computed(Val),
-	Waiting(Box<dyn Fn() -> Result<Val>>),
+	Errored(LocError),
+	Waiting(Box<dyn LazyValValue>),
+	Pending,
 }
-#[derive(Clone)]
-pub struct LazyVal(Rc<RefCell<LazyValInternals>>);
+
+#[derive(Clone, Trace)]
+#[trivially_drop]
+pub struct LazyVal(Gc<GcCell<LazyValInternals>>);
 impl LazyVal {
-	pub fn new(f: Box<dyn Fn() -> Result<Val>>) -> Self {
-		Self(Rc::new(RefCell::new(LazyValInternals::Waiting(f))))
+	pub fn new(f: Box<dyn LazyValValue>) -> Self {
+		Self(Gc::new(GcCell::new(LazyValInternals::Waiting(f))))
 	}
 	pub fn new_resolved(val: Val) -> Self {
-		Self(Rc::new(RefCell::new(LazyValInternals::Computed(val))))
+		Self(Gc::new(GcCell::new(LazyValInternals::Computed(val))))
 	}
 	pub fn evaluate(&self) -> Result<Val> {
-		let new_value = match &*self.0.borrow() {
+		match &*self.0.borrow() {
 			LazyValInternals::Computed(v) => return Ok(v.clone()),
-			LazyValInternals::Waiting(f) => f()?,
+			LazyValInternals::Errored(e) => return Err(e.clone()),
+			LazyValInternals::Pending => return Err(RecursiveLazyValueEvaluation.into()),
+			_ => (),
+		};
+		let value = if let LazyValInternals::Waiting(value) =
+			std::mem::replace(&mut *self.0.borrow_mut(), LazyValInternals::Pending)
+		{
+			value
+		} else {
+			unreachable!()
+		};
+		let new_value = match value.get() {
+			Ok(v) => v,
+			Err(e) => {
+				*self.0.borrow_mut() = LazyValInternals::Errored(e.clone());
+				return Err(e);
+			}
 		};
 		*self.0.borrow_mut() = LazyValInternals::Computed(new_value.clone());
 		Ok(new_value)
 	}
 }
 
-#[macro_export]
-macro_rules! lazy_val {
-	($f: expr) => {
-		$crate::LazyVal::new(Box::new($f))
-	};
-}
-#[macro_export]
-macro_rules! resolved_lazy_val {
-	($f: expr) => {
-		$crate::LazyVal::new_resolved($f)
-	};
-}
 impl Debug for LazyVal {
 	fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
 		write!(f, "Lazy")
@@ -56,11 +71,12 @@
 }
 impl PartialEq for LazyVal {
 	fn eq(&self, other: &Self) -> bool {
-		Rc::ptr_eq(&self.0, &other.0)
+		Gc::ptr_eq(&self.0, &other.0)
 	}
 }
 
-#[derive(Debug, PartialEq)]
+#[derive(Debug, PartialEq, Trace)]
+#[trivially_drop]
 pub struct FuncDesc {
 	pub name: IStr,
 	pub ctx: Context,
@@ -68,14 +84,15 @@
 	pub body: LocExpr,
 }
 
-#[derive(Debug)]
+#[derive(Debug, Trace)]
+#[trivially_drop]
 pub enum FuncVal {
 	/// Plain function implemented in jsonnet
 	Normal(FuncDesc),
 	/// Standard library function
 	Intrinsic(IStr),
 	/// Library functions implemented in native
-	NativeExt(IStr, Rc<NativeCallback>),
+	NativeExt(IStr, Gc<NativeCallback>),
 }
 
 impl PartialEq for FuncVal {
@@ -172,15 +189,16 @@
 	String,
 }
 
-#[derive(Debug, Clone)]
+#[derive(Debug, Clone, Trace)]
+#[trivially_drop]
 pub enum ArrValue {
-	Lazy(Rc<Vec<LazyVal>>),
-	Eager(Rc<Vec<Val>>),
+	Lazy(Gc<Vec<LazyVal>>),
+	Eager(Gc<Vec<Val>>),
 	Extended(Box<(Self, Self)>),
 }
 impl ArrValue {
 	pub fn new_eager() -> Self {
-		Self::Eager(Rc::new(Vec::new()))
+		Self::Eager(Gc::new(Vec::new()))
 	}
 
 	pub fn len(&self) -> usize {
@@ -231,14 +249,14 @@
 		}
 	}
 
-	pub fn evaluated(&self) -> Result<Rc<Vec<Val>>> {
+	pub fn evaluated(&self) -> Result<Gc<Vec<Val>>> {
 		Ok(match self {
 			Self::Lazy(vec) => {
 				let mut out = Vec::with_capacity(vec.len());
 				for item in vec.iter() {
 					out.push(item.evaluate()?);
 				}
-				Rc::new(out)
+				Gc::new(out)
 			}
 			Self::Eager(vec) => vec.clone(),
 			Self::Extended(_v) => {
@@ -246,7 +264,7 @@
 				for item in self.iter() {
 					out.push(item?);
 				}
-				Rc::new(out)
+				Gc::new(out)
 			}
 		})
 	}
@@ -272,12 +290,12 @@
 			Self::Lazy(vec) => {
 				let mut out = (&vec as &Vec<_>).clone();
 				out.reverse();
-				Self::Lazy(Rc::new(out))
+				Self::Lazy(Gc::new(out))
 			}
 			Self::Eager(vec) => {
 				let mut out = (&vec as &Vec<_>).clone();
 				out.reverse();
-				Self::Eager(Rc::new(out))
+				Self::Eager(Gc::new(out))
 			}
 			Self::Extended(b) => Self::Extended(Box::new((b.1.reversed(), b.0.reversed()))),
 		}
@@ -290,7 +308,7 @@
 			out.push(mapper(value?)?);
 		}
 
-		Ok(Self::Eager(Rc::new(out)))
+		Ok(Self::Eager(Gc::new(out)))
 	}
 
 	pub fn filter(self, filter: impl Fn(&Val) -> Result<bool>) -> Result<Self> {
@@ -303,13 +321,13 @@
 			}
 		}
 
-		Ok(Self::Eager(Rc::new(out)))
+		Ok(Self::Eager(Gc::new(out)))
 	}
 
 	pub fn ptr_eq(a: &Self, b: &Self) -> bool {
 		match (a, b) {
-			(Self::Lazy(a), Self::Lazy(b)) => Rc::ptr_eq(a, b),
-			(Self::Eager(a), Self::Eager(b)) => Rc::ptr_eq(a, b),
+			(Self::Lazy(a), Self::Lazy(b)) => Gc::ptr_eq(a, b),
+			(Self::Eager(a), Self::Eager(b)) => Gc::ptr_eq(a, b),
 			_ => false,
 		}
 	}
@@ -317,17 +335,77 @@
 
 impl From<Vec<LazyVal>> for ArrValue {
 	fn from(v: Vec<LazyVal>) -> Self {
-		Self::Lazy(Rc::new(v))
+		Self::Lazy(Gc::new(v))
 	}
 }
 
 impl From<Vec<Val>> for ArrValue {
 	fn from(v: Vec<Val>) -> Self {
-		Self::Eager(Rc::new(v))
+		Self::Eager(Gc::new(v))
+	}
+}
+
+#[derive(Debug)]
+pub struct DebugGcTraceValue {
+	name: IStr,
+	pub value: Box<Val>,
+}
+impl DebugGcTraceValue {
+	fn print(&self, action: &str) {
+		println!("{} {}#{:?}", action, self.name, &*self.value as *const _)
+	}
+}
+impl Finalize for DebugGcTraceValue {
+	fn finalize(&self) {
+		self.print("Garbage-collecting")
+	}
+}
+impl Drop for DebugGcTraceValue {
+	fn drop(&mut self) {
+		self.print("Garbage-collected")
+	}
+}
+unsafe impl Trace for DebugGcTraceValue {
+	unsafe fn trace(&self) {
+		self.print("Traced");
+		self.value.trace()
+	}
+	unsafe fn root(&self) {
+		self.print("Rooted");
+		self.value.root()
+	}
+	unsafe fn unroot(&self) {
+		self.print("Unrooted");
+		self.value.unroot()
+	}
+	fn finalize_glue(&self) {
+		Finalize::finalize(self)
+	}
+}
+impl Clone for DebugGcTraceValue {
+	fn clone(&self) -> Self {
+		self.print("Cloned");
+		let value = Self {
+			name: self.name.clone(),
+			value: self.value.clone(),
+		};
+		value.print("I'm clone");
+		value
 	}
 }
+impl DebugGcTraceValue {
+	pub fn create(name: IStr, value: Val) -> Val {
+		let value = Self {
+			name,
+			value: Box::new(value),
+		};
+		value.print("Constructed");
+		Val::DebugGcTraceValue(value)
+	}
+}
 
-#[derive(Debug, Clone)]
+#[derive(Debug, Clone, Trace)]
+#[trivially_drop]
 pub enum Val {
 	Bool(bool),
 	Null,
@@ -335,7 +413,8 @@
 	Num(f64),
 	Arr(ArrValue),
 	Obj(ObjValue),
-	Func(Rc<FuncVal>),
+	Func(Gc<FuncVal>),
+	DebugGcTraceValue(DebugGcTraceValue),
 }
 
 macro_rules! matches_unwrap {
@@ -368,7 +447,7 @@
 	pub fn unwrap_num(self) -> Result<f64> {
 		Ok(matches_unwrap!(self, Self::Num(v), v))
 	}
-	pub fn unwrap_func(self) -> Result<Rc<FuncVal>> {
+	pub fn unwrap_func(self) -> Result<Gc<FuncVal>> {
 		Ok(matches_unwrap!(self, Self::Func(v), v))
 	}
 	pub fn try_cast_bool(self, context: &'static str) -> Result<bool> {
@@ -392,6 +471,7 @@
 			Self::Bool(_) => ValType::Bool,
 			Self::Null => ValType::Null,
 			Self::Func(..) => ValType::Func,
+			Self::DebugGcTraceValue(v) => v.value.value_type(),
 		}
 	}
 
modifiedcrates/jrsonnet-interner/Cargo.tomldiffbeforeafterboth
--- a/crates/jrsonnet-interner/Cargo.toml
+++ b/crates/jrsonnet-interner/Cargo.toml
@@ -9,3 +9,4 @@
 [dependencies]
 serde = { version = "1.0" }
 rustc-hash = "1.1.0"
+jrsonnet-gc = { version = "0.4.2", features = ["derive"] }
modifiedcrates/jrsonnet-interner/src/lib.rsdiffbeforeafterboth
--- a/crates/jrsonnet-interner/src/lib.rs
+++ b/crates/jrsonnet-interner/src/lib.rs
@@ -1,3 +1,4 @@
+use jrsonnet_gc::{unsafe_empty_trace, Finalize, Trace};
 use rustc_hash::FxHashMap;
 use serde::{Deserialize, Serialize};
 use std::{
@@ -10,6 +11,10 @@
 
 #[derive(Clone, PartialOrd, Ord, Eq)]
 pub struct IStr(Rc<str>);
+impl Finalize for IStr {}
+unsafe impl Trace for IStr {
+	unsafe_empty_trace!();
+}
 
 impl Deref for IStr {
 	type Target = str;
modifiedcrates/jrsonnet-parser/Cargo.tomldiffbeforeafterboth
--- a/crates/jrsonnet-parser/Cargo.toml
+++ b/crates/jrsonnet-parser/Cargo.toml
@@ -18,6 +18,7 @@
 unescape = "0.1.0"
 
 serde = { version = "1.0", features = ["derive", "rc"], optional = true }
+jrsonnet-gc = { version = "0.4.2", features = ["derive"] }
 
 [dev-dependencies]
 jrsonnet-stdlib = { path = "../jrsonnet-stdlib", version = "0.3.8" }
modifiedcrates/jrsonnet-parser/src/expr.rsdiffbeforeafterboth
--- a/crates/jrsonnet-parser/src/expr.rs
+++ b/crates/jrsonnet-parser/src/expr.rs
@@ -1,3 +1,4 @@
+use jrsonnet_gc::{unsafe_empty_trace, Finalize, Trace};
 use jrsonnet_interner::IStr;
 #[cfg(feature = "deserialize")]
 use serde::Deserialize;
@@ -12,7 +13,8 @@
 
 #[cfg_attr(feature = "serialize", derive(Serialize))]
 #[cfg_attr(feature = "deserialize", derive(Deserialize))]
-#[derive(Debug, PartialEq)]
+#[derive(Debug, PartialEq, Trace)]
+#[trivially_drop]
 pub enum FieldName {
 	/// {fixed: 2}
 	Fixed(IStr),
@@ -22,7 +24,8 @@
 
 #[cfg_attr(feature = "serialize", derive(Serialize))]
 #[cfg_attr(feature = "deserialize", derive(Deserialize))]
-#[derive(Debug, Clone, Copy, PartialEq)]
+#[derive(Debug, Clone, Copy, PartialEq, Trace)]
+#[trivially_drop]
 pub enum Visibility {
 	/// :
 	Normal,
@@ -40,12 +43,14 @@
 
 #[cfg_attr(feature = "serialize", derive(Serialize))]
 #[cfg_attr(feature = "deserialize", derive(Deserialize))]
-#[derive(Clone, Debug, PartialEq)]
+#[derive(Clone, Debug, PartialEq, Trace)]
+#[trivially_drop]
 pub struct AssertStmt(pub LocExpr, pub Option<LocExpr>);
 
 #[cfg_attr(feature = "serialize", derive(Serialize))]
 #[cfg_attr(feature = "deserialize", derive(Deserialize))]
-#[derive(Debug, PartialEq)]
+#[derive(Debug, PartialEq, Trace)]
+#[trivially_drop]
 pub struct FieldMember {
 	pub name: FieldName,
 	pub plus: bool,
@@ -56,7 +61,8 @@
 
 #[cfg_attr(feature = "serialize", derive(Serialize))]
 #[cfg_attr(feature = "deserialize", derive(Deserialize))]
-#[derive(Debug, PartialEq)]
+#[derive(Debug, PartialEq, Trace)]
+#[trivially_drop]
 pub enum Member {
 	Field(FieldMember),
 	BindStmt(BindSpec),
@@ -65,13 +71,15 @@
 
 #[cfg_attr(feature = "serialize", derive(Serialize))]
 #[cfg_attr(feature = "deserialize", derive(Deserialize))]
-#[derive(Debug, Clone, Copy, PartialEq)]
+#[derive(Debug, Clone, Copy, PartialEq, Trace)]
+#[trivially_drop]
 pub enum UnaryOpType {
 	Plus,
 	Minus,
 	BitNot,
 	Not,
 }
+
 impl Display for UnaryOpType {
 	fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
 		use UnaryOpType::*;
@@ -90,7 +98,8 @@
 
 #[cfg_attr(feature = "serialize", derive(Serialize))]
 #[cfg_attr(feature = "deserialize", derive(Deserialize))]
-#[derive(Debug, Clone, Copy, PartialEq)]
+#[derive(Debug, Clone, Copy, PartialEq, Trace)]
+#[trivially_drop]
 pub enum BinaryOpType {
 	Mul,
 	Div,
@@ -119,6 +128,7 @@
 	And,
 	Or,
 }
+
 impl Display for BinaryOpType {
 	fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
 		use BinaryOpType::*;
@@ -152,7 +162,8 @@
 /// name, default value
 #[cfg_attr(feature = "serialize", derive(Serialize))]
 #[cfg_attr(feature = "deserialize", derive(Deserialize))]
-#[derive(Debug, PartialEq)]
+#[derive(Debug, PartialEq, Trace)]
+#[trivially_drop]
 pub struct Param(pub IStr, pub Option<LocExpr>);
 
 /// Defined function parameters
@@ -160,6 +171,14 @@
 #[cfg_attr(feature = "deserialize", derive(Deserialize))]
 #[derive(Debug, Clone, PartialEq)]
 pub struct ParamsDesc(pub Rc<Vec<Param>>);
+
+/// Safety:
+/// AST is acyclic, and there should be no gc pointers
+unsafe impl Trace for ParamsDesc {
+	unsafe_empty_trace!();
+}
+impl Finalize for ParamsDesc {}
+
 impl Deref for ParamsDesc {
 	type Target = Vec<Param>;
 	fn deref(&self) -> &Self::Target {
@@ -169,13 +188,16 @@
 
 #[cfg_attr(feature = "serialize", derive(Serialize))]
 #[cfg_attr(feature = "deserialize", derive(Deserialize))]
-#[derive(Debug, PartialEq)]
+#[derive(Debug, PartialEq, Trace)]
+#[trivially_drop]
 pub struct Arg(pub Option<String>, pub LocExpr);
 
 #[cfg_attr(feature = "serialize", derive(Serialize))]
 #[cfg_attr(feature = "deserialize", derive(Deserialize))]
-#[derive(Debug, PartialEq)]
+#[derive(Debug, PartialEq, Trace)]
+#[trivially_drop]
 pub struct ArgsDesc(pub Vec<Arg>);
+
 impl Deref for ArgsDesc {
 	type Target = Vec<Arg>;
 	fn deref(&self) -> &Self::Target {
@@ -185,7 +207,8 @@
 
 #[cfg_attr(feature = "serialize", derive(Serialize))]
 #[cfg_attr(feature = "deserialize", derive(Deserialize))]
-#[derive(Debug, Clone, PartialEq)]
+#[derive(Debug, Clone, PartialEq, Trace)]
+#[trivially_drop]
 pub struct BindSpec {
 	pub name: IStr,
 	pub params: Option<ParamsDesc>,
@@ -194,17 +217,20 @@
 
 #[cfg_attr(feature = "serialize", derive(Serialize))]
 #[cfg_attr(feature = "deserialize", derive(Deserialize))]
-#[derive(Debug, PartialEq)]
+#[derive(Debug, PartialEq, Trace)]
+#[trivially_drop]
 pub struct IfSpecData(pub LocExpr);
 
 #[cfg_attr(feature = "serialize", derive(Serialize))]
 #[cfg_attr(feature = "deserialize", derive(Deserialize))]
-#[derive(Debug, PartialEq)]
+#[derive(Debug, PartialEq, Trace)]
+#[trivially_drop]
 pub struct ForSpecData(pub IStr, pub LocExpr);
 
 #[cfg_attr(feature = "serialize", derive(Serialize))]
 #[cfg_attr(feature = "deserialize", derive(Deserialize))]
-#[derive(Debug, PartialEq)]
+#[derive(Debug, PartialEq, Trace)]
+#[trivially_drop]
 pub enum CompSpec {
 	IfSpec(IfSpecData),
 	ForSpec(ForSpecData),
@@ -212,7 +238,8 @@
 
 #[cfg_attr(feature = "serialize", derive(Serialize))]
 #[cfg_attr(feature = "deserialize", derive(Deserialize))]
-#[derive(Debug, PartialEq)]
+#[derive(Debug, PartialEq, Trace)]
+#[trivially_drop]
 pub struct ObjComp {
 	pub pre_locals: Vec<BindSpec>,
 	pub key: LocExpr,
@@ -223,7 +250,8 @@
 
 #[cfg_attr(feature = "serialize", derive(Serialize))]
 #[cfg_attr(feature = "deserialize", derive(Deserialize))]
-#[derive(Debug, PartialEq)]
+#[derive(Debug, PartialEq, Trace)]
+#[trivially_drop]
 pub enum ObjBody {
 	MemberList(Vec<Member>),
 	ObjComp(ObjComp),
@@ -231,7 +259,8 @@
 
 #[cfg_attr(feature = "serialize", derive(Serialize))]
 #[cfg_attr(feature = "deserialize", derive(Deserialize))]
-#[derive(Debug, PartialEq, Clone, Copy)]
+#[derive(Debug, PartialEq, Clone, Copy, Trace)]
+#[trivially_drop]
 pub enum LiteralType {
 	This,
 	Super,
@@ -241,7 +270,8 @@
 	False,
 }
 
-#[derive(Debug, PartialEq)]
+#[derive(Debug, PartialEq, Trace)]
+#[trivially_drop]
 pub struct SliceDesc {
 	pub start: Option<LocExpr>,
 	pub end: Option<LocExpr>,
@@ -251,7 +281,8 @@
 /// Syntax base
 #[cfg_attr(feature = "serialize", derive(Serialize))]
 #[cfg_attr(feature = "deserialize", derive(Deserialize))]
-#[derive(Debug, PartialEq)]
+#[derive(Debug, PartialEq, Trace)]
+#[trivially_drop]
 pub enum Expr {
 	Literal(LiteralType),
 
@@ -319,8 +350,10 @@
 /// file, begin offset, end offset
 #[cfg_attr(feature = "serialize", derive(Serialize))]
 #[cfg_attr(feature = "deserialize", derive(Deserialize))]
-#[derive(Clone, PartialEq)]
+#[derive(Clone, PartialEq, Trace)]
+#[trivially_drop]
 pub struct ExprLocation(pub Rc<Path>, pub usize, pub usize);
+
 impl Debug for ExprLocation {
 	fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
 		write!(f, "{:?}:{:?}-{:?}", self.0, self.1, self.2)
@@ -332,6 +365,13 @@
 #[cfg_attr(feature = "deserialize", derive(Deserialize))]
 #[derive(Clone, PartialEq)]
 pub struct LocExpr(pub Rc<Expr>, pub Option<ExprLocation>);
+/// Safety:
+/// AST is acyclic, and there should be no gc pointers
+unsafe impl Trace for LocExpr {
+	unsafe_empty_trace!();
+}
+impl Finalize for LocExpr {}
+
 impl Debug for LocExpr {
 	fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
 		if f.alternate() {
modifiedcrates/jrsonnet-types/Cargo.tomldiffbeforeafterboth
--- a/crates/jrsonnet-types/Cargo.toml
+++ b/crates/jrsonnet-types/Cargo.toml
@@ -8,3 +8,4 @@
 
 [dependencies]
 peg = "0.7.0"
+jrsonnet-gc = { version = "0.4.2", features = ["derive"] }
modifiedcrates/jrsonnet-types/src/lib.rsdiffbeforeafterboth
--- a/crates/jrsonnet-types/src/lib.rs
+++ b/crates/jrsonnet-types/src/lib.rs
@@ -1,5 +1,6 @@
 #![allow(clippy::redundant_closure_call)]
 
+use jrsonnet_gc::Trace;
 use std::fmt::Display;
 
 #[macro_export]
@@ -77,7 +78,8 @@
 	);
 }
 
-#[derive(Debug, Clone, Copy, PartialEq, Eq)]
+#[derive(Debug, Clone, Copy, PartialEq, Eq, Trace)]
+#[trivially_drop]
 pub enum ValType {
 	Bool,
 	Null,
@@ -109,7 +111,8 @@
 	}
 }
 
-#[derive(Debug, Clone, PartialEq)]
+#[derive(Debug, Clone, PartialEq, Trace)]
+#[trivially_drop]
 pub enum ComplexValType {
 	Any,
 	Char,
@@ -123,6 +126,7 @@
 	Sum(Vec<ComplexValType>),
 	SumRef(&'static [ComplexValType]),
 }
+
 impl From<ValType> for ComplexValType {
 	fn from(s: ValType) -> Self {
 		Self::Simple(s)
modifiedflake.lockdiffbeforeafterboth
--- a/flake.lock
+++ b/flake.lock
@@ -2,11 +2,11 @@
   "nodes": {
     "flake-utils": {
       "locked": {
-        "lastModified": 1614513358,
-        "narHash": "sha256-LakhOx3S1dRjnh0b5Dg3mbZyH0ToC9I8Y2wKSkBaTzU=",
+        "lastModified": 1623875721,
+        "narHash": "sha256-A8BU7bjS5GirpAUv4QA+QnJ4CceLHkcXdRp4xITDB0s=",
         "owner": "numtide",
         "repo": "flake-utils",
-        "rev": "5466c5bbece17adaab2d82fae80b46e807611bf3",
+        "rev": "f7e004a55b120c02ecb6219596820fcd32ca8772",
         "type": "github"
       },
       "original": {
@@ -17,11 +17,11 @@
     },
     "nixpkgs": {
       "locked": {
-        "lastModified": 1615532953,
-        "narHash": "sha256-SWpaGjrp/INzorEqMz3HLi6Uuk9I0KAn4YS8B4n3q5g=",
+        "lastModified": 1625281901,
+        "narHash": "sha256-DkZDtTIPzhXATqIps2ifNFpnI+PTcfMYdcrx/oFm00Q=",
         "owner": "NixOS",
         "repo": "nixpkgs",
-        "rev": "916ee862e87ac5ee2439f2fb7856386b4dc906ae",
+        "rev": "09c38c29f2c719cd76ca17a596c2fdac9e186ceb",
         "type": "github"
       },
       "original": {
modifiedflake.nixdiffbeforeafterboth
--- a/flake.nix
+++ b/flake.nix
@@ -12,7 +12,7 @@
           pname = "jrsonnet";
           version = "0.1.0";
           src = self;
-          cargoSha256 = "sha256-6VhaQi3L2LWzR0cq7oRG81MDbrKJbzSNPcvYSoQ5ISo=";
+          cargoSha256 = "sha256-cez8pJ/uwj+PHAPQwpSB4CKaxcP8Uvv8xguOrVXR2xE=";
         };
       in { 
         defaultPackage = jrsonnet;