git.delta.rocks / jrsonnet / refs/commits / 027693dbe6bd

difftreelog

refactor reduce boilerplate by automatic conversions

Yaroslav Bolyukin2023-08-13parent: #dad6c32.patch.diff
in: master

29 files changed

modifiedbindings/jsonnet/src/native.rsdiffbeforeafterboth
--- a/bindings/jsonnet/src/native.rs
+++ b/bindings/jsonnet/src/native.rs
@@ -69,10 +69,7 @@
 	ctx: *const c_void,
 	mut raw_params: *const *const c_char,
 ) {
-	let name = CStr::from_ptr(name)
-		.to_str()
-		.expect("name is not utf-8")
-		.into();
+	let name = CStr::from_ptr(name).to_str().expect("name is not utf-8");
 	let mut params = Vec::new();
 	loop {
 		if (*raw_params).is_null() {
modifiedbindings/jsonnet/src/val_make.rsdiffbeforeafterboth
--- a/bindings/jsonnet/src/val_make.rs
+++ b/bindings/jsonnet/src/val_make.rs
@@ -5,10 +5,7 @@
 	os::raw::{c_char, c_double, c_int},
 };
 
-use jrsonnet_evaluator::{
-	val::{ArrValue, StrValue},
-	ObjValue, Val,
-};
+use jrsonnet_evaluator::{val::ArrValue, ObjValue, Val};
 
 use crate::VM;
 
@@ -21,7 +18,7 @@
 pub unsafe extern "C" fn jsonnet_json_make_string(_vm: &VM, val: *const c_char) -> *mut Val {
 	let val = CStr::from_ptr(val);
 	let val = val.to_str().expect("string is not utf-8");
-	Box::into_raw(Box::new(Val::Str(StrValue::Flat(val.into()))))
+	Box::into_raw(Box::new(Val::string(val)))
 }
 
 /// Convert the given double to a `JsonnetJsonValue`.
modifiedbindings/jsonnet/src/val_modify.rsdiffbeforeafterboth
--- a/bindings/jsonnet/src/val_modify.rs
+++ b/bindings/jsonnet/src/val_modify.rs
@@ -5,7 +5,6 @@
 use std::{ffi::CStr, os::raw::c_char};
 
 use jrsonnet_evaluator::{val::ArrValue, Thunk, Val};
-use jrsonnet_gcmodule::Cc;
 
 use crate::VM;
 
modifiedcrates/jrsonnet-cli/src/stdlib.rsdiffbeforeafterboth
--- a/crates/jrsonnet-cli/src/stdlib.rs
+++ b/crates/jrsonnet-cli/src/stdlib.rs
@@ -1,7 +1,7 @@
 use std::{fs::read_to_string, str::FromStr};
 
 use clap::Parser;
-use jrsonnet_evaluator::{error::Result, trace::PathResolver, State};
+use jrsonnet_evaluator::{trace::PathResolver, Result, State};
 use jrsonnet_stdlib::ContextInitializer;
 
 #[derive(Clone)]
modifiedcrates/jrsonnet-evaluator/src/arr/spec.rsdiffbeforeafterboth
--- a/crates/jrsonnet-evaluator/src/arr/spec.rs
+++ b/crates/jrsonnet-evaluator/src/arr/spec.rs
@@ -6,12 +6,8 @@
 
 use super::ArrValue;
 use crate::{
-	error::ErrorKind::InfiniteRecursionDetected,
-	evaluate,
-	function::FuncVal,
-	typed::Typed,
-	val::{StrValue, ThunkValue},
-	Context, Error, ObjValue, Result, Thunk, Val,
+	error::ErrorKind::InfiniteRecursionDetected, evaluate, function::FuncVal, typed::Typed,
+	val::ThunkValue, Context, Error, ObjValue, Result, Thunk, Val,
 };
 
 pub trait ArrayLike: Any + Trace + Debug {
@@ -101,9 +97,7 @@
 	}
 
 	fn get_cheap(&self, index: usize) -> Option<Val> {
-		self.0
-			.get(index)
-			.map(|v| Val::Str(StrValue::Flat(IStr::from(*v))))
+		self.0.get(index).map(|v| Val::string(*v))
 	}
 	fn is_cheap(&self) -> bool {
 		true
modifiedcrates/jrsonnet-evaluator/src/ctx.rsdiffbeforeafterboth
--- a/crates/jrsonnet-evaluator/src/ctx.rs
+++ b/crates/jrsonnet-evaluator/src/ctx.rs
@@ -87,9 +87,9 @@
 	}
 
 	#[must_use]
-	pub fn with_var(self, name: IStr, value: Val) -> Self {
+	pub fn with_var(self, name: impl Into<IStr>, value: Val) -> Self {
 		let mut new_bindings = GcHashMap::with_capacity(1);
-		new_bindings.insert(name, Thunk::evaluated(value));
+		new_bindings.insert(name.into(), Thunk::evaluated(value));
 		self.extend(new_bindings, None, None, None)
 	}
 
@@ -161,8 +161,8 @@
 	}
 	/// # Panics
 	/// If `name` is already bound
-	pub fn bind(&mut self, name: IStr, value: Thunk<Val>) -> &mut Self {
-		let old = self.bindings.insert(name, value);
+	pub fn bind(&mut self, name: impl Into<IStr>, value: Thunk<Val>) -> &mut Self {
+		let old = self.bindings.insert(name.into(), value);
 		assert!(old.is_none(), "variable bound twice in single context call");
 		self
 	}
modifiedcrates/jrsonnet-evaluator/src/dynamic.rsdiffbeforeafterboth
--- a/crates/jrsonnet-evaluator/src/dynamic.rs
+++ b/crates/jrsonnet-evaluator/src/dynamic.rs
@@ -52,9 +52,3 @@
 		Self::new()
 	}
 }
-
-impl<T: Trace + Clone> From<Pending<T>> for Thunk<T> {
-	fn from(value: Pending<T>) -> Self {
-		Self::new(value)
-	}
-}
modifiedcrates/jrsonnet-evaluator/src/evaluate/mod.rsdiffbeforeafterboth
--- a/crates/jrsonnet-evaluator/src/evaluate/mod.rs
+++ b/crates/jrsonnet-evaluator/src/evaluate/mod.rs
@@ -36,7 +36,7 @@
 		}
 	}
 	Some(match &*expr.0 {
-		Expr::Str(s) => Val::Str(StrValue::Flat(s.clone())),
+		Expr::Str(s) => Val::string(s.clone()),
 		Expr::Num(n) => Val::Num(*n),
 		Expr::Literal(LiteralType::False) => Val::Bool(false),
 		Expr::Literal(LiteralType::True) => Val::Bool(true),
@@ -135,7 +135,7 @@
 					let fctx = Pending::new();
 					let mut new_bindings = GcHashMap::with_capacity(var.capacity_hint());
 					let value = Thunk::evaluated(Val::Arr(ArrValue::lazy(vec![
-						Thunk::evaluated(Val::Str(StrValue::Flat(field.clone()))),
+						Thunk::evaluated(Val::string(field.clone())),
 						Thunk::new(ObjectFieldThunk {
 							field: field.clone(),
 							obj: obj.clone(),
@@ -226,7 +226,7 @@
 			}
 
 			builder
-				.member(name.clone())
+				.field(name.clone())
 				.with_add(*plus)
 				.with_visibility(*visibility)
 				.with_location(value.1.clone())
@@ -262,7 +262,7 @@
 			}
 
 			builder
-				.member(name.clone())
+				.field(name.clone())
 				.with_visibility(*visibility)
 				.with_location(value.1.clone())
 				.bindable(UnboundMethod {
@@ -437,7 +437,7 @@
 		Literal(LiteralType::False) => Val::Bool(false),
 		Literal(LiteralType::Null) => Val::Null,
 		Parened(e) => evaluate(ctx, e)?,
-		Str(v) => Val::Str(StrValue::Flat(v.clone())),
+		Str(v) => Val::string(v.clone()),
 		Num(v) => Val::new_checked_num(*v)?,
 		BinaryOp(v1, o, v2) => evaluate_binary_op_special(ctx, v1, *o, v2)?,
 		UnaryOp(o, v) => evaluate_unary_op(*o, &evaluate(ctx, v)?)?,
@@ -672,7 +672,7 @@
 					|| format!("import {:?}", path.clone()),
 					|| s.import_resolved(resolved_path),
 				)?,
-				ImportStr(_) => Val::Str(StrValue::Flat(s.import_resolved_str(resolved_path)?)),
+				ImportStr(_) => Val::string(s.import_resolved_str(resolved_path)?),
 				ImportBin(_) => Val::Arr(ArrValue::bytes(s.import_resolved_bin(resolved_path)?)),
 				_ => unreachable!(),
 			}
modifiedcrates/jrsonnet-evaluator/src/evaluate/operator.rsdiffbeforeafterboth
--- a/crates/jrsonnet-evaluator/src/evaluate/operator.rs
+++ b/crates/jrsonnet-evaluator/src/evaluate/operator.rs
@@ -30,18 +30,12 @@
 	Ok(match (a, b) {
 		(Str(v1), Str(v2)) => Str(StrValue::concat(v1.clone(), v2.clone())),
 
-		(Num(a), Str(b)) => Str(StrValue::Flat(format!("{a}{b}").into())),
-		(Str(a), Num(b)) => Str(StrValue::Flat(format!("{a}{b}").into())),
+		(Num(a), Str(b)) => Val::string(format!("{a}{b}")),
+		(Str(a), Num(b)) => Val::string(format!("{a}{b}")),
 
-		(Str(a), o) | (o, Str(a)) if a.is_empty() => {
-			Val::Str(StrValue::Flat(o.clone().to_string()?))
-		}
-		(Str(a), o) => Str(StrValue::Flat(
-			format!("{a}{}", o.clone().to_string()?).into(),
-		)),
-		(o, Str(a)) => Str(StrValue::Flat(
-			format!("{}{a}", o.clone().to_string()?).into(),
-		)),
+		(Str(a), o) | (o, Str(a)) if a.is_empty() => Val::string(o.clone().to_string()?),
+		(Str(a), o) => Val::string(format!("{a}{}", o.clone().to_string()?)),
+		(o, Str(a)) => Val::string(format!("{}{a}", o.clone().to_string()?)),
 
 		(Obj(v1), Obj(v2)) => Obj(v2.extend_from(v1.clone())),
 		(Arr(a), Arr(b)) => Val::Arr(ArrValue::extended(a.clone(), b.clone())),
@@ -149,7 +143,7 @@
 		(Str(a), In, Obj(obj)) => Bool(obj.has_field_ex(a.clone().into_flat(), true)),
 		(a, Mod, b) => evaluate_mod_op(a, b)?,
 
-		(Str(v1), Mul, Num(v2)) => Str(StrValue::Flat(v1.to_string().repeat(*v2 as usize).into())),
+		(Str(v1), Mul, Num(v2)) => Val::string(v1.to_string().repeat(*v2 as usize)),
 
 		// Bool X Bool
 		(Bool(a), And, Bool(b)) => Bool(*a && *b),
modifiedcrates/jrsonnet-evaluator/src/function/arglike.rsdiffbeforeafterboth
--- a/crates/jrsonnet-evaluator/src/function/arglike.rs
+++ b/crates/jrsonnet-evaluator/src/function/arglike.rs
@@ -61,7 +61,7 @@
 impl ArgLike for TlaArg {
 	fn evaluate_arg(&self, ctx: Context, tailstrict: bool) -> Result<Thunk<Val>> {
 		match self {
-			TlaArg::String(s) => Ok(Thunk::evaluated(Val::Str(StrValue::Flat(s.clone())))),
+			TlaArg::String(s) => Ok(Thunk::evaluated(Val::string(s.clone()))),
 			TlaArg::Code(code) => Ok(if tailstrict {
 				Thunk::evaluated(evaluate(ctx, code)?)
 			} else {
modifiedcrates/jrsonnet-evaluator/src/function/mod.rsdiffbeforeafterboth
--- a/crates/jrsonnet-evaluator/src/function/mod.rs
+++ b/crates/jrsonnet-evaluator/src/function/mod.rs
@@ -12,7 +12,10 @@
 	native::NativeDesc,
 	parse::{parse_default_function_call, parse_function_call},
 };
-use crate::{evaluate, evaluate_trivial, gc::TraceBox, tb, Context, ContextBuilder, Result, Val};
+use crate::{
+	evaluate, evaluate_trivial, gc::TraceBox, tb, Context, ContextBuilder, Result,
+	Val,
+};
 
 pub mod arglike;
 pub mod builtin;
@@ -124,6 +127,9 @@
 	pub fn builtin(builtin: impl Builtin) -> Self {
 		Self::Builtin(Cc::new(tb!(builtin)))
 	}
+	pub fn static_builtin(static_builtin: &'static dyn StaticBuiltin) -> Self {
+		Self::StaticBuiltin(static_builtin)
+	}
 
 	pub fn params(&self) -> Vec<BuiltinParam> {
 		match self {
@@ -239,3 +245,17 @@
 		}
 	}
 }
+
+impl<T> From<T> for FuncVal
+where
+	T: Builtin,
+{
+	fn from(value: T) -> Self {
+		Self::builtin(value)
+	}
+}
+impl From<&'static dyn StaticBuiltin> for FuncVal {
+	fn from(value: &'static dyn StaticBuiltin) -> Self {
+		Self::static_builtin(value)
+	}
+}
modifiedcrates/jrsonnet-evaluator/src/function/native.rsdiffbeforeafterboth
--- a/crates/jrsonnet-evaluator/src/function/native.rs
+++ b/crates/jrsonnet-evaluator/src/function/native.rs
@@ -2,7 +2,7 @@
 	arglike::{ArgLike, OptionalContext},
 	FuncVal,
 };
-use crate::{error::Result, typed::Typed};
+use crate::{typed::Typed, Result};
 
 pub trait NativeDesc {
 	type Value;
modifiedcrates/jrsonnet-evaluator/src/gc.rsdiffbeforeafterboth
--- a/crates/jrsonnet-evaluator/src/gc.rs
+++ b/crates/jrsonnet-evaluator/src/gc.rs
@@ -117,9 +117,7 @@
 }
 
 #[derive(Debug)]
-pub struct GcHashMap<K, V>(
-	pub HashMap<K, V, BuildHasherDefault<FxHasher>>
-);
+pub struct GcHashMap<K, V>(pub HashMap<K, V, BuildHasherDefault<FxHasher>>);
 impl<K, V> GcHashMap<K, V> {
 	pub fn new() -> Self {
 		Self(HashMap::default())
modifiedcrates/jrsonnet-evaluator/src/integrations/serde.rsdiffbeforeafterboth
--- a/crates/jrsonnet-evaluator/src/integrations/serde.rs
+++ b/crates/jrsonnet-evaluator/src/integrations/serde.rs
@@ -11,10 +11,8 @@
 };
 
 use crate::{
-	arr::ArrValue,
-	error::{Error as JrError, ErrorKind, Result},
-	val::StrValue,
-	ObjValue, ObjValueBuilder, State, Val,
+	arr::ArrValue, runtime_error, Error as JrError, ObjValue, ObjValueBuilder,
+	Result, State, Val,
 };
 
 impl<'de> Deserialize<'de> for Val {
@@ -57,7 +55,7 @@
 			where
 				E: serde::de::Error,
 			{
-				Ok(Val::Str(StrValue::Flat(v.into())))
+				Ok(Val::string(v))
 			}
 
 			// visit_num! {
@@ -138,7 +136,7 @@
 
 				while let Some((k, v)) = map.next_entry::<Cow<'de, str>, Val>()? {
 					// Jsonnet ignores duplicate keys
-					out.member(k.into()).value_unchecked(v);
+					out.field(k).value(v);
 				}
 
 				Ok(Val::Obj(out.build()))
@@ -264,7 +262,7 @@
 		let inner = Val::Arr(ArrValue::eager(self.data));
 		if let Some(variant) = self.variant {
 			let mut out = ObjValue::builder_with_capacity(1);
-			out.member(variant).value_unchecked(inner);
+			out.field(variant).value(inner);
 			Ok(Val::Obj(out.build()))
 		} else {
 			Ok(inner)
@@ -365,7 +363,7 @@
 	{
 		let key = self.key.take().expect("no serialize_key called");
 		let value = value.serialize(IntoValSerializer)?;
-		self.data.member(key).value(value)?;
+		self.data.field(key).try_value(value)?;
 		Ok(())
 	}
 
@@ -378,7 +376,7 @@
 		let key = key.serialize(IntoValSerializer)?;
 		let key = key.to_string()?;
 		let value = value.serialize(IntoValSerializer)?;
-		self.data.member(key).value(value)?;
+		self.data.field(key).try_value(value)?;
 		Ok(())
 	}
 
@@ -386,7 +384,7 @@
 		let inner = Val::Obj(self.data.build());
 		if let Some(variant) = self.variant {
 			let mut out = ObjValue::builder_with_capacity(1);
-			out.member(variant).value_unchecked(inner);
+			out.field(variant).value(inner);
 			Ok(Val::Obj(out.build()))
 		} else {
 			Ok(inner)
@@ -550,7 +548,7 @@
 	{
 		let mut out = ObjValue::builder_with_capacity(1);
 		let value = value.serialize(self)?;
-		out.member(variant.into()).value_unchecked(value);
+		out.field(variant).value(value);
 		Ok(Val::Obj(out.build()))
 	}
 
modifiedcrates/jrsonnet-evaluator/src/lib.rsdiffbeforeafterboth
--- a/crates/jrsonnet-evaluator/src/lib.rs
+++ b/crates/jrsonnet-evaluator/src/lib.rs
@@ -498,7 +498,7 @@
 pub struct InitialUnderscore(pub Thunk<Val>);
 impl ContextInitializer for InitialUnderscore {
 	fn populate(&self, _for_file: Source, builder: &mut ContextBuilder) {
-		builder.bind("_".into(), self.0.clone());
+		builder.bind("_", self.0.clone());
 	}
 
 	fn as_any(&self) -> &dyn Any {
modifiedcrates/jrsonnet-evaluator/src/manifest.rsdiffbeforeafterboth
--- a/crates/jrsonnet-evaluator/src/manifest.rs
+++ b/crates/jrsonnet-evaluator/src/manifest.rs
@@ -174,11 +174,13 @@
 		Val::Str(s) => escape_string_json_buf(&s.clone().into_flat(), buf),
 		Val::Num(n) => write!(buf, "{n}").unwrap(),
 		#[cfg(feature = "exp-bigint")]
-		Val::BigInt(n) => if options.preserve_bigints {
-			write!(buf, "{n}").unwrap()
-		} else {
-			write!(buf, "{:?}", n.to_string()).unwrap()
-		},
+		Val::BigInt(n) => {
+			if options.preserve_bigints {
+				write!(buf, "{n}").unwrap()
+			} else {
+				write!(buf, "{:?}", n.to_string()).unwrap()
+			}
+		}
 		Val::Arr(items) => {
 			buf.push('[');
 			if !items.is_empty() {
modifiedcrates/jrsonnet-evaluator/src/obj.rsdiffbeforeafterboth
before · crates/jrsonnet-evaluator/src/obj.rs
1use std::{2	any::Any,3	cell::RefCell,4	fmt::Debug,5	hash::{Hash, Hasher},6	ptr::addr_of,7};89use jrsonnet_gcmodule::{Cc, Trace, Weak};10use jrsonnet_interner::IStr;11use jrsonnet_parser::{ExprLocation, Visibility};12use rustc_hash::FxHashMap;1314use crate::{15	arr::{PickObjectKeyValues, PickObjectValues},16	bail,17	error::{suggest_object_fields, Error, ErrorKind::*},18	function::CallLocation,19	gc::{GcHashMap, GcHashSet, TraceBox},20	operator::evaluate_add_op,21	tb,22	val::{ArrValue, ThunkValue},23	MaybeUnbound, Result, State, Thunk, Unbound, Val,24};2526#[cfg(not(feature = "exp-preserve-order"))]27mod ordering {28	#![allow(29		// This module works as stub for preserve-order feature30		clippy::unused_self,31	)]3233	use jrsonnet_gcmodule::Trace;3435	#[derive(Clone, Copy, Default, Debug, Trace)]36	pub struct FieldIndex(());37	impl FieldIndex {38		pub const fn next(self) -> Self {39			Self(())40		}41	}4243	#[derive(Clone, Copy, Default, Debug, Trace)]44	pub struct SuperDepth(());45	impl SuperDepth {46		pub const fn deeper(self) -> Self {47			Self(())48		}49	}5051	#[derive(Clone, Copy)]52	pub struct FieldSortKey(());53	impl FieldSortKey {54		pub const fn new(_: SuperDepth, _: FieldIndex) -> Self {55			Self(())56		}57	}58}5960#[cfg(feature = "exp-preserve-order")]61mod ordering {62	use std::cmp::Reverse;6364	use jrsonnet_gcmodule::Trace;6566	#[derive(Clone, Copy, Default, Debug, Trace, PartialEq, Eq, PartialOrd, Ord)]67	pub struct FieldIndex(u32);68	impl FieldIndex {69		pub fn next(self) -> Self {70			Self(self.0 + 1)71		}72	}7374	#[derive(Clone, Copy, Default, PartialEq, Eq, PartialOrd, Ord, Debug)]75	pub struct SuperDepth(u32);76	impl SuperDepth {77		pub fn deeper(self) -> Self {78			Self(self.0 + 1)79		}80	}8182	#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Debug)]83	pub struct FieldSortKey(Reverse<SuperDepth>, FieldIndex);84	impl FieldSortKey {85		pub fn new(depth: SuperDepth, index: FieldIndex) -> Self {86			Self(Reverse(depth), index)87		}88	}89}9091use ordering::*;9293// 0 - add94//  12 - visibility95#[derive(Clone, Copy)]96pub struct ObjFieldFlags(u8);97impl ObjFieldFlags {98	fn new(add: bool, visibility: Visibility) -> Self {99		let mut v = 0;100		if add {101			v |= 1;102		}103		v |= match visibility {104			Visibility::Normal => 0b000,105			Visibility::Hidden => 0b010,106			Visibility::Unhide => 0b100,107		};108		Self(v)109	}110	pub fn add(&self) -> bool {111		self.0 & 1 != 0112	}113	pub fn visibility(&self) -> Visibility {114		match (self.0 & 0b110) >> 1 {115			0b00 => Visibility::Normal,116			0b01 => Visibility::Hidden,117			0b10 => Visibility::Unhide,118			_ => unreachable!(),119		}120	}121}122impl Debug for ObjFieldFlags {123	fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {124		f.debug_struct("ObjFieldFlags")125			.field("add", &self.add())126			.field("visibility", &self.visibility())127			.finish()128	}129}130131#[allow(clippy::module_name_repetitions)]132#[derive(Debug, Trace)]133pub struct ObjMember {134	#[trace(skip)]135	flags: ObjFieldFlags,136	original_index: FieldIndex,137	pub invoke: MaybeUnbound,138	pub location: Option<ExprLocation>,139}140141pub trait ObjectAssertion: Trace {142	fn run(&self, super_obj: Option<ObjValue>, this: Option<ObjValue>) -> Result<()>;143}144145// Field => This146147#[derive(Trace)]148enum CacheValue {149	Cached(Val),150	NotFound,151	Pending,152	Errored(Error),153}154155#[allow(clippy::module_name_repetitions)]156#[derive(Trace)]157#[trace(tracking(force))]158pub struct OopObject {159	sup: Option<ObjValue>,160	// this: Option<ObjValue>,161	assertions: Cc<Vec<TraceBox<dyn ObjectAssertion>>>,162	assertions_ran: RefCell<GcHashSet<ObjValue>>,163	this_entries: Cc<GcHashMap<IStr, ObjMember>>,164	value_cache: RefCell<GcHashMap<(IStr, Option<WeakObjValue>), CacheValue>>,165}166impl Debug for OopObject {167	fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {168		f.debug_struct("OopObject")169			.field("sup", &self.sup)170			// .field("assertions", &self.assertions)171			// .field("assertions_ran", &self.assertions_ran)172			.field("this_entries", &self.this_entries)173			// .field("value_cache", &self.value_cache)174			.finish()175	}176}177178type EnumFieldsHandler<'a> = dyn FnMut(SuperDepth, FieldIndex, IStr, Visibility) -> bool + 'a;179180pub trait ObjectLike: Trace + Any + Debug {181	fn extend_from(&self, sup: ObjValue) -> ObjValue;182	/// When using standalone super in object, `this.super_obj.with_this(this)` is executed183	fn with_this(&self, me: ObjValue, this: ObjValue) -> ObjValue {184		ObjValue::new(ThisOverride { inner: me, this })185	}186	fn this(&self) -> Option<ObjValue> {187		None188	}189	fn len(&self) -> usize;190	fn is_empty(&self) -> bool;191	// If callback returns false, iteration stops192	fn enum_fields(&self, depth: SuperDepth, handler: &mut EnumFieldsHandler<'_>) -> bool;193194	fn has_field_include_hidden(&self, name: IStr) -> bool;195	fn has_field(&self, name: IStr) -> bool;196197	fn get_for(&self, key: IStr, this: ObjValue) -> Result<Option<Val>>;198	fn get_for_uncached(&self, key: IStr, this: ObjValue) -> Result<Option<Val>>;199	fn field_visibility(&self, field: IStr) -> Option<Visibility>;200201	fn run_assertions_raw(&self, this: ObjValue) -> Result<()>;202}203204#[derive(Clone, Trace)]205pub struct WeakObjValue(#[trace(skip)] pub(crate) Weak<TraceBox<dyn ObjectLike>>);206207impl PartialEq for WeakObjValue {208	fn eq(&self, other: &Self) -> bool {209		Weak::ptr_eq(&self.0, &other.0)210	}211}212213impl Eq for WeakObjValue {}214impl Hash for WeakObjValue {215	fn hash<H: Hasher>(&self, hasher: &mut H) {216		// Safety: usize is POD217		let addr = unsafe { *std::ptr::addr_of!(self.0).cast() };218		hasher.write_usize(addr);219	}220}221222#[allow(clippy::module_name_repetitions)]223#[derive(Clone, Trace, Debug)]224pub struct ObjValue(pub(crate) Cc<TraceBox<dyn ObjectLike>>);225226#[derive(Debug, Trace)]227struct EmptyObject;228impl ObjectLike for EmptyObject {229	fn extend_from(&self, sup: ObjValue) -> ObjValue {230		// obj + {} == obj231		sup232	}233234	fn this(&self) -> Option<ObjValue> {235		None236	}237238	fn len(&self) -> usize {239		0240	}241242	fn is_empty(&self) -> bool {243		true244	}245246	fn enum_fields(&self, _depth: SuperDepth, _handler: &mut EnumFieldsHandler<'_>) -> bool {247		false248	}249250	fn has_field_include_hidden(&self, _name: IStr) -> bool {251		false252	}253254	fn has_field(&self, _name: IStr) -> bool {255		false256	}257258	fn get_for(&self, _key: IStr, _this: ObjValue) -> Result<Option<Val>> {259		Ok(None)260	}261	fn get_for_uncached(&self, _key: IStr, _this: ObjValue) -> Result<Option<Val>> {262		Ok(None)263	}264265	fn run_assertions_raw(&self, _this: ObjValue) -> Result<()> {266		Ok(())267	}268269	fn field_visibility(&self, _field: IStr) -> Option<Visibility> {270		None271	}272}273274#[derive(Trace, Debug)]275struct ThisOverride {276	inner: ObjValue,277	this: ObjValue,278}279impl ObjectLike for ThisOverride {280	fn with_this(&self, _me: ObjValue, this: ObjValue) -> ObjValue {281		ObjValue::new(ThisOverride {282			inner: self.inner.clone(),283			this,284		})285	}286287	fn extend_from(&self, sup: ObjValue) -> ObjValue {288		self.inner.extend_from(sup).with_this(self.this.clone())289	}290291	fn this(&self) -> Option<ObjValue> {292		Some(self.this.clone())293	}294295	fn len(&self) -> usize {296		self.inner.len()297	}298299	fn is_empty(&self) -> bool {300		self.inner.is_empty()301	}302303	fn enum_fields(&self, depth: SuperDepth, handler: &mut EnumFieldsHandler<'_>) -> bool {304		self.inner.enum_fields(depth, handler)305	}306307	fn has_field_include_hidden(&self, name: IStr) -> bool {308		self.inner.has_field_include_hidden(name)309	}310311	fn has_field(&self, name: IStr) -> bool {312		self.inner.has_field(name)313	}314315	fn get_for(&self, key: IStr, this: ObjValue) -> Result<Option<Val>> {316		self.inner.get_for(key, this)317	}318319	fn get_for_uncached(&self, key: IStr, this: ObjValue) -> Result<Option<Val>> {320		self.inner.get_raw(key, this)321	}322323	fn field_visibility(&self, field: IStr) -> Option<Visibility> {324		self.inner.field_visibility(field)325	}326327	fn run_assertions_raw(&self, this: ObjValue) -> Result<()> {328		self.inner.run_assertions_raw(this)329	}330}331332impl ObjValue {333	pub fn new(v: impl ObjectLike) -> Self {334		Self(Cc::new(tb!(v)))335	}336	pub fn new_empty() -> Self {337		Self::new(EmptyObject)338	}339	pub fn builder() -> ObjValueBuilder {340		ObjValueBuilder::new()341	}342	pub fn builder_with_capacity(capacity: usize) -> ObjValueBuilder {343		ObjValueBuilder::with_capacity(capacity)344	}345	pub(crate) fn extend_with_raw_member(self, key: IStr, value: ObjMember) -> Self {346		let mut out = ObjValueBuilder::with_capacity(1);347		out.with_super(self);348		let mut member = out.member(key);349		if value.flags.add() {350			member = member.add()351		}352		if let Some(loc) = value.location {353			member = member.with_location(loc);354		}355		let _ = member356			.with_visibility(value.flags.visibility())357			.binding(value.invoke);358		out.build()359	}360	pub fn extend_field(&mut self, name: IStr) -> ObjMemberBuilder<ExtendBuilder<'_>> {361		ObjMemberBuilder::new(ExtendBuilder(self), name, FieldIndex::default())362	}363364	#[must_use]365	pub fn extend_from(&self, sup: Self) -> Self {366		self.0.extend_from(sup)367	}368	#[must_use]369	pub fn with_this(&self, this: Self) -> Self {370		self.0.with_this(self.clone(), this)371	}372	pub fn len(&self) -> usize {373		self.0.len()374	}375	pub fn is_empty(&self) -> bool {376		self.0.is_empty()377	}378	pub fn enum_fields(&self, depth: SuperDepth, handler: &mut EnumFieldsHandler<'_>) -> bool {379		self.0.enum_fields(depth, handler)380	}381382	pub fn has_field_include_hidden(&self, name: IStr) -> bool {383		self.0.has_field_include_hidden(name)384	}385	pub fn has_field(&self, name: IStr) -> bool {386		self.0.has_field(name)387	}388	pub fn has_field_ex(&self, name: IStr, include_hidden: bool) -> bool {389		if include_hidden {390			self.has_field_include_hidden(name)391		} else {392			self.has_field(name)393		}394	}395396	pub fn get(&self, key: IStr) -> Result<Option<Val>> {397		self.run_assertions()?;398		self.get_for(key, self.0.this().unwrap_or(self.clone()))399	}400401	pub fn get_for(&self, key: IStr, this: ObjValue) -> Result<Option<Val>> {402		self.0.get_for(key, this)403	}404405	pub fn get_or_bail(&self, key: IStr) -> Result<Val> {406		let Some(value) = self.get(key.clone())? else {407			let suggestions = suggest_object_fields(self, key.clone());408			bail!(NoSuchField(key, suggestions))409		};410		Ok(value)411	}412413	fn get_raw(&self, key: IStr, this: ObjValue) -> Result<Option<Val>> {414		self.0.get_for_uncached(key, this)415	}416417	fn field_visibility(&self, field: IStr) -> Option<Visibility> {418		self.0.field_visibility(field)419	}420421	pub fn run_assertions(&self) -> Result<()> {422		// FIXME: Should it use `self.0.this()` in case of standalone super?423		self.run_assertions_raw(self.clone())424	}425	fn run_assertions_raw(&self, this: ObjValue) -> Result<()> {426		self.0.run_assertions_raw(this)427	}428429	pub fn iter(430		&self,431		#[cfg(feature = "exp-preserve-order")] preserve_order: bool,432	) -> impl Iterator<Item = (IStr, Result<Val>)> + '_ {433		let fields = self.fields(434			#[cfg(feature = "exp-preserve-order")]435			preserve_order,436		);437		fields.into_iter().map(|field| {438			(439				field.clone(),440				self.get(field)441					.map(|opt| opt.expect("iterating over keys, field exists")),442			)443		})444	}445	pub fn get_lazy(&self, key: IStr) -> Option<Thunk<Val>> {446		#[derive(Trace)]447		struct ThunkGet {448			obj: ObjValue,449			key: IStr,450		}451		impl ThunkValue for ThunkGet {452			type Output = Val;453454			fn get(self: Box<Self>) -> Result<Self::Output> {455				Ok(self.obj.get(self.key)?.expect("field exists"))456			}457		}458459		if !self.has_field_ex(key.clone(), true) {460			return None;461		}462		Some(Thunk::new(ThunkGet {463			obj: self.clone(),464			key,465		}))466	}467	pub fn get_lazy_or_bail(&self, key: IStr) -> Thunk<Val> {468		#[derive(Trace)]469		struct ThunkGet {470			obj: ObjValue,471			key: IStr,472		}473		impl ThunkValue for ThunkGet {474			type Output = Val;475476			fn get(self: Box<Self>) -> Result<Self::Output> {477				Ok(self.obj.get_or_bail(self.key)?)478			}479		}480481		Thunk::new(ThunkGet {482			obj: self.clone(),483			key,484		})485	}486	pub fn ptr_eq(a: &Self, b: &Self) -> bool {487		Cc::ptr_eq(&a.0, &b.0)488	}489	pub fn downgrade(self) -> WeakObjValue {490		WeakObjValue(self.0.downgrade())491	}492	fn fields_visibility(&self) -> FxHashMap<IStr, (bool, FieldSortKey)> {493		let mut out = FxHashMap::default();494		self.enum_fields(495			SuperDepth::default(),496			&mut |depth, index, name, visibility| {497				let new_sort_key = FieldSortKey::new(depth, index);498				let entry = out.entry(name.clone());499				let (visible, _) = entry.or_insert((true, new_sort_key));500				match visibility {501					Visibility::Normal => {}502					Visibility::Hidden => {503						*visible = false;504					}505					Visibility::Unhide => {506						*visible = true;507					}508				};509				false510			},511		);512		out513	}514	pub fn fields_ex(515		&self,516		include_hidden: bool,517		#[cfg(feature = "exp-preserve-order")] preserve_order: bool,518	) -> Vec<IStr> {519		#[cfg(feature = "exp-preserve-order")]520		if preserve_order {521			let (mut fields, mut keys): (Vec<_>, Vec<_>) = self522				.fields_visibility()523				.into_iter()524				.filter(|(_, (visible, _))| include_hidden || *visible)525				.enumerate()526				.map(|(idx, (k, (_, sk)))| (k, (sk, idx)))527				.unzip();528			keys.sort_unstable_by_key(|v| v.0);529			// Reorder in-place by resulting indexes530			for i in 0..fields.len() {531				let x = fields[i].clone();532				let mut j = i;533				loop {534					let k = keys[j].1;535					keys[j].1 = j;536					if k == i {537						break;538					}539					fields[j] = fields[k].clone();540					j = k;541				}542				fields[j] = x;543			}544			return fields;545		}546547		let mut fields: Vec<_> = self548			.fields_visibility()549			.into_iter()550			.filter(|(_, (visible, _))| include_hidden || *visible)551			.map(|(k, _)| k)552			.collect();553		fields.sort_unstable();554		fields555	}556	pub fn fields(&self, #[cfg(feature = "exp-preserve-order")] preserve_order: bool) -> Vec<IStr> {557		self.fields_ex(558			false,559			#[cfg(feature = "exp-preserve-order")]560			preserve_order,561		)562	}563	pub fn values_ex(564		&self,565		include_hidden: bool,566		#[cfg(feature = "exp-preserve-order")] preserve_order: bool,567	) -> ArrValue {568		ArrValue::new(PickObjectValues::new(569			self.clone(),570			self.fields_ex(571				include_hidden,572				#[cfg(feature = "exp-preserve-order")]573				preserve_order,574			),575		))576	}577	pub fn values(&self, #[cfg(feature = "exp-preserve-order")] preserve_order: bool) -> ArrValue {578		self.values_ex(579			false,580			#[cfg(feature = "exp-preserve-order")]581			preserve_order,582		)583	}584	pub fn key_values_ex(585		&self,586		include_hidden: bool,587		#[cfg(feature = "exp-preserve-order")] preserve_order: bool,588	) -> ArrValue {589		ArrValue::new(PickObjectKeyValues::new(590			self.clone(),591			self.fields_ex(592				include_hidden,593				#[cfg(feature = "exp-preserve-order")]594				preserve_order,595			),596		))597	}598	pub fn key_values(599		&self,600		#[cfg(feature = "exp-preserve-order")] preserve_order: bool,601	) -> ArrValue {602		self.key_values_ex(603			false,604			#[cfg(feature = "exp-preserve-order")]605			preserve_order,606		)607	}608}609610impl OopObject {611	pub fn new(612		sup: Option<ObjValue>,613		this_entries: Cc<GcHashMap<IStr, ObjMember>>,614		assertions: Cc<Vec<TraceBox<dyn ObjectAssertion>>>,615	) -> Self {616		Self {617			sup,618			// this: None,619			assertions,620			assertions_ran: RefCell::new(GcHashSet::new()),621			this_entries,622			value_cache: RefCell::new(GcHashMap::new()),623		}624	}625626	fn evaluate_this(&self, v: &ObjMember, real_this: ObjValue) -> Result<Val> {627		v.invoke.evaluate(self.sup.clone(), Some(real_this))628	}629630	// FIXME: Duplication between ObjValue and OopObject631	fn fields_visibility(&self) -> FxHashMap<IStr, (bool, FieldSortKey)> {632		let mut out = FxHashMap::default();633		self.enum_fields(634			SuperDepth::default(),635			&mut |depth, index, name, visibility| {636				let new_sort_key = FieldSortKey::new(depth, index);637				let entry = out.entry(name.clone());638				let (visible, _) = entry.or_insert((true, new_sort_key));639				match visibility {640					Visibility::Normal => {}641					Visibility::Hidden => {642						*visible = false;643					}644					Visibility::Unhide => {645						*visible = true;646					}647				};648				false649			},650		);651		out652	}653}654655impl ObjectLike for OopObject {656	fn extend_from(&self, sup: ObjValue) -> ObjValue {657		ObjValue::new(match &self.sup {658			None => Self::new(659				Some(sup),660				self.this_entries.clone(),661				self.assertions.clone(),662			),663			Some(v) => Self::new(664				Some(v.extend_from(sup)),665				self.this_entries.clone(),666				self.assertions.clone(),667			),668		})669	}670671	fn len(&self) -> usize {672		self.fields_visibility()673			.into_iter()674			.filter(|(_, (visible, _))| *visible)675			.count()676	}677678	fn is_empty(&self) -> bool {679		if !self.this_entries.is_empty() {680			return false;681		}682		self.sup.as_ref().map_or(true, ObjValue::is_empty)683	}684685	/// Run callback for every field found in object686	///687	/// Returns true if ended prematurely688	fn enum_fields(&self, depth: SuperDepth, handler: &mut EnumFieldsHandler<'_>) -> bool {689		if let Some(s) = &self.sup {690			if s.enum_fields(depth.deeper(), handler) {691				return true;692			}693		}694		for (name, member) in self.this_entries.iter() {695			if handler(696				depth,697				member.original_index,698				name.clone(),699				member.flags.visibility(),700			) {701				return true;702			}703		}704		false705	}706707	fn has_field_include_hidden(&self, name: IStr) -> bool {708		if self.this_entries.contains_key(&name) {709			true710		} else if let Some(super_obj) = &self.sup {711			super_obj.has_field_include_hidden(name)712		} else {713			false714		}715	}716	fn has_field(&self, name: IStr) -> bool {717		self.field_visibility(name)718			.map_or(false, |v| v.is_visible())719	}720721	fn get_for(&self, key: IStr, this: ObjValue) -> Result<Option<Val>> {722		let cache_key = (key.clone(), Some(this.clone().downgrade()));723		if let Some(v) = self.value_cache.borrow().get(&cache_key) {724			return Ok(match v {725				CacheValue::Cached(v) => Some(v.clone()),726				CacheValue::NotFound => None,727				CacheValue::Pending => bail!(InfiniteRecursionDetected),728				CacheValue::Errored(e) => return Err(e.clone()),729			});730		}731		self.value_cache732			.borrow_mut()733			.insert(cache_key.clone(), CacheValue::Pending);734		let value = self.get_for_uncached(key, this).map_err(|e| {735			self.value_cache736				.borrow_mut()737				.insert(cache_key.clone(), CacheValue::Errored(e.clone()));738			e739		})?;740		self.value_cache.borrow_mut().insert(741			cache_key,742			value743				.as_ref()744				.map_or(CacheValue::NotFound, |v| CacheValue::Cached(v.clone())),745		);746		Ok(value)747	}748	fn get_for_uncached(&self, key: IStr, real_this: ObjValue) -> Result<Option<Val>> {749		match (self.this_entries.get(&key), &self.sup) {750			(Some(k), None) => Ok(Some(self.evaluate_this(k, real_this)?)),751			(Some(k), Some(super_obj)) => {752				let our = self.evaluate_this(k, real_this.clone())?;753				if k.flags.add() {754					super_obj755						.get_raw(key, real_this)?756						.map_or(Ok(Some(our.clone())), |v| {757							Ok(Some(evaluate_add_op(&v, &our)?))758						})759				} else {760					Ok(Some(our))761				}762			}763			(None, Some(super_obj)) => super_obj.get_raw(key, real_this),764			(None, None) => Ok(None),765		}766	}767	fn field_visibility(&self, name: IStr) -> Option<Visibility> {768		if let Some(m) = self.this_entries.get(&name) {769			Some(match &m.flags.visibility() {770				Visibility::Normal => self771					.sup772					.as_ref()773					.and_then(|super_obj| super_obj.field_visibility(name))774					.unwrap_or(Visibility::Normal),775				v => *v,776			})777		} else if let Some(super_obj) = &self.sup {778			super_obj.field_visibility(name)779		} else {780			None781		}782	}783784	fn run_assertions_raw(&self, real_this: ObjValue) -> Result<()> {785		if self.assertions.is_empty() {786			if let Some(super_obj) = &self.sup {787				super_obj.run_assertions_raw(real_this)?;788			}789			return Ok(());790		}791		if self.assertions_ran.borrow_mut().insert(real_this.clone()) {792			for assertion in self.assertions.iter() {793				if let Err(e) = assertion.run(self.sup.clone(), Some(real_this.clone())) {794					self.assertions_ran.borrow_mut().remove(&real_this);795					return Err(e);796				}797			}798			if let Some(super_obj) = &self.sup {799				super_obj.run_assertions_raw(real_this)?;800			}801		}802		Ok(())803	}804}805806impl PartialEq for ObjValue {807	fn eq(&self, other: &Self) -> bool {808		Cc::ptr_eq(&self.0, &other.0)809	}810}811812impl Eq for ObjValue {}813impl Hash for ObjValue {814	fn hash<H: Hasher>(&self, hasher: &mut H) {815		hasher.write_usize(addr_of!(*self.0) as usize);816	}817}818819#[allow(clippy::module_name_repetitions)]820pub struct ObjValueBuilder {821	sup: Option<ObjValue>,822	map: GcHashMap<IStr, ObjMember>,823	assertions: Vec<TraceBox<dyn ObjectAssertion>>,824	next_field_index: FieldIndex,825}826impl ObjValueBuilder {827	pub fn new() -> Self {828		Self::with_capacity(0)829	}830	pub fn with_capacity(capacity: usize) -> Self {831		Self {832			sup: None,833			map: GcHashMap::with_capacity(capacity),834			assertions: Vec::new(),835			next_field_index: FieldIndex::default(),836		}837	}838	pub fn reserve_asserts(&mut self, capacity: usize) -> &mut Self {839		self.assertions.reserve_exact(capacity);840		self841	}842	pub fn with_super(&mut self, super_obj: ObjValue) -> &mut Self {843		self.sup = Some(super_obj);844		self845	}846847	pub fn assert(&mut self, assertion: impl ObjectAssertion + 'static) -> &mut Self {848		self.assertions.push(tb!(assertion));849		self850	}851	pub fn member(&mut self, name: IStr) -> ObjMemberBuilder<ValueBuilder<'_>> {852		let field_index = self.next_field_index;853		self.next_field_index = self.next_field_index.next();854		ObjMemberBuilder::new(ValueBuilder(self), name, field_index)855	}856857	pub fn build(self) -> ObjValue {858		if self.sup.is_none() && self.map.is_empty() && self.assertions.is_empty() {859			return ObjValue::new_empty();860		}861		ObjValue::new(OopObject::new(862			self.sup,863			Cc::new(self.map),864			Cc::new(self.assertions),865		))866	}867}868impl Default for ObjValueBuilder {869	fn default() -> Self {870		Self::with_capacity(0)871	}872}873874#[allow(clippy::module_name_repetitions)]875#[must_use = "value not added unless binding() was called"]876pub struct ObjMemberBuilder<Kind> {877	kind: Kind,878	name: IStr,879	add: bool,880	visibility: Visibility,881	original_index: FieldIndex,882	location: Option<ExprLocation>,883}884885#[allow(clippy::missing_const_for_fn)]886impl<Kind> ObjMemberBuilder<Kind> {887	pub(crate) fn new(kind: Kind, name: IStr, original_index: FieldIndex) -> Self {888		Self {889			kind,890			name,891			original_index,892			add: false,893			visibility: Visibility::Normal,894			location: None,895		}896	}897898	pub const fn with_add(mut self, add: bool) -> Self {899		self.add = add;900		self901	}902	pub fn add(self) -> Self {903		self.with_add(true)904	}905	pub fn with_visibility(mut self, visibility: Visibility) -> Self {906		self.visibility = visibility;907		self908	}909	pub fn hide(self) -> Self {910		self.with_visibility(Visibility::Hidden)911	}912	pub fn with_location(mut self, location: ExprLocation) -> Self {913		self.location = Some(location);914		self915	}916	fn build_member(self, binding: MaybeUnbound) -> (Kind, IStr, ObjMember) {917		(918			self.kind,919			self.name,920			ObjMember {921				flags: ObjFieldFlags::new(self.add, self.visibility),922				original_index: self.original_index,923				invoke: binding,924				location: self.location,925			},926		)927	}928}929930pub struct ValueBuilder<'v>(&'v mut ObjValueBuilder);931impl ObjMemberBuilder<ValueBuilder<'_>> {932	/// Inserts value, replacing if it is already defined933	pub fn value_unchecked(self, value: Val) {934		let (receiver, name, member) =935			self.build_member(MaybeUnbound::Bound(Thunk::evaluated(value)));936		let entry = receiver.0.map.entry(name);937		entry.insert(member);938	}939940	pub fn value(self, value: Val) -> Result<()> {941		self.thunk(Thunk::evaluated(value))942	}943	pub fn thunk(self, value: Thunk<Val>) -> Result<()> {944		self.binding(MaybeUnbound::Bound(value))945	}946	pub fn bindable(self, bindable: impl Unbound<Bound = Val>) -> Result<()> {947		self.binding(MaybeUnbound::Unbound(Cc::new(tb!(bindable))))948	}949	pub fn binding(self, binding: MaybeUnbound) -> Result<()> {950		let (receiver, name, member) = self.build_member(binding);951		let location = member.location.clone();952		let old = receiver.0.map.insert(name.clone(), member);953		if old.is_some() {954			State::push(955				CallLocation(location.as_ref()),956				|| format!("field <{}> initializtion", name.clone()),957				|| bail!(DuplicateFieldName(name.clone())),958			)?;959		}960		Ok(())961	}962}963964pub struct ExtendBuilder<'v>(&'v mut ObjValue);965impl ObjMemberBuilder<ExtendBuilder<'_>> {966	pub fn value(self, value: Val) {967		self.binding(MaybeUnbound::Bound(Thunk::evaluated(value)));968	}969	pub fn bindable(self, bindable: TraceBox<dyn Unbound<Bound = Val>>) {970		self.binding(MaybeUnbound::Unbound(Cc::new(bindable)));971	}972	pub fn binding(self, binding: MaybeUnbound) {973		let (receiver, name, member) = self.build_member(binding);974		let new = receiver.0.clone();975		*receiver.0 = new.extend_with_raw_member(name, member);976	}977}
after · crates/jrsonnet-evaluator/src/obj.rs
1use std::{2	any::Any,3	cell::RefCell,4	fmt::Debug,5	hash::{Hash, Hasher},6	ptr::addr_of,7};89use jrsonnet_gcmodule::{Cc, Trace, Weak};10use jrsonnet_interner::IStr;11use jrsonnet_parser::{ExprLocation, Visibility};12use rustc_hash::FxHashMap;1314use crate::{15	arr::{PickObjectKeyValues, PickObjectValues},16	bail,17	error::{suggest_object_fields, Error, ErrorKind::*},18	function::{CallLocation, FuncVal},19	gc::{GcHashMap, GcHashSet, TraceBox},20	operator::evaluate_add_op,21	tb,22	val::{ArrValue, ThunkValue},23	MaybeUnbound, Result, State, Thunk, Unbound, Val,24};2526#[cfg(not(feature = "exp-preserve-order"))]27mod ordering {28	#![allow(29		// This module works as stub for preserve-order feature30		clippy::unused_self,31	)]3233	use jrsonnet_gcmodule::Trace;3435	#[derive(Clone, Copy, Default, Debug, Trace)]36	pub struct FieldIndex(());37	impl FieldIndex {38		pub const fn next(self) -> Self {39			Self(())40		}41	}4243	#[derive(Clone, Copy, Default, Debug, Trace)]44	pub struct SuperDepth(());45	impl SuperDepth {46		pub const fn deeper(self) -> Self {47			Self(())48		}49	}5051	#[derive(Clone, Copy)]52	pub struct FieldSortKey(());53	impl FieldSortKey {54		pub const fn new(_: SuperDepth, _: FieldIndex) -> Self {55			Self(())56		}57	}58}5960#[cfg(feature = "exp-preserve-order")]61mod ordering {62	use std::cmp::Reverse;6364	use jrsonnet_gcmodule::Trace;6566	#[derive(Clone, Copy, Default, Debug, Trace, PartialEq, Eq, PartialOrd, Ord)]67	pub struct FieldIndex(u32);68	impl FieldIndex {69		pub fn next(self) -> Self {70			Self(self.0 + 1)71		}72	}7374	#[derive(Clone, Copy, Default, PartialEq, Eq, PartialOrd, Ord, Debug)]75	pub struct SuperDepth(u32);76	impl SuperDepth {77		pub fn deeper(self) -> Self {78			Self(self.0 + 1)79		}80	}8182	#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Debug)]83	pub struct FieldSortKey(Reverse<SuperDepth>, FieldIndex);84	impl FieldSortKey {85		pub fn new(depth: SuperDepth, index: FieldIndex) -> Self {86			Self(Reverse(depth), index)87		}88	}89}9091use ordering::*;9293// 0 - add94//  12 - visibility95#[derive(Clone, Copy)]96pub struct ObjFieldFlags(u8);97impl ObjFieldFlags {98	fn new(add: bool, visibility: Visibility) -> Self {99		let mut v = 0;100		if add {101			v |= 1;102		}103		v |= match visibility {104			Visibility::Normal => 0b000,105			Visibility::Hidden => 0b010,106			Visibility::Unhide => 0b100,107		};108		Self(v)109	}110	pub fn add(&self) -> bool {111		self.0 & 1 != 0112	}113	pub fn visibility(&self) -> Visibility {114		match (self.0 & 0b110) >> 1 {115			0b00 => Visibility::Normal,116			0b01 => Visibility::Hidden,117			0b10 => Visibility::Unhide,118			_ => unreachable!(),119		}120	}121}122impl Debug for ObjFieldFlags {123	fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {124		f.debug_struct("ObjFieldFlags")125			.field("add", &self.add())126			.field("visibility", &self.visibility())127			.finish()128	}129}130131#[allow(clippy::module_name_repetitions)]132#[derive(Debug, Trace)]133pub struct ObjMember {134	#[trace(skip)]135	flags: ObjFieldFlags,136	original_index: FieldIndex,137	pub invoke: MaybeUnbound,138	pub location: Option<ExprLocation>,139}140141pub trait ObjectAssertion: Trace {142	fn run(&self, super_obj: Option<ObjValue>, this: Option<ObjValue>) -> Result<()>;143}144145// Field => This146147#[derive(Trace)]148enum CacheValue {149	Cached(Val),150	NotFound,151	Pending,152	Errored(Error),153}154155#[allow(clippy::module_name_repetitions)]156#[derive(Trace)]157#[trace(tracking(force))]158pub struct OopObject {159	sup: Option<ObjValue>,160	// this: Option<ObjValue>,161	assertions: Cc<Vec<TraceBox<dyn ObjectAssertion>>>,162	assertions_ran: RefCell<GcHashSet<ObjValue>>,163	this_entries: Cc<GcHashMap<IStr, ObjMember>>,164	value_cache: RefCell<GcHashMap<(IStr, Option<WeakObjValue>), CacheValue>>,165}166impl Debug for OopObject {167	fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {168		f.debug_struct("OopObject")169			.field("sup", &self.sup)170			// .field("assertions", &self.assertions)171			// .field("assertions_ran", &self.assertions_ran)172			.field("this_entries", &self.this_entries)173			// .field("value_cache", &self.value_cache)174			.finish()175	}176}177178type EnumFieldsHandler<'a> = dyn FnMut(SuperDepth, FieldIndex, IStr, Visibility) -> bool + 'a;179180pub trait ObjectLike: Trace + Any + Debug {181	fn extend_from(&self, sup: ObjValue) -> ObjValue;182	/// When using standalone super in object, `this.super_obj.with_this(this)` is executed183	fn with_this(&self, me: ObjValue, this: ObjValue) -> ObjValue {184		ObjValue::new(ThisOverride { inner: me, this })185	}186	fn this(&self) -> Option<ObjValue> {187		None188	}189	fn len(&self) -> usize;190	fn is_empty(&self) -> bool;191	// If callback returns false, iteration stops192	fn enum_fields(&self, depth: SuperDepth, handler: &mut EnumFieldsHandler<'_>) -> bool;193194	fn has_field_include_hidden(&self, name: IStr) -> bool;195	fn has_field(&self, name: IStr) -> bool;196197	fn get_for(&self, key: IStr, this: ObjValue) -> Result<Option<Val>>;198	fn get_for_uncached(&self, key: IStr, this: ObjValue) -> Result<Option<Val>>;199	fn field_visibility(&self, field: IStr) -> Option<Visibility>;200201	fn run_assertions_raw(&self, this: ObjValue) -> Result<()>;202}203204#[derive(Clone, Trace)]205pub struct WeakObjValue(#[trace(skip)] pub(crate) Weak<TraceBox<dyn ObjectLike>>);206207impl PartialEq for WeakObjValue {208	fn eq(&self, other: &Self) -> bool {209		Weak::ptr_eq(&self.0, &other.0)210	}211}212213impl Eq for WeakObjValue {}214impl Hash for WeakObjValue {215	fn hash<H: Hasher>(&self, hasher: &mut H) {216		// Safety: usize is POD217		let addr = unsafe { *std::ptr::addr_of!(self.0).cast() };218		hasher.write_usize(addr);219	}220}221222#[allow(clippy::module_name_repetitions)]223#[derive(Clone, Trace, Debug)]224pub struct ObjValue(pub(crate) Cc<TraceBox<dyn ObjectLike>>);225226#[derive(Debug, Trace)]227struct EmptyObject;228impl ObjectLike for EmptyObject {229	fn extend_from(&self, sup: ObjValue) -> ObjValue {230		// obj + {} == obj231		sup232	}233234	fn this(&self) -> Option<ObjValue> {235		None236	}237238	fn len(&self) -> usize {239		0240	}241242	fn is_empty(&self) -> bool {243		true244	}245246	fn enum_fields(&self, _depth: SuperDepth, _handler: &mut EnumFieldsHandler<'_>) -> bool {247		false248	}249250	fn has_field_include_hidden(&self, _name: IStr) -> bool {251		false252	}253254	fn has_field(&self, _name: IStr) -> bool {255		false256	}257258	fn get_for(&self, _key: IStr, _this: ObjValue) -> Result<Option<Val>> {259		Ok(None)260	}261	fn get_for_uncached(&self, _key: IStr, _this: ObjValue) -> Result<Option<Val>> {262		Ok(None)263	}264265	fn run_assertions_raw(&self, _this: ObjValue) -> Result<()> {266		Ok(())267	}268269	fn field_visibility(&self, _field: IStr) -> Option<Visibility> {270		None271	}272}273274#[derive(Trace, Debug)]275struct ThisOverride {276	inner: ObjValue,277	this: ObjValue,278}279impl ObjectLike for ThisOverride {280	fn with_this(&self, _me: ObjValue, this: ObjValue) -> ObjValue {281		ObjValue::new(ThisOverride {282			inner: self.inner.clone(),283			this,284		})285	}286287	fn extend_from(&self, sup: ObjValue) -> ObjValue {288		self.inner.extend_from(sup).with_this(self.this.clone())289	}290291	fn this(&self) -> Option<ObjValue> {292		Some(self.this.clone())293	}294295	fn len(&self) -> usize {296		self.inner.len()297	}298299	fn is_empty(&self) -> bool {300		self.inner.is_empty()301	}302303	fn enum_fields(&self, depth: SuperDepth, handler: &mut EnumFieldsHandler<'_>) -> bool {304		self.inner.enum_fields(depth, handler)305	}306307	fn has_field_include_hidden(&self, name: IStr) -> bool {308		self.inner.has_field_include_hidden(name)309	}310311	fn has_field(&self, name: IStr) -> bool {312		self.inner.has_field(name)313	}314315	fn get_for(&self, key: IStr, this: ObjValue) -> Result<Option<Val>> {316		self.inner.get_for(key, this)317	}318319	fn get_for_uncached(&self, key: IStr, this: ObjValue) -> Result<Option<Val>> {320		self.inner.get_raw(key, this)321	}322323	fn field_visibility(&self, field: IStr) -> Option<Visibility> {324		self.inner.field_visibility(field)325	}326327	fn run_assertions_raw(&self, this: ObjValue) -> Result<()> {328		self.inner.run_assertions_raw(this)329	}330}331332impl ObjValue {333	pub fn new(v: impl ObjectLike) -> Self {334		Self(Cc::new(tb!(v)))335	}336	pub fn new_empty() -> Self {337		Self::new(EmptyObject)338	}339	pub fn builder() -> ObjValueBuilder {340		ObjValueBuilder::new()341	}342	pub fn builder_with_capacity(capacity: usize) -> ObjValueBuilder {343		ObjValueBuilder::with_capacity(capacity)344	}345	pub(crate) fn extend_with_raw_member(self, key: IStr, value: ObjMember) -> Self {346		let mut out = ObjValueBuilder::with_capacity(1);347		out.with_super(self);348		let mut member = out.field(key);349		if value.flags.add() {350			member = member.add()351		}352		if let Some(loc) = value.location {353			member = member.with_location(loc);354		}355		let _ = member356			.with_visibility(value.flags.visibility())357			.binding(value.invoke);358		out.build()359	}360	pub fn extend_field(&mut self, name: IStr) -> ObjMemberBuilder<ExtendBuilder<'_>> {361		ObjMemberBuilder::new(ExtendBuilder(self), name, FieldIndex::default())362	}363364	#[must_use]365	pub fn extend_from(&self, sup: Self) -> Self {366		self.0.extend_from(sup)367	}368	#[must_use]369	pub fn with_this(&self, this: Self) -> Self {370		self.0.with_this(self.clone(), this)371	}372	pub fn len(&self) -> usize {373		self.0.len()374	}375	pub fn is_empty(&self) -> bool {376		self.0.is_empty()377	}378	pub fn enum_fields(&self, depth: SuperDepth, handler: &mut EnumFieldsHandler<'_>) -> bool {379		self.0.enum_fields(depth, handler)380	}381382	pub fn has_field_include_hidden(&self, name: IStr) -> bool {383		self.0.has_field_include_hidden(name)384	}385	pub fn has_field(&self, name: IStr) -> bool {386		self.0.has_field(name)387	}388	pub fn has_field_ex(&self, name: IStr, include_hidden: bool) -> bool {389		if include_hidden {390			self.has_field_include_hidden(name)391		} else {392			self.has_field(name)393		}394	}395396	pub fn get(&self, key: IStr) -> Result<Option<Val>> {397		self.run_assertions()?;398		self.get_for(key, self.0.this().unwrap_or(self.clone()))399	}400401	pub fn get_for(&self, key: IStr, this: ObjValue) -> Result<Option<Val>> {402		self.0.get_for(key, this)403	}404405	pub fn get_or_bail(&self, key: IStr) -> Result<Val> {406		let Some(value) = self.get(key.clone())? else {407			let suggestions = suggest_object_fields(self, key.clone());408			bail!(NoSuchField(key, suggestions))409		};410		Ok(value)411	}412413	fn get_raw(&self, key: IStr, this: ObjValue) -> Result<Option<Val>> {414		self.0.get_for_uncached(key, this)415	}416417	fn field_visibility(&self, field: IStr) -> Option<Visibility> {418		self.0.field_visibility(field)419	}420421	pub fn run_assertions(&self) -> Result<()> {422		// FIXME: Should it use `self.0.this()` in case of standalone super?423		self.run_assertions_raw(self.clone())424	}425	fn run_assertions_raw(&self, this: ObjValue) -> Result<()> {426		self.0.run_assertions_raw(this)427	}428429	pub fn iter(430		&self,431		#[cfg(feature = "exp-preserve-order")] preserve_order: bool,432	) -> impl Iterator<Item = (IStr, Result<Val>)> + '_ {433		let fields = self.fields(434			#[cfg(feature = "exp-preserve-order")]435			preserve_order,436		);437		fields.into_iter().map(|field| {438			(439				field.clone(),440				self.get(field)441					.map(|opt| opt.expect("iterating over keys, field exists")),442			)443		})444	}445	pub fn get_lazy(&self, key: IStr) -> Option<Thunk<Val>> {446		#[derive(Trace)]447		struct ThunkGet {448			obj: ObjValue,449			key: IStr,450		}451		impl ThunkValue for ThunkGet {452			type Output = Val;453454			fn get(self: Box<Self>) -> Result<Self::Output> {455				Ok(self.obj.get(self.key)?.expect("field exists"))456			}457		}458459		if !self.has_field_ex(key.clone(), true) {460			return None;461		}462		Some(Thunk::new(ThunkGet {463			obj: self.clone(),464			key,465		}))466	}467	pub fn get_lazy_or_bail(&self, key: IStr) -> Thunk<Val> {468		#[derive(Trace)]469		struct ThunkGet {470			obj: ObjValue,471			key: IStr,472		}473		impl ThunkValue for ThunkGet {474			type Output = Val;475476			fn get(self: Box<Self>) -> Result<Self::Output> {477				Ok(self.obj.get_or_bail(self.key)?)478			}479		}480481		Thunk::new(ThunkGet {482			obj: self.clone(),483			key,484		})485	}486	pub fn ptr_eq(a: &Self, b: &Self) -> bool {487		Cc::ptr_eq(&a.0, &b.0)488	}489	pub fn downgrade(self) -> WeakObjValue {490		WeakObjValue(self.0.downgrade())491	}492	fn fields_visibility(&self) -> FxHashMap<IStr, (bool, FieldSortKey)> {493		let mut out = FxHashMap::default();494		self.enum_fields(495			SuperDepth::default(),496			&mut |depth, index, name, visibility| {497				let new_sort_key = FieldSortKey::new(depth, index);498				let entry = out.entry(name.clone());499				let (visible, _) = entry.or_insert((true, new_sort_key));500				match visibility {501					Visibility::Normal => {}502					Visibility::Hidden => {503						*visible = false;504					}505					Visibility::Unhide => {506						*visible = true;507					}508				};509				false510			},511		);512		out513	}514	pub fn fields_ex(515		&self,516		include_hidden: bool,517		#[cfg(feature = "exp-preserve-order")] preserve_order: bool,518	) -> Vec<IStr> {519		#[cfg(feature = "exp-preserve-order")]520		if preserve_order {521			let (mut fields, mut keys): (Vec<_>, Vec<_>) = self522				.fields_visibility()523				.into_iter()524				.filter(|(_, (visible, _))| include_hidden || *visible)525				.enumerate()526				.map(|(idx, (k, (_, sk)))| (k, (sk, idx)))527				.unzip();528			keys.sort_unstable_by_key(|v| v.0);529			// Reorder in-place by resulting indexes530			for i in 0..fields.len() {531				let x = fields[i].clone();532				let mut j = i;533				loop {534					let k = keys[j].1;535					keys[j].1 = j;536					if k == i {537						break;538					}539					fields[j] = fields[k].clone();540					j = k;541				}542				fields[j] = x;543			}544			return fields;545		}546547		let mut fields: Vec<_> = self548			.fields_visibility()549			.into_iter()550			.filter(|(_, (visible, _))| include_hidden || *visible)551			.map(|(k, _)| k)552			.collect();553		fields.sort_unstable();554		fields555	}556	pub fn fields(&self, #[cfg(feature = "exp-preserve-order")] preserve_order: bool) -> Vec<IStr> {557		self.fields_ex(558			false,559			#[cfg(feature = "exp-preserve-order")]560			preserve_order,561		)562	}563	pub fn values_ex(564		&self,565		include_hidden: bool,566		#[cfg(feature = "exp-preserve-order")] preserve_order: bool,567	) -> ArrValue {568		ArrValue::new(PickObjectValues::new(569			self.clone(),570			self.fields_ex(571				include_hidden,572				#[cfg(feature = "exp-preserve-order")]573				preserve_order,574			),575		))576	}577	pub fn values(&self, #[cfg(feature = "exp-preserve-order")] preserve_order: bool) -> ArrValue {578		self.values_ex(579			false,580			#[cfg(feature = "exp-preserve-order")]581			preserve_order,582		)583	}584	pub fn key_values_ex(585		&self,586		include_hidden: bool,587		#[cfg(feature = "exp-preserve-order")] preserve_order: bool,588	) -> ArrValue {589		ArrValue::new(PickObjectKeyValues::new(590			self.clone(),591			self.fields_ex(592				include_hidden,593				#[cfg(feature = "exp-preserve-order")]594				preserve_order,595			),596		))597	}598	pub fn key_values(599		&self,600		#[cfg(feature = "exp-preserve-order")] preserve_order: bool,601	) -> ArrValue {602		self.key_values_ex(603			false,604			#[cfg(feature = "exp-preserve-order")]605			preserve_order,606		)607	}608}609610impl OopObject {611	pub fn new(612		sup: Option<ObjValue>,613		this_entries: Cc<GcHashMap<IStr, ObjMember>>,614		assertions: Cc<Vec<TraceBox<dyn ObjectAssertion>>>,615	) -> Self {616		Self {617			sup,618			// this: None,619			assertions,620			assertions_ran: RefCell::new(GcHashSet::new()),621			this_entries,622			value_cache: RefCell::new(GcHashMap::new()),623		}624	}625626	fn evaluate_this(&self, v: &ObjMember, real_this: ObjValue) -> Result<Val> {627		v.invoke.evaluate(self.sup.clone(), Some(real_this))628	}629630	// FIXME: Duplication between ObjValue and OopObject631	fn fields_visibility(&self) -> FxHashMap<IStr, (bool, FieldSortKey)> {632		let mut out = FxHashMap::default();633		self.enum_fields(634			SuperDepth::default(),635			&mut |depth, index, name, visibility| {636				let new_sort_key = FieldSortKey::new(depth, index);637				let entry = out.entry(name.clone());638				let (visible, _) = entry.or_insert((true, new_sort_key));639				match visibility {640					Visibility::Normal => {}641					Visibility::Hidden => {642						*visible = false;643					}644					Visibility::Unhide => {645						*visible = true;646					}647				};648				false649			},650		);651		out652	}653}654655impl ObjectLike for OopObject {656	fn extend_from(&self, sup: ObjValue) -> ObjValue {657		ObjValue::new(match &self.sup {658			None => Self::new(659				Some(sup),660				self.this_entries.clone(),661				self.assertions.clone(),662			),663			Some(v) => Self::new(664				Some(v.extend_from(sup)),665				self.this_entries.clone(),666				self.assertions.clone(),667			),668		})669	}670671	fn len(&self) -> usize {672		self.fields_visibility()673			.into_iter()674			.filter(|(_, (visible, _))| *visible)675			.count()676	}677678	fn is_empty(&self) -> bool {679		if !self.this_entries.is_empty() {680			return false;681		}682		self.sup.as_ref().map_or(true, ObjValue::is_empty)683	}684685	/// Run callback for every field found in object686	///687	/// Returns true if ended prematurely688	fn enum_fields(&self, depth: SuperDepth, handler: &mut EnumFieldsHandler<'_>) -> bool {689		if let Some(s) = &self.sup {690			if s.enum_fields(depth.deeper(), handler) {691				return true;692			}693		}694		for (name, member) in self.this_entries.iter() {695			if handler(696				depth,697				member.original_index,698				name.clone(),699				member.flags.visibility(),700			) {701				return true;702			}703		}704		false705	}706707	fn has_field_include_hidden(&self, name: IStr) -> bool {708		if self.this_entries.contains_key(&name) {709			true710		} else if let Some(super_obj) = &self.sup {711			super_obj.has_field_include_hidden(name)712		} else {713			false714		}715	}716	fn has_field(&self, name: IStr) -> bool {717		self.field_visibility(name)718			.map_or(false, |v| v.is_visible())719	}720721	fn get_for(&self, key: IStr, this: ObjValue) -> Result<Option<Val>> {722		let cache_key = (key.clone(), Some(this.clone().downgrade()));723		if let Some(v) = self.value_cache.borrow().get(&cache_key) {724			return Ok(match v {725				CacheValue::Cached(v) => Some(v.clone()),726				CacheValue::NotFound => None,727				CacheValue::Pending => bail!(InfiniteRecursionDetected),728				CacheValue::Errored(e) => return Err(e.clone()),729			});730		}731		self.value_cache732			.borrow_mut()733			.insert(cache_key.clone(), CacheValue::Pending);734		let value = self.get_for_uncached(key, this).map_err(|e| {735			self.value_cache736				.borrow_mut()737				.insert(cache_key.clone(), CacheValue::Errored(e.clone()));738			e739		})?;740		self.value_cache.borrow_mut().insert(741			cache_key,742			value743				.as_ref()744				.map_or(CacheValue::NotFound, |v| CacheValue::Cached(v.clone())),745		);746		Ok(value)747	}748	fn get_for_uncached(&self, key: IStr, real_this: ObjValue) -> Result<Option<Val>> {749		match (self.this_entries.get(&key), &self.sup) {750			(Some(k), None) => Ok(Some(self.evaluate_this(k, real_this)?)),751			(Some(k), Some(super_obj)) => {752				let our = self.evaluate_this(k, real_this.clone())?;753				if k.flags.add() {754					super_obj755						.get_raw(key, real_this)?756						.map_or(Ok(Some(our.clone())), |v| {757							Ok(Some(evaluate_add_op(&v, &our)?))758						})759				} else {760					Ok(Some(our))761				}762			}763			(None, Some(super_obj)) => super_obj.get_raw(key, real_this),764			(None, None) => Ok(None),765		}766	}767	fn field_visibility(&self, name: IStr) -> Option<Visibility> {768		if let Some(m) = self.this_entries.get(&name) {769			Some(match &m.flags.visibility() {770				Visibility::Normal => self771					.sup772					.as_ref()773					.and_then(|super_obj| super_obj.field_visibility(name))774					.unwrap_or(Visibility::Normal),775				v => *v,776			})777		} else if let Some(super_obj) = &self.sup {778			super_obj.field_visibility(name)779		} else {780			None781		}782	}783784	fn run_assertions_raw(&self, real_this: ObjValue) -> Result<()> {785		if self.assertions.is_empty() {786			if let Some(super_obj) = &self.sup {787				super_obj.run_assertions_raw(real_this)?;788			}789			return Ok(());790		}791		if self.assertions_ran.borrow_mut().insert(real_this.clone()) {792			for assertion in self.assertions.iter() {793				if let Err(e) = assertion.run(self.sup.clone(), Some(real_this.clone())) {794					self.assertions_ran.borrow_mut().remove(&real_this);795					return Err(e);796				}797			}798			if let Some(super_obj) = &self.sup {799				super_obj.run_assertions_raw(real_this)?;800			}801		}802		Ok(())803	}804}805806impl PartialEq for ObjValue {807	fn eq(&self, other: &Self) -> bool {808		Cc::ptr_eq(&self.0, &other.0)809	}810}811812impl Eq for ObjValue {}813impl Hash for ObjValue {814	fn hash<H: Hasher>(&self, hasher: &mut H) {815		hasher.write_usize(addr_of!(*self.0) as usize);816	}817}818819#[allow(clippy::module_name_repetitions)]820pub struct ObjValueBuilder {821	sup: Option<ObjValue>,822	map: GcHashMap<IStr, ObjMember>,823	assertions: Vec<TraceBox<dyn ObjectAssertion>>,824	next_field_index: FieldIndex,825}826impl ObjValueBuilder {827	pub fn new() -> Self {828		Self::with_capacity(0)829	}830	pub fn with_capacity(capacity: usize) -> Self {831		Self {832			sup: None,833			map: GcHashMap::with_capacity(capacity),834			assertions: Vec::new(),835			next_field_index: FieldIndex::default(),836		}837	}838	pub fn reserve_asserts(&mut self, capacity: usize) -> &mut Self {839		self.assertions.reserve_exact(capacity);840		self841	}842	pub fn with_super(&mut self, super_obj: ObjValue) -> &mut Self {843		self.sup = Some(super_obj);844		self845	}846847	pub fn assert(&mut self, assertion: impl ObjectAssertion + 'static) -> &mut Self {848		self.assertions.push(tb!(assertion));849		self850	}851	pub fn field(&mut self, name: impl Into<IStr>) -> ObjMemberBuilder<ValueBuilder<'_>> {852		let field_index = self.next_field_index;853		self.next_field_index = self.next_field_index.next();854		ObjMemberBuilder::new(ValueBuilder(self), name.into(), field_index)855	}856	/// Preset for common method definiton pattern:857	/// Create a hidden field with the function value.858	///859	/// `.field(name).hide().value(Val::function(value))`860	pub fn method(&mut self, name: impl Into<IStr>, value: impl Into<FuncVal>) -> &mut Self {861		self.field(name).hide().value(Val::Func(value.into()));862		self863	}864	pub fn try_method(865		&mut self,866		name: impl Into<IStr>,867		value: impl Into<FuncVal>,868	) -> Result<&mut Self> {869		self.field(name).hide().try_value(Val::Func(value.into()))?;870		Ok(self)871	}872873	pub fn build(self) -> ObjValue {874		if self.sup.is_none() && self.map.is_empty() && self.assertions.is_empty() {875			return ObjValue::new_empty();876		}877		ObjValue::new(OopObject::new(878			self.sup,879			Cc::new(self.map),880			Cc::new(self.assertions),881		))882	}883}884impl Default for ObjValueBuilder {885	fn default() -> Self {886		Self::with_capacity(0)887	}888}889890#[allow(clippy::module_name_repetitions)]891#[must_use = "value not added unless binding() was called"]892pub struct ObjMemberBuilder<Kind> {893	kind: Kind,894	name: IStr,895	add: bool,896	visibility: Visibility,897	original_index: FieldIndex,898	location: Option<ExprLocation>,899}900901#[allow(clippy::missing_const_for_fn)]902impl<Kind> ObjMemberBuilder<Kind> {903	pub(crate) fn new(kind: Kind, name: IStr, original_index: FieldIndex) -> Self {904		Self {905			kind,906			name,907			original_index,908			add: false,909			visibility: Visibility::Normal,910			location: None,911		}912	}913914	pub const fn with_add(mut self, add: bool) -> Self {915		self.add = add;916		self917	}918	pub fn add(self) -> Self {919		self.with_add(true)920	}921	pub fn with_visibility(mut self, visibility: Visibility) -> Self {922		self.visibility = visibility;923		self924	}925	pub fn hide(self) -> Self {926		self.with_visibility(Visibility::Hidden)927	}928	pub fn with_location(mut self, location: ExprLocation) -> Self {929		self.location = Some(location);930		self931	}932	fn build_member(self, binding: MaybeUnbound) -> (Kind, IStr, ObjMember) {933		(934			self.kind,935			self.name,936			ObjMember {937				flags: ObjFieldFlags::new(self.add, self.visibility),938				original_index: self.original_index,939				invoke: binding,940				location: self.location,941			},942		)943	}944}945946pub struct ValueBuilder<'v>(&'v mut ObjValueBuilder);947impl ObjMemberBuilder<ValueBuilder<'_>> {948	/// Inserts value, replacing if it is already defined949	pub fn value(self, value: impl Into<Val>) {950		let (receiver, name, member) =951			self.build_member(MaybeUnbound::Bound(Thunk::evaluated(value.into())));952		let entry = receiver.0.map.entry(name);953		entry.insert(member);954	}955956	/// Tries to insert value, returns an error if it was already defined957	pub fn try_value(self, value: impl Into<Val>) -> Result<()> {958		self.thunk(Thunk::evaluated(value.into()))959	}960	pub fn thunk(self, value: impl Into<Thunk<Val>>) -> Result<()> {961		self.binding(MaybeUnbound::Bound(value.into()))962	}963	pub fn bindable(self, bindable: impl Unbound<Bound = Val>) -> Result<()> {964		self.binding(MaybeUnbound::Unbound(Cc::new(tb!(bindable))))965	}966	pub fn binding(self, binding: MaybeUnbound) -> Result<()> {967		let (receiver, name, member) = self.build_member(binding);968		let location = member.location.clone();969		let old = receiver.0.map.insert(name.clone(), member);970		if old.is_some() {971			State::push(972				CallLocation(location.as_ref()),973				|| format!("field <{}> initializtion", name.clone()),974				|| bail!(DuplicateFieldName(name.clone())),975			)?;976		}977		Ok(())978	}979}980981pub struct ExtendBuilder<'v>(&'v mut ObjValue);982impl ObjMemberBuilder<ExtendBuilder<'_>> {983	pub fn value(self, value: impl Into<Val>) {984		self.binding(MaybeUnbound::Bound(Thunk::evaluated(value.into())));985	}986	pub fn bindable(self, bindable: TraceBox<dyn Unbound<Bound = Val>>) {987		self.binding(MaybeUnbound::Unbound(Cc::new(bindable)));988	}989	pub fn binding(self, binding: MaybeUnbound) {990		let (receiver, name, member) = self.build_member(binding);991		let new = receiver.0.clone();992		*receiver.0 = new.extend_with_raw_member(name, member);993	}994}
modifiedcrates/jrsonnet-evaluator/src/typed/conversions.rsdiffbeforeafterboth
--- a/crates/jrsonnet-evaluator/src/typed/conversions.rs
+++ b/crates/jrsonnet-evaluator/src/typed/conversions.rs
@@ -276,7 +276,7 @@
 	const TYPE: &'static ComplexValType = &ComplexValType::Simple(ValType::Str);
 
 	fn into_untyped(value: Self) -> Result<Val> {
-		Ok(Val::Str(StrValue::Flat(value)))
+		Ok(Val::string(value))
 	}
 
 	fn from_untyped(value: Val) -> Result<Self> {
@@ -292,7 +292,7 @@
 	const TYPE: &'static ComplexValType = &ComplexValType::Simple(ValType::Str);
 
 	fn into_untyped(value: Self) -> Result<Val> {
-		Ok(Val::Str(StrValue::Flat(value.into())))
+		Ok(Val::string(value))
 	}
 
 	fn from_untyped(value: Val) -> Result<Self> {
@@ -308,7 +308,7 @@
 	const TYPE: &'static ComplexValType = &ComplexValType::Char;
 
 	fn into_untyped(value: Self) -> Result<Val> {
-		Ok(Val::Str(StrValue::Flat(value.to_string().into())))
+		Ok(Val::string(value))
 	}
 
 	fn from_untyped(value: Val) -> Result<Self> {
@@ -356,7 +356,7 @@
 				bail!("map key should serialize to string");
 			};
 			let value = V::into_untyped(v)?;
-			out.member(key).value_unchecked(value);
+			out.field(key).value(value);
 		}
 		Ok(Val::Obj(out.build()))
 	}
@@ -611,7 +611,7 @@
 
 	fn into_untyped(value: Self) -> Result<Val> {
 		match value {
-			IndexableVal::Str(s) => Ok(Val::Str(StrValue::Flat(s))),
+			IndexableVal::Str(s) => Ok(Val::string(s)),
 			IndexableVal::Arr(a) => Ok(Val::Arr(a)),
 		}
 	}
modifiedcrates/jrsonnet-evaluator/src/val.rsdiffbeforeafterboth
--- a/crates/jrsonnet-evaluator/src/val.rs
+++ b/crates/jrsonnet-evaluator/src/val.rs
@@ -142,6 +142,14 @@
 		}
 	}
 }
+impl<T, V: Trace> From<T> for Thunk<V>
+where
+	T: ThunkValue<Output = V>,
+{
+	fn from(value: T) -> Self {
+		Thunk::new(value)
+	}
+}
 
 impl<T: Trace + Default> Default for Thunk<T> {
 	fn default() -> Self {
@@ -323,21 +331,14 @@
 		}
 	}
 }
-impl From<&str> for StrValue {
-	fn from(value: &str) -> Self {
-		Self::Flat(value.into())
-	}
-}
-impl From<String> for StrValue {
-	fn from(value: String) -> Self {
-		Self::Flat(value.into())
+impl<T> From<T> for StrValue
+where
+	IStr: From<T>,
+{
+	fn from(value: T) -> Self {
+		Self::Flat(IStr::from(value))
 	}
 }
-impl From<IStr> for StrValue {
-	fn from(value: IStr) -> Self {
-		Self::Flat(value)
-	}
-}
 impl Display for StrValue {
 	fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
 		match self {
@@ -401,7 +402,7 @@
 impl From<IndexableVal> for Val {
 	fn from(v: IndexableVal) -> Self {
 		match v {
-			IndexableVal::Str(s) => Self::Str(StrValue::Flat(s)),
+			IndexableVal::Str(s) => Self::string(s),
 			IndexableVal::Arr(a) => Self::Arr(a),
 		}
 	}
@@ -499,6 +500,34 @@
 			_ => bail!(ValueIsNotIndexable(self.value_type())),
 		})
 	}
+
+	pub fn function(function: impl Into<FuncVal>) -> Self {
+		Self::Func(function.into())
+	}
+	pub fn string(string: impl Into<StrValue>) -> Self {
+		Self::Str(string.into())
+	}
+}
+
+impl From<IStr> for Val {
+	fn from(value: IStr) -> Self {
+		Self::string(value)
+	}
+}
+impl From<String> for Val {
+	fn from(value: String) -> Self {
+		Self::string(value)
+	}
+}
+impl From<&str> for Val {
+	fn from(value: &str) -> Self {
+		Self::string(value)
+	}
+}
+impl From<ObjValue> for Val {
+	fn from(value: ObjValue) -> Self {
+		Self::Obj(value)
+	}
 }
 
 const fn is_function_like(val: &Val) -> bool {
modifiedcrates/jrsonnet-macros/src/lib.rsdiffbeforeafterboth
--- a/crates/jrsonnet-macros/src/lib.rs
+++ b/crates/jrsonnet-macros/src/lib.rs
@@ -567,18 +567,18 @@
 			if self.is_option {
 				quote! {
 					if let Some(value) = self.#ident {
-						out.member(#name.into())
+						out.field(#name)
 							#hide
 							#add
-							.value(<#ty as Typed>::into_untyped(value)?)?;
+							.try_value(<#ty as Typed>::into_untyped(value)?)?;
 					}
 				}
 			} else {
 				quote! {
-					out.member(#name.into())
+					out.field(#name)
 						#hide
 						#add
-						.value(<#ty as Typed>::into_untyped(self.#ident)?)?;
+						.try_value(<#ty as Typed>::into_untyped(self.#ident)?)?;
 				}
 			}
 		} else if self.is_option {
modifiedcrates/jrsonnet-stdlib/src/arrays.rsdiffbeforeafterboth
--- a/crates/jrsonnet-stdlib/src/arrays.rs
+++ b/crates/jrsonnet-stdlib/src/arrays.rs
@@ -36,7 +36,7 @@
 #[builtin]
 pub fn builtin_repeat(what: Either![IStr, ArrValue], count: usize) -> Result<Val> {
 	Ok(match what {
-		Either2::A(s) => Val::Str(StrValue::Flat(s.repeat(count).into())),
+		Either2::A(s) => Val::string(s.repeat(count)),
 		Either2::B(arr) => Val::Arr(
 			ArrValue::repeated(arr, count)
 				.ok_or_else(|| runtime_error!("repeated length overflow"))?,
modifiedcrates/jrsonnet-stdlib/src/lib.rsdiffbeforeafterboth
--- a/crates/jrsonnet-stdlib/src/lib.rs
+++ b/crates/jrsonnet-stdlib/src/lib.rs
@@ -6,13 +6,12 @@
 
 use jrsonnet_evaluator::{
 	error::{ErrorKind::*, Result},
-	function::{builtin::Builtin, CallLocation, FuncVal, TlaArg},
-	gc::TraceBox,
+	function::{CallLocation, FuncVal, TlaArg},
 	tb,
 	trace::PathResolver,
 	ContextBuilder, IStr, ObjValue, ObjValueBuilder, State, Thunk, Val,
 };
-use jrsonnet_gcmodule::{Cc, Trace};
+use jrsonnet_gcmodule::Trace;
 use jrsonnet_parser::Source;
 
 mod expr;
@@ -182,38 +181,24 @@
 	.iter()
 	.cloned()
 	{
-		builder
-			.member(name.into())
-			.hide()
-			.value(Val::Func(FuncVal::StaticBuiltin(builtin)))
-			.expect("no conflict");
+		builder.method(name, builtin);
 	}
 
-	builder
-		.member("extVar".into())
-		.hide()
-		.value(Val::Func(FuncVal::builtin(builtin_ext_var {
+	builder.method(
+		"extVar",
+		builtin_ext_var {
 			settings: settings.clone(),
-		})))
-		.expect("no conflict");
-	builder
-		.member("native".into())
-		.hide()
-		.value(Val::Func(FuncVal::builtin(builtin_native {
+		},
+	);
+	builder.method(
+		"native",
+		builtin_native {
 			settings: settings.clone(),
-		})))
-		.expect("no conflict");
-	builder
-		.member("trace".into())
-		.hide()
-		.value(Val::Func(FuncVal::builtin(builtin_trace { settings })))
-		.expect("no conflict");
+		},
+	);
+	builder.method("trace", builtin_trace { settings });
 
-	builder
-		.member("id".into())
-		.hide()
-		.value(Val::Func(FuncVal::Id))
-		.expect("no conflict");
+	builder.method("id", FuncVal::Id);
 
 	builder.build()
 }
@@ -293,7 +278,7 @@
 			#[cfg(not(feature = "legacy-this-file"))]
 			context: {
 				let mut context = ContextBuilder::with_capacity(_s, 1);
-				context.bind("std".into(), stdlib_thunk.clone());
+				context.bind("std", stdlib_thunk.clone());
 				context.build()
 			},
 			#[cfg(not(feature = "legacy-this-file"))]
@@ -338,10 +323,10 @@
 			.insert(name.into(), TlaArg::Code(parsed));
 		Ok(())
 	}
-	pub fn add_native(&self, name: IStr, cb: impl Builtin) {
+	pub fn add_native(&self, name: impl Into<IStr>, cb: impl Into<FuncVal>) {
 		self.settings_mut()
 			.ext_natives
-			.insert(name, Cc::new(tb!(cb)));
+			.insert(name.into(), cb.into());
 	}
 }
 impl jrsonnet_evaluator::ContextInitializer for ContextInitializer {
@@ -354,7 +339,7 @@
 	}
 	#[cfg(not(feature = "legacy-this-file"))]
 	fn populate(&self, _for_file: Source, builder: &mut ContextBuilder) {
-		builder.bind("std".into(), self.stdlib_thunk.clone());
+		builder.bind("std", self.stdlib_thunk.clone());
 	}
 	#[cfg(feature = "legacy-this-file")]
 	fn populate(&self, source: Source, builder: &mut ContextBuilder) {
@@ -362,14 +347,14 @@
 
 		let mut std = ObjValueBuilder::new();
 		std.with_super(self.stdlib_obj.clone());
-		std.member("thisFile".into())
+		std.field("thisFile".into())
 			.hide()
-			.value(Val::Str(StrValue::Flat(
+			.value(Val::string(
 				match source.source_path().path() {
 					Some(p) => self.settings().path_resolver.resolve(p).into(),
 					None => source.source_path().to_string().into(),
 				},
-			)))
+			))
 			.expect("this object builder is empty");
 		let stdlib_with_this_file = std.build();
 
modifiedcrates/jrsonnet-stdlib/src/misc.rsdiffbeforeafterboth
--- a/crates/jrsonnet-stdlib/src/misc.rs
+++ b/crates/jrsonnet-stdlib/src/misc.rs
@@ -47,7 +47,7 @@
 		.ext_natives
 		.get(&x)
 		.cloned()
-		.map_or(Val::Null, |v| Val::Func(FuncVal::Builtin(v)))
+		.map_or(Val::Null, |v| Val::Func(v))
 }
 
 #[builtin(fields(
modifiedcrates/jrsonnet-stdlib/src/objects.rsdiffbeforeafterboth
--- a/crates/jrsonnet-stdlib/src/objects.rs
+++ b/crates/jrsonnet-stdlib/src/objects.rs
@@ -122,7 +122,7 @@
 		if k == key {
 			continue;
 		}
-		new_obj.member(k).value_unchecked(v.unwrap())
+		new_obj.field(k).value(v.unwrap())
 	}
 
 	new_obj.build()
modifiedcrates/jrsonnet-stdlib/src/operator.rsdiffbeforeafterboth
--- a/crates/jrsonnet-stdlib/src/operator.rs
+++ b/crates/jrsonnet-stdlib/src/operator.rs
@@ -16,7 +16,7 @@
 	evaluate_mod_op(
 		&match a {
 			A(v) => Val::Num(v),
-			B(s) => Val::Str(StrValue::Flat(s)),
+			B(s) => Val::string(s),
 		},
 		&b,
 	)
modifiedcrates/jrsonnet-stdlib/src/sets.rsdiffbeforeafterboth
--- a/crates/jrsonnet-stdlib/src/sets.rs
+++ b/crates/jrsonnet-stdlib/src/sets.rs
@@ -1,11 +1,10 @@
 use std::cmp::Ordering;
 
 use jrsonnet_evaluator::{
-	error::Result,
 	function::{builtin, FuncVal},
 	operator::evaluate_compare_op,
 	val::ArrValue,
-	Thunk, Val,
+	Result, Thunk, Val,
 };
 use jrsonnet_parser::BinaryOpType;
 
@@ -108,7 +107,7 @@
 			}
 		};
 	}
-	while let Some(ac) = &ak {
+	while let Some(_ac) = &ak {
 		// In a, but not in b
 		out.push(av.clone().expect("ak != None"));
 		av = a.next();
modifiedcrates/jrsonnet-stdlib/src/strings.rsdiffbeforeafterboth
--- a/crates/jrsonnet-stdlib/src/strings.rs
+++ b/crates/jrsonnet-stdlib/src/strings.rs
@@ -3,7 +3,7 @@
 	error::{ErrorKind::*, Result},
 	function::builtin,
 	typed::{Either2, M1},
-	val::{ArrValue, StrValue},
+	val::ArrValue,
 	Either, IStr, Val,
 };
 
@@ -41,14 +41,8 @@
 pub fn builtin_splitlimit(str: IStr, c: IStr, maxsplits: Either![usize, M1]) -> ArrValue {
 	use Either2::*;
 	match maxsplits {
-		A(n) => str
-			.splitn(n + 1, &c as &str)
-			.map(|s| Val::Str(StrValue::Flat(s.into())))
-			.collect(),
-		B(_) => str
-			.split(&c as &str)
-			.map(|s| Val::Str(StrValue::Flat(s.into())))
-			.collect(),
+		A(n) => str.splitn(n + 1, &c as &str).map(Val::string).collect(),
+		B(_) => str.split(&c as &str).map(Val::string).collect(),
 	}
 }
 
modifiedtests/tests/builtin.rsdiffbeforeafterboth
--- a/tests/tests/builtin.rs
+++ b/tests/tests/builtin.rs
@@ -36,7 +36,7 @@
 	s.with_stdlib();
 	s.add_global(
 		"nativeAdd".into(),
-		Thunk::evaluated(Val::Func(FuncVal::StaticBuiltin(native_add::INST))),
+		Thunk::evaluated(Val::function(native_add::INST)),
 	);
 
 	let v = s.evaluate_snippet(
@@ -69,7 +69,7 @@
 	s.with_stdlib();
 	s.add_global(
 		"curryAdd".into(),
-		Thunk::evaluated(Val::Func(FuncVal::StaticBuiltin(curry_add::INST))),
+		Thunk::evaluated(Val::function(curry_add::INST)),
 	);
 
 	let v = s.evaluate_snippet(
modifiedtests/tests/common.rsdiffbeforeafterboth
--- a/tests/tests/common.rs
+++ b/tests/tests/common.rs
@@ -77,12 +77,8 @@
 #[allow(dead_code)]
 pub fn with_test(s: &State) {
 	let mut bobj = ObjValueBuilder::new();
-	bobj.member("assertThrow".into())
-		.hide()
-		.value_unchecked(Val::Func(FuncVal::StaticBuiltin(assert_throw::INST)));
-	bobj.member("paramNames".into())
-		.hide()
-		.value_unchecked(Val::Func(FuncVal::StaticBuiltin(param_names::INST)));
+	bobj.method("assertThrow", assert_throw::INST);
+	bobj.method("paramNames", param_names::INST);
 
 	s.add_global("test".into(), Thunk::evaluated(Val::Obj(bobj.build())))
 }