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
before · crates/jrsonnet-evaluator/src/manifest.rs
1use std::{borrow::Cow, fmt::Write};23use crate::{bail, Result, State, Val};45pub trait ManifestFormat {6	fn manifest_buf(&self, val: Val, buf: &mut String) -> Result<()>;7	fn manifest(&self, val: Val) -> Result<String> {8		let mut out = String::new();9		self.manifest_buf(val, &mut out)?;10		Ok(out)11	}12	/// When outputing to file, is it safe to append a trailing newline (I.e newline won't change13	/// the meaning).14	///15	/// Default implementation returns `true`16	fn file_trailing_newline(&self) -> bool {17		true18	}19}20impl<T> ManifestFormat for Box<T>21where22	T: ManifestFormat + ?Sized,23{24	fn manifest_buf(&self, val: Val, buf: &mut String) -> Result<()> {25		let inner = &**self;26		inner.manifest_buf(val, buf)27	}28	fn file_trailing_newline(&self) -> bool {29		let inner = &**self;30		inner.file_trailing_newline()31	}32}33impl<T> ManifestFormat for &'_ T34where35	T: ManifestFormat + ?Sized,36{37	fn manifest_buf(&self, val: Val, buf: &mut String) -> Result<()> {38		let inner = &**self;39		inner.manifest_buf(val, buf)40	}41	fn file_trailing_newline(&self) -> bool {42		let inner = &**self;43		inner.file_trailing_newline()44	}45}4647#[derive(PartialEq, Eq, Clone, Copy)]48enum JsonFormatting {49	// Applied in manifestification50	Manifest,51	/// Used for std.manifestJson52	/// Empty array/objects extends to "[\n\n]" instead of "[ ]" as in manifest53	Std,54	/// No line breaks, used in `obj+''`55	ToString,56	/// Minified json57	Minify,58}5960pub struct JsonFormat<'s> {61	padding: Cow<'s, str>,62	mtype: JsonFormatting,63	newline: &'s str,64	key_val_sep: &'s str,65	#[cfg(feature = "exp-preserve-order")]66	preserve_order: bool,67	#[cfg(feature = "exp-bigint")]68	preserve_bigints: bool,69}7071impl<'s> JsonFormat<'s> {72	// Minifying format73	pub fn minify(#[cfg(feature = "exp-preserve-order")] preserve_order: bool) -> Self {74		Self {75			padding: Cow::Borrowed(""),76			mtype: JsonFormatting::Minify,77			newline: "\n",78			key_val_sep: ":",79			#[cfg(feature = "exp-preserve-order")]80			preserve_order,81			#[cfg(feature = "exp-bigint")]82			preserve_bigints: false,83		}84	}85	// Same format as std.toString86	pub fn std_to_string() -> Self {87		Self {88			padding: Cow::Borrowed(""),89			mtype: JsonFormatting::ToString,90			newline: "\n",91			key_val_sep: ": ",92			#[cfg(feature = "exp-preserve-order")]93			preserve_order: false,94			#[cfg(feature = "exp-bigint")]95			preserve_bigints: false,96		}97	}98	pub fn std_to_json(99		padding: String,100		newline: &'s str,101		key_val_sep: &'s str,102		#[cfg(feature = "exp-preserve-order")] preserve_order: bool,103	) -> Self {104		Self {105			padding: Cow::Owned(padding),106			mtype: JsonFormatting::Std,107			newline,108			key_val_sep,109			#[cfg(feature = "exp-preserve-order")]110			preserve_order,111			#[cfg(feature = "exp-bigint")]112			preserve_bigints: false,113		}114	}115	// Same format as CLI manifestification116	pub fn cli(117		padding: usize,118		#[cfg(feature = "exp-preserve-order")] preserve_order: bool,119	) -> Self {120		if padding == 0 {121			return Self::minify(122				#[cfg(feature = "exp-preserve-order")]123				preserve_order,124			);125		}126		Self {127			padding: Cow::Owned(" ".repeat(padding)),128			mtype: JsonFormatting::Manifest,129			newline: "\n",130			key_val_sep: ": ",131			#[cfg(feature = "exp-preserve-order")]132			preserve_order,133			#[cfg(feature = "exp-bigint")]134			preserve_bigints: false,135		}136	}137}138impl Default for JsonFormat<'static> {139	fn default() -> Self {140		Self {141			padding: Cow::Borrowed("    "),142			mtype: JsonFormatting::Manifest,143			newline: "\n",144			key_val_sep: ": ",145			#[cfg(feature = "exp-preserve-order")]146			preserve_order: false,147			#[cfg(feature = "exp-bigint")]148			preserve_bigints: false,149		}150	}151}152153pub fn manifest_json_ex(val: &Val, options: &JsonFormat<'_>) -> Result<String> {154	let mut out = String::new();155	manifest_json_ex_buf(val, &mut out, &mut String::new(), options)?;156	Ok(out)157}158fn manifest_json_ex_buf(159	val: &Val,160	buf: &mut String,161	cur_padding: &mut String,162	options: &JsonFormat<'_>,163) -> Result<()> {164	let mtype = options.mtype;165	match val {166		Val::Bool(v) => {167			if *v {168				buf.push_str("true");169			} else {170				buf.push_str("false");171			}172		}173		Val::Null => buf.push_str("null"),174		Val::Str(s) => escape_string_json_buf(&s.clone().into_flat(), buf),175		Val::Num(n) => write!(buf, "{n}").unwrap(),176		#[cfg(feature = "exp-bigint")]177		Val::BigInt(n) => if options.preserve_bigints {178			write!(buf, "{n}").unwrap()179		} else {180			write!(buf, "{:?}", n.to_string()).unwrap()181		},182		Val::Arr(items) => {183			buf.push('[');184			if !items.is_empty() {185				if mtype != JsonFormatting::ToString && mtype != JsonFormatting::Minify {186					buf.push_str(options.newline);187				}188189				let old_len = cur_padding.len();190				cur_padding.push_str(&options.padding);191				for (i, item) in items.iter().enumerate() {192					if i != 0 {193						buf.push(',');194						if mtype == JsonFormatting::ToString {195							buf.push(' ');196						} else if mtype != JsonFormatting::Minify {197							buf.push_str(options.newline);198						}199					}200					buf.push_str(cur_padding);201					manifest_json_ex_buf(&item?, buf, cur_padding, options)?;202				}203				cur_padding.truncate(old_len);204205				if mtype != JsonFormatting::ToString && mtype != JsonFormatting::Minify {206					buf.push_str(options.newline);207					buf.push_str(cur_padding);208				}209			} else if mtype == JsonFormatting::Std {210				buf.push_str(options.newline);211				buf.push_str(options.newline);212				buf.push_str(cur_padding);213			} else if mtype == JsonFormatting::ToString || mtype == JsonFormatting::Manifest {214				buf.push(' ');215			}216			buf.push(']');217		}218		Val::Obj(obj) => {219			obj.run_assertions()?;220			buf.push('{');221			let fields = obj.fields(222				#[cfg(feature = "exp-preserve-order")]223				options.preserve_order,224			);225			if !fields.is_empty() {226				if mtype != JsonFormatting::ToString && mtype != JsonFormatting::Minify {227					buf.push_str(options.newline);228				}229230				let old_len = cur_padding.len();231				cur_padding.push_str(&options.padding);232				for (i, field) in fields.into_iter().enumerate() {233					if i != 0 {234						buf.push(',');235						if mtype == JsonFormatting::ToString {236							buf.push(' ');237						} else if mtype != JsonFormatting::Minify {238							buf.push_str(options.newline);239						}240					}241					buf.push_str(cur_padding);242					escape_string_json_buf(&field, buf);243					buf.push_str(options.key_val_sep);244					State::push_description(245						|| format!("field <{}> manifestification", field.clone()),246						|| {247							let value = obj.get(field.clone())?.unwrap();248							manifest_json_ex_buf(&value, buf, cur_padding, options)?;249							Ok(())250						},251					)?;252				}253				cur_padding.truncate(old_len);254255				if mtype != JsonFormatting::ToString && mtype != JsonFormatting::Minify {256					buf.push_str(options.newline);257					buf.push_str(cur_padding);258				}259			} else if mtype == JsonFormatting::Std {260				buf.push_str(options.newline);261				buf.push_str(options.newline);262				buf.push_str(cur_padding);263			} else if mtype == JsonFormatting::ToString || mtype == JsonFormatting::Manifest {264				buf.push(' ');265			}266			buf.push('}');267		}268		Val::Func(_) => bail!("tried to manifest function"),269	};270	Ok(())271}272273impl ManifestFormat for JsonFormat<'_> {274	fn manifest_buf(&self, val: Val, buf: &mut String) -> Result<()> {275		manifest_json_ex_buf(&val, buf, &mut String::new(), self)276	}277}278279pub struct ToStringFormat;280impl ManifestFormat for ToStringFormat {281	fn manifest_buf(&self, val: Val, out: &mut String) -> Result<()> {282		JsonFormat::std_to_string().manifest_buf(val, out)283	}284	fn file_trailing_newline(&self) -> bool {285		false286	}287}288pub struct StringFormat;289impl ManifestFormat for StringFormat {290	fn manifest_buf(&self, val: Val, out: &mut String) -> Result<()> {291		let Val::Str(s) = val else {292			bail!(293				"output should be string for string manifest format, got {}",294				val.value_type()295			)296		};297		write!(out, "{s}").unwrap();298		Ok(())299	}300	fn file_trailing_newline(&self) -> bool {301		false302	}303}304305pub struct YamlStreamFormat<I>(pub I);306impl<I: ManifestFormat> ManifestFormat for YamlStreamFormat<I> {307	fn manifest_buf(&self, val: Val, out: &mut String) -> Result<()> {308		let Val::Arr(arr) = val else {309			bail!(310				"output should be array for yaml stream format, got {}",311				val.value_type()312			)313		};314		if !arr.is_empty() {315			for v in arr.iter() {316				let v = v?;317				out.push_str("---\n");318				self.0.manifest_buf(v, out)?;319				out.push('\n');320			}321			out.push_str("...");322		}323		Ok(())324	}325}326327pub fn escape_string_json(s: &str) -> String {328	let mut buf = String::new();329	escape_string_json_buf(s, &mut buf);330	buf331}332333// Json string encoding was borrowed from https://github.com/serde-rs/json334335const BB: u8 = b'b'; // \x08336const TT: u8 = b't'; // \x09337const NN: u8 = b'n'; // \x0A338const FF: u8 = b'f'; // \x0C339const RR: u8 = b'r'; // \x0D340const QU: u8 = b'"'; // \x22341const BS: u8 = b'\\'; // \x5C342const UU: u8 = b'u'; // \x00...\x1F except the ones above343const __: u8 = 0;344345// Lookup table of escape sequences. A value of b'x' at index i means that byte346// i is escaped as "\x" in JSON. A value of 0 means that byte i is not escaped.347static ESCAPE: [u8; 256] = [348	//   1   2   3   4   5   6   7   8   9   A   B   C   D   E   F349	UU, UU, UU, UU, UU, UU, UU, UU, BB, TT, NN, UU, FF, RR, UU, UU, // 0350	UU, UU, UU, UU, UU, UU, UU, UU, UU, UU, UU, UU, UU, UU, UU, UU, // 1351	__, __, QU, __, __, __, __, __, __, __, __, __, __, __, __, __, // 2352	__, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, // 3353	__, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, // 4354	__, __, __, __, __, __, __, __, __, __, __, __, BS, __, __, __, // 5355	__, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, // 6356	__, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, // 7357	__, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, // 8358	__, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, // 9359	__, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, // A360	__, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, // B361	__, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, // C362	__, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, // D363	__, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, // E364	__, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, // F365];366367pub fn escape_string_json_buf(value: &str, buf: &mut String) {368	// Safety: we only write correct utf-8 in this function369	let buf: &mut Vec<u8> = unsafe { &mut *(buf as *mut String).cast::<Vec<u8>>() };370	let bytes = value.as_bytes();371372	// Perfect for ascii strings, removes any reallocations373	buf.reserve(value.len() + 2);374375	buf.push(b'"');376377	let mut start = 0;378379	for (i, &byte) in bytes.iter().enumerate() {380		let escape = ESCAPE[byte as usize];381		if escape == __ {382			continue;383		}384385		if start < i {386			buf.extend_from_slice(&bytes[start..i]);387		}388		start = i + 1;389390		match escape {391			self::BB | self::TT | self::NN | self::FF | self::RR | self::QU | self::BS => {392				buf.extend_from_slice(&[b'\\', escape]);393			}394			self::UU => {395				static HEX_DIGITS: [u8; 16] = *b"0123456789abcdef";396				let bytes = &[397					b'\\',398					b'u',399					b'0',400					b'0',401					HEX_DIGITS[(byte >> 4) as usize],402					HEX_DIGITS[(byte & 0xF) as usize],403				];404				buf.extend_from_slice(bytes);405			}406			_ => unreachable!(),407		}408	}409410	if start == bytes.len() {411		buf.push(b'"');412		return;413	}414415	buf.extend_from_slice(&bytes[start..]);416	buf.push(b'"');417}
after · crates/jrsonnet-evaluator/src/manifest.rs
1use std::{borrow::Cow, fmt::Write};23use crate::{bail, Result, State, Val};45pub trait ManifestFormat {6	fn manifest_buf(&self, val: Val, buf: &mut String) -> Result<()>;7	fn manifest(&self, val: Val) -> Result<String> {8		let mut out = String::new();9		self.manifest_buf(val, &mut out)?;10		Ok(out)11	}12	/// When outputing to file, is it safe to append a trailing newline (I.e newline won't change13	/// the meaning).14	///15	/// Default implementation returns `true`16	fn file_trailing_newline(&self) -> bool {17		true18	}19}20impl<T> ManifestFormat for Box<T>21where22	T: ManifestFormat + ?Sized,23{24	fn manifest_buf(&self, val: Val, buf: &mut String) -> Result<()> {25		let inner = &**self;26		inner.manifest_buf(val, buf)27	}28	fn file_trailing_newline(&self) -> bool {29		let inner = &**self;30		inner.file_trailing_newline()31	}32}33impl<T> ManifestFormat for &'_ T34where35	T: ManifestFormat + ?Sized,36{37	fn manifest_buf(&self, val: Val, buf: &mut String) -> Result<()> {38		let inner = &**self;39		inner.manifest_buf(val, buf)40	}41	fn file_trailing_newline(&self) -> bool {42		let inner = &**self;43		inner.file_trailing_newline()44	}45}4647#[derive(PartialEq, Eq, Clone, Copy)]48enum JsonFormatting {49	// Applied in manifestification50	Manifest,51	/// Used for std.manifestJson52	/// Empty array/objects extends to "[\n\n]" instead of "[ ]" as in manifest53	Std,54	/// No line breaks, used in `obj+''`55	ToString,56	/// Minified json57	Minify,58}5960pub struct JsonFormat<'s> {61	padding: Cow<'s, str>,62	mtype: JsonFormatting,63	newline: &'s str,64	key_val_sep: &'s str,65	#[cfg(feature = "exp-preserve-order")]66	preserve_order: bool,67	#[cfg(feature = "exp-bigint")]68	preserve_bigints: bool,69}7071impl<'s> JsonFormat<'s> {72	// Minifying format73	pub fn minify(#[cfg(feature = "exp-preserve-order")] preserve_order: bool) -> Self {74		Self {75			padding: Cow::Borrowed(""),76			mtype: JsonFormatting::Minify,77			newline: "\n",78			key_val_sep: ":",79			#[cfg(feature = "exp-preserve-order")]80			preserve_order,81			#[cfg(feature = "exp-bigint")]82			preserve_bigints: false,83		}84	}85	// Same format as std.toString86	pub fn std_to_string() -> Self {87		Self {88			padding: Cow::Borrowed(""),89			mtype: JsonFormatting::ToString,90			newline: "\n",91			key_val_sep: ": ",92			#[cfg(feature = "exp-preserve-order")]93			preserve_order: false,94			#[cfg(feature = "exp-bigint")]95			preserve_bigints: false,96		}97	}98	pub fn std_to_json(99		padding: String,100		newline: &'s str,101		key_val_sep: &'s str,102		#[cfg(feature = "exp-preserve-order")] preserve_order: bool,103	) -> Self {104		Self {105			padding: Cow::Owned(padding),106			mtype: JsonFormatting::Std,107			newline,108			key_val_sep,109			#[cfg(feature = "exp-preserve-order")]110			preserve_order,111			#[cfg(feature = "exp-bigint")]112			preserve_bigints: false,113		}114	}115	// Same format as CLI manifestification116	pub fn cli(117		padding: usize,118		#[cfg(feature = "exp-preserve-order")] preserve_order: bool,119	) -> Self {120		if padding == 0 {121			return Self::minify(122				#[cfg(feature = "exp-preserve-order")]123				preserve_order,124			);125		}126		Self {127			padding: Cow::Owned(" ".repeat(padding)),128			mtype: JsonFormatting::Manifest,129			newline: "\n",130			key_val_sep: ": ",131			#[cfg(feature = "exp-preserve-order")]132			preserve_order,133			#[cfg(feature = "exp-bigint")]134			preserve_bigints: false,135		}136	}137}138impl Default for JsonFormat<'static> {139	fn default() -> Self {140		Self {141			padding: Cow::Borrowed("    "),142			mtype: JsonFormatting::Manifest,143			newline: "\n",144			key_val_sep: ": ",145			#[cfg(feature = "exp-preserve-order")]146			preserve_order: false,147			#[cfg(feature = "exp-bigint")]148			preserve_bigints: false,149		}150	}151}152153pub fn manifest_json_ex(val: &Val, options: &JsonFormat<'_>) -> Result<String> {154	let mut out = String::new();155	manifest_json_ex_buf(val, &mut out, &mut String::new(), options)?;156	Ok(out)157}158fn manifest_json_ex_buf(159	val: &Val,160	buf: &mut String,161	cur_padding: &mut String,162	options: &JsonFormat<'_>,163) -> Result<()> {164	let mtype = options.mtype;165	match val {166		Val::Bool(v) => {167			if *v {168				buf.push_str("true");169			} else {170				buf.push_str("false");171			}172		}173		Val::Null => buf.push_str("null"),174		Val::Str(s) => escape_string_json_buf(&s.clone().into_flat(), buf),175		Val::Num(n) => write!(buf, "{n}").unwrap(),176		#[cfg(feature = "exp-bigint")]177		Val::BigInt(n) => {178			if options.preserve_bigints {179				write!(buf, "{n}").unwrap()180			} else {181				write!(buf, "{:?}", n.to_string()).unwrap()182			}183		}184		Val::Arr(items) => {185			buf.push('[');186			if !items.is_empty() {187				if mtype != JsonFormatting::ToString && mtype != JsonFormatting::Minify {188					buf.push_str(options.newline);189				}190191				let old_len = cur_padding.len();192				cur_padding.push_str(&options.padding);193				for (i, item) in items.iter().enumerate() {194					if i != 0 {195						buf.push(',');196						if mtype == JsonFormatting::ToString {197							buf.push(' ');198						} else if mtype != JsonFormatting::Minify {199							buf.push_str(options.newline);200						}201					}202					buf.push_str(cur_padding);203					manifest_json_ex_buf(&item?, buf, cur_padding, options)?;204				}205				cur_padding.truncate(old_len);206207				if mtype != JsonFormatting::ToString && mtype != JsonFormatting::Minify {208					buf.push_str(options.newline);209					buf.push_str(cur_padding);210				}211			} else if mtype == JsonFormatting::Std {212				buf.push_str(options.newline);213				buf.push_str(options.newline);214				buf.push_str(cur_padding);215			} else if mtype == JsonFormatting::ToString || mtype == JsonFormatting::Manifest {216				buf.push(' ');217			}218			buf.push(']');219		}220		Val::Obj(obj) => {221			obj.run_assertions()?;222			buf.push('{');223			let fields = obj.fields(224				#[cfg(feature = "exp-preserve-order")]225				options.preserve_order,226			);227			if !fields.is_empty() {228				if mtype != JsonFormatting::ToString && mtype != JsonFormatting::Minify {229					buf.push_str(options.newline);230				}231232				let old_len = cur_padding.len();233				cur_padding.push_str(&options.padding);234				for (i, field) in fields.into_iter().enumerate() {235					if i != 0 {236						buf.push(',');237						if mtype == JsonFormatting::ToString {238							buf.push(' ');239						} else if mtype != JsonFormatting::Minify {240							buf.push_str(options.newline);241						}242					}243					buf.push_str(cur_padding);244					escape_string_json_buf(&field, buf);245					buf.push_str(options.key_val_sep);246					State::push_description(247						|| format!("field <{}> manifestification", field.clone()),248						|| {249							let value = obj.get(field.clone())?.unwrap();250							manifest_json_ex_buf(&value, buf, cur_padding, options)?;251							Ok(())252						},253					)?;254				}255				cur_padding.truncate(old_len);256257				if mtype != JsonFormatting::ToString && mtype != JsonFormatting::Minify {258					buf.push_str(options.newline);259					buf.push_str(cur_padding);260				}261			} else if mtype == JsonFormatting::Std {262				buf.push_str(options.newline);263				buf.push_str(options.newline);264				buf.push_str(cur_padding);265			} else if mtype == JsonFormatting::ToString || mtype == JsonFormatting::Manifest {266				buf.push(' ');267			}268			buf.push('}');269		}270		Val::Func(_) => bail!("tried to manifest function"),271	};272	Ok(())273}274275impl ManifestFormat for JsonFormat<'_> {276	fn manifest_buf(&self, val: Val, buf: &mut String) -> Result<()> {277		manifest_json_ex_buf(&val, buf, &mut String::new(), self)278	}279}280281pub struct ToStringFormat;282impl ManifestFormat for ToStringFormat {283	fn manifest_buf(&self, val: Val, out: &mut String) -> Result<()> {284		JsonFormat::std_to_string().manifest_buf(val, out)285	}286	fn file_trailing_newline(&self) -> bool {287		false288	}289}290pub struct StringFormat;291impl ManifestFormat for StringFormat {292	fn manifest_buf(&self, val: Val, out: &mut String) -> Result<()> {293		let Val::Str(s) = val else {294			bail!(295				"output should be string for string manifest format, got {}",296				val.value_type()297			)298		};299		write!(out, "{s}").unwrap();300		Ok(())301	}302	fn file_trailing_newline(&self) -> bool {303		false304	}305}306307pub struct YamlStreamFormat<I>(pub I);308impl<I: ManifestFormat> ManifestFormat for YamlStreamFormat<I> {309	fn manifest_buf(&self, val: Val, out: &mut String) -> Result<()> {310		let Val::Arr(arr) = val else {311			bail!(312				"output should be array for yaml stream format, got {}",313				val.value_type()314			)315		};316		if !arr.is_empty() {317			for v in arr.iter() {318				let v = v?;319				out.push_str("---\n");320				self.0.manifest_buf(v, out)?;321				out.push('\n');322			}323			out.push_str("...");324		}325		Ok(())326	}327}328329pub fn escape_string_json(s: &str) -> String {330	let mut buf = String::new();331	escape_string_json_buf(s, &mut buf);332	buf333}334335// Json string encoding was borrowed from https://github.com/serde-rs/json336337const BB: u8 = b'b'; // \x08338const TT: u8 = b't'; // \x09339const NN: u8 = b'n'; // \x0A340const FF: u8 = b'f'; // \x0C341const RR: u8 = b'r'; // \x0D342const QU: u8 = b'"'; // \x22343const BS: u8 = b'\\'; // \x5C344const UU: u8 = b'u'; // \x00...\x1F except the ones above345const __: u8 = 0;346347// Lookup table of escape sequences. A value of b'x' at index i means that byte348// i is escaped as "\x" in JSON. A value of 0 means that byte i is not escaped.349static ESCAPE: [u8; 256] = [350	//   1   2   3   4   5   6   7   8   9   A   B   C   D   E   F351	UU, UU, UU, UU, UU, UU, UU, UU, BB, TT, NN, UU, FF, RR, UU, UU, // 0352	UU, UU, UU, UU, UU, UU, UU, UU, UU, UU, UU, UU, UU, UU, UU, UU, // 1353	__, __, QU, __, __, __, __, __, __, __, __, __, __, __, __, __, // 2354	__, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, // 3355	__, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, // 4356	__, __, __, __, __, __, __, __, __, __, __, __, BS, __, __, __, // 5357	__, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, // 6358	__, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, // 7359	__, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, // 8360	__, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, // 9361	__, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, // A362	__, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, // B363	__, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, // C364	__, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, // D365	__, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, // E366	__, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, // F367];368369pub fn escape_string_json_buf(value: &str, buf: &mut String) {370	// Safety: we only write correct utf-8 in this function371	let buf: &mut Vec<u8> = unsafe { &mut *(buf as *mut String).cast::<Vec<u8>>() };372	let bytes = value.as_bytes();373374	// Perfect for ascii strings, removes any reallocations375	buf.reserve(value.len() + 2);376377	buf.push(b'"');378379	let mut start = 0;380381	for (i, &byte) in bytes.iter().enumerate() {382		let escape = ESCAPE[byte as usize];383		if escape == __ {384			continue;385		}386387		if start < i {388			buf.extend_from_slice(&bytes[start..i]);389		}390		start = i + 1;391392		match escape {393			self::BB | self::TT | self::NN | self::FF | self::RR | self::QU | self::BS => {394				buf.extend_from_slice(&[b'\\', escape]);395			}396			self::UU => {397				static HEX_DIGITS: [u8; 16] = *b"0123456789abcdef";398				let bytes = &[399					b'\\',400					b'u',401					b'0',402					b'0',403					HEX_DIGITS[(byte >> 4) as usize],404					HEX_DIGITS[(byte & 0xF) as usize],405				];406				buf.extend_from_slice(bytes);407			}408			_ => unreachable!(),409		}410	}411412	if start == bytes.len() {413		buf.push(b'"');414		return;415	}416417	buf.extend_from_slice(&bytes[start..]);418	buf.push(b'"');419}
modifiedcrates/jrsonnet-evaluator/src/obj.rsdiffbeforeafterboth
--- a/crates/jrsonnet-evaluator/src/obj.rs
+++ b/crates/jrsonnet-evaluator/src/obj.rs
@@ -15,7 +15,7 @@
 	arr::{PickObjectKeyValues, PickObjectValues},
 	bail,
 	error::{suggest_object_fields, Error, ErrorKind::*},
-	function::CallLocation,
+	function::{CallLocation, FuncVal},
 	gc::{GcHashMap, GcHashSet, TraceBox},
 	operator::evaluate_add_op,
 	tb,
@@ -345,7 +345,7 @@
 	pub(crate) fn extend_with_raw_member(self, key: IStr, value: ObjMember) -> Self {
 		let mut out = ObjValueBuilder::with_capacity(1);
 		out.with_super(self);
-		let mut member = out.member(key);
+		let mut member = out.field(key);
 		if value.flags.add() {
 			member = member.add()
 		}
@@ -848,11 +848,27 @@
 		self.assertions.push(tb!(assertion));
 		self
 	}
-	pub fn member(&mut self, name: IStr) -> ObjMemberBuilder<ValueBuilder<'_>> {
+	pub fn field(&mut self, name: impl Into<IStr>) -> ObjMemberBuilder<ValueBuilder<'_>> {
 		let field_index = self.next_field_index;
 		self.next_field_index = self.next_field_index.next();
-		ObjMemberBuilder::new(ValueBuilder(self), name, field_index)
+		ObjMemberBuilder::new(ValueBuilder(self), name.into(), field_index)
 	}
+	/// Preset for common method definiton pattern:
+	/// Create a hidden field with the function value.
+	///
+	/// `.field(name).hide().value(Val::function(value))`
+	pub fn method(&mut self, name: impl Into<IStr>, value: impl Into<FuncVal>) -> &mut Self {
+		self.field(name).hide().value(Val::Func(value.into()));
+		self
+	}
+	pub fn try_method(
+		&mut self,
+		name: impl Into<IStr>,
+		value: impl Into<FuncVal>,
+	) -> Result<&mut Self> {
+		self.field(name).hide().try_value(Val::Func(value.into()))?;
+		Ok(self)
+	}
 
 	pub fn build(self) -> ObjValue {
 		if self.sup.is_none() && self.map.is_empty() && self.assertions.is_empty() {
@@ -930,18 +946,19 @@
 pub struct ValueBuilder<'v>(&'v mut ObjValueBuilder);
 impl ObjMemberBuilder<ValueBuilder<'_>> {
 	/// Inserts value, replacing if it is already defined
-	pub fn value_unchecked(self, value: Val) {
+	pub fn value(self, value: impl Into<Val>) {
 		let (receiver, name, member) =
-			self.build_member(MaybeUnbound::Bound(Thunk::evaluated(value)));
+			self.build_member(MaybeUnbound::Bound(Thunk::evaluated(value.into())));
 		let entry = receiver.0.map.entry(name);
 		entry.insert(member);
 	}
 
-	pub fn value(self, value: Val) -> Result<()> {
-		self.thunk(Thunk::evaluated(value))
+	/// Tries to insert value, returns an error if it was already defined
+	pub fn try_value(self, value: impl Into<Val>) -> Result<()> {
+		self.thunk(Thunk::evaluated(value.into()))
 	}
-	pub fn thunk(self, value: Thunk<Val>) -> Result<()> {
-		self.binding(MaybeUnbound::Bound(value))
+	pub fn thunk(self, value: impl Into<Thunk<Val>>) -> Result<()> {
+		self.binding(MaybeUnbound::Bound(value.into()))
 	}
 	pub fn bindable(self, bindable: impl Unbound<Bound = Val>) -> Result<()> {
 		self.binding(MaybeUnbound::Unbound(Cc::new(tb!(bindable))))
@@ -963,8 +980,8 @@
 
 pub struct ExtendBuilder<'v>(&'v mut ObjValue);
 impl ObjMemberBuilder<ExtendBuilder<'_>> {
-	pub fn value(self, value: Val) {
-		self.binding(MaybeUnbound::Bound(Thunk::evaluated(value)));
+	pub fn value(self, value: impl Into<Val>) {
+		self.binding(MaybeUnbound::Bound(Thunk::evaluated(value.into())));
 	}
 	pub fn bindable(self, bindable: TraceBox<dyn Unbound<Bound = Val>>) {
 		self.binding(MaybeUnbound::Unbound(Cc::new(bindable)));
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())))
 }