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
--- 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
before · crates/jrsonnet-macros/src/lib.rs
1use proc_macro2::TokenStream;2use quote::quote;3use syn::{4	parenthesized,5	parse::{Parse, ParseStream},6	parse_macro_input,7	punctuated::Punctuated,8	spanned::Spanned,9	token::{self, Comma},10	Attribute, DeriveInput, Error, FnArg, GenericArgument, Ident, ItemFn, LitStr, Pat, Path,11	PathArguments, Result, ReturnType, Token, Type,12};1314fn parse_attr<A: Parse, I>(attrs: &[Attribute], ident: I) -> Result<Option<A>>15where16	Ident: PartialEq<I>,17{18	let attrs = attrs19		.iter()20		.filter(|a| a.path.is_ident(&ident))21		.collect::<Vec<_>>();22	if attrs.len() > 1 {23		return Err(Error::new(24			attrs[1].span(),25			"this attribute may be specified only once",26		));27	} else if attrs.is_empty() {28		return Ok(None);29	}30	let attr = attrs[0];31	let attr = attr.parse_args::<A>()?;3233	Ok(Some(attr))34}3536fn path_is(path: &Path, needed: &str) -> bool {37	path.leading_colon.is_none()38		&& !path.segments.is_empty()39		&& path.segments.iter().last().unwrap().ident == needed40}4142fn type_is_path<'ty>(ty: &'ty Type, needed: &str) -> Option<&'ty PathArguments> {43	match ty {44		Type::Path(path) if path.qself.is_none() && path_is(&path.path, needed) => {45			let args = &path.path.segments.iter().last().unwrap().arguments;46			Some(args)47		}48		_ => None,49	}50}5152fn extract_type_from_option(ty: &Type) -> Result<Option<&Type>> {53	let Some(args) = type_is_path(ty, "Option") else {54		return Ok(None);55	};56	// It should have only on angle-bracketed param ("<String>"):57	let PathArguments::AngleBracketed(params) = args else {58		return Err(Error::new(args.span(), "missing option generic"));59	};60	let generic_arg = params.args.iter().next().unwrap();61	// This argument must be a type:62	let GenericArgument::Type(ty) = generic_arg else {63		return Err(Error::new(64			generic_arg.span(),65			"option generic should be a type",66		));67	};68	Ok(Some(ty))69}7071struct Field {72	attrs: Vec<Attribute>,73	name: Ident,74	_colon: Token![:],75	ty: Type,76}77impl Parse for Field {78	fn parse(input: ParseStream) -> syn::Result<Self> {79		Ok(Self {80			attrs: input.call(Attribute::parse_outer)?,81			name: input.parse()?,82			_colon: input.parse()?,83			ty: input.parse()?,84		})85	}86}8788mod kw {89	syn::custom_keyword!(fields);90	syn::custom_keyword!(rename);91	syn::custom_keyword!(flatten);92	syn::custom_keyword!(add);93	syn::custom_keyword!(hide);94	syn::custom_keyword!(ok);95}9697struct EmptyAttr;98impl Parse for EmptyAttr {99	fn parse(_input: ParseStream) -> Result<Self> {100		Ok(Self)101	}102}103104struct BuiltinAttrs {105	fields: Vec<Field>,106}107impl Parse for BuiltinAttrs {108	fn parse(input: ParseStream) -> syn::Result<Self> {109		if input.is_empty() {110			return Ok(Self { fields: Vec::new() });111		}112		input.parse::<kw::fields>()?;113		let fields;114		parenthesized!(fields in input);115		let p = Punctuated::<Field, Comma>::parse_terminated(&fields)?;116		Ok(Self {117			fields: p.into_iter().collect(),118		})119	}120}121122enum ArgInfo {123	Normal {124		ty: Box<Type>,125		is_option: bool,126		name: Option<String>,127		cfg_attrs: Vec<Attribute>,128	},129	Lazy {130		is_option: bool,131		name: Option<String>,132	},133	Context,134	Location,135	This,136}137138impl ArgInfo {139	fn parse(name: &str, arg: &FnArg) -> Result<Self> {140		let FnArg::Typed(arg) = arg else {141			unreachable!()142		};143		let ident = match &arg.pat as &Pat {144			Pat::Ident(i) => Some(i.ident.clone()),145			_ => None,146		};147		let ty = &arg.ty;148		if type_is_path(ty, "Context").is_some() {149			return Ok(Self::Context);150		} else if type_is_path(ty, "CallLocation").is_some() {151			return Ok(Self::Location);152		} else if type_is_path(ty, "Thunk").is_some() {153			return Ok(Self::Lazy {154				is_option: false,155				name: ident.map(|v| v.to_string()),156			});157		}158159		match ty as &Type {160			Type::Reference(r) if type_is_path(&r.elem, name).is_some() => return Ok(Self::This),161			_ => {}162		}163164		let (is_option, ty) = if let Some(ty) = extract_type_from_option(ty)? {165			if type_is_path(ty, "Thunk").is_some() {166				return Ok(Self::Lazy {167					is_option: true,168					name: ident.map(|v| v.to_string()),169				});170			}171172			(true, Box::new(ty.clone()))173		} else {174			(false, ty.clone())175		};176177		let cfg_attrs = arg178			.attrs179			.iter()180			.filter(|a| a.path.is_ident("cfg"))181			.cloned()182			.collect();183184		Ok(Self::Normal {185			ty,186			is_option,187			name: ident.map(|v| v.to_string()),188			cfg_attrs,189		})190	}191}192193#[proc_macro_attribute]194pub fn builtin(195	attr: proc_macro::TokenStream,196	item: proc_macro::TokenStream,197) -> proc_macro::TokenStream {198	let attr = parse_macro_input!(attr as BuiltinAttrs);199	let item_fn = item.clone();200	let item_fn: ItemFn = parse_macro_input!(item_fn);201202	match builtin_inner(attr, item_fn, item.into()) {203		Ok(v) => v.into(),204		Err(e) => e.into_compile_error().into(),205	}206}207208fn builtin_inner(209	attr: BuiltinAttrs,210	fun: ItemFn,211	item: proc_macro2::TokenStream,212) -> syn::Result<TokenStream> {213	let ReturnType::Type(_, result) = &fun.sig.output else {214		return Err(Error::new(215			fun.sig.span(),216			"builtin should return something",217		));218	};219220	let name = fun.sig.ident.to_string();221	let args = fun222		.sig223		.inputs224		.iter()225		.map(|arg| ArgInfo::parse(&name, arg))226		.collect::<Result<Vec<_>>>()?;227228	let params_desc = args.iter().flat_map(|a| match a {229		ArgInfo::Normal {230			is_option,231			name,232			cfg_attrs,233			..234		} => {235			let name = name236				.as_ref()237				.map(|n| quote! {ParamName::new_static(#n)})238				.unwrap_or_else(|| quote! {None});239			Some(quote! {240				#(#cfg_attrs)*241				BuiltinParam::new(#name, #is_option),242			})243		}244		ArgInfo::Lazy { is_option, name } => {245			let name = name246				.as_ref()247				.map(|n| quote! {ParamName::new_static(#n)})248				.unwrap_or_else(|| quote! {None});249			Some(quote! {250				BuiltinParam::new(#name, #is_option),251			})252		}253		ArgInfo::Context => None,254		ArgInfo::Location => None,255		ArgInfo::This => None,256	});257258	let mut id = 0usize;259	let pass = args260		.iter()261		.map(|a| match a {262			ArgInfo::Normal { .. } | ArgInfo::Lazy { .. } => {263				let cid = id;264				id += 1;265				(quote! {#cid}, a)266			}267			ArgInfo::Context | ArgInfo::Location | ArgInfo::This => {268				(quote! {compile_error!("should not use id")}, a)269			}270		})271		.map(|(id, a)| match a {272			ArgInfo::Normal {273				ty,274				is_option,275				name,276				cfg_attrs,277			} => {278				let name = name.as_ref().map(|v| v.as_str()).unwrap_or("<unnamed>");279				let eval = quote! {jrsonnet_evaluator::State::push_description(280					|| format!("argument <{}> evaluation", #name),281					|| <#ty>::from_untyped(value.evaluate()?),282				)?};283				let value = if *is_option {284					quote! {if let Some(value) = &parsed[#id] {285						Some(#eval)286					} else {287						None288					},}289				} else {290					quote! {{291						let value = parsed[#id].as_ref().expect("args shape is checked");292						#eval293					},}294				};295				quote! {296					#(#cfg_attrs)*297					#value298				}299			}300			ArgInfo::Lazy { is_option, .. } => {301				if *is_option {302					quote! {if let Some(value) = &parsed[#id] {303						Some(value.clone())304					} else {305						None306					}}307				} else {308					quote! {309						parsed[#id].as_ref().expect("args shape is correct").clone(),310					}311				}312			}313			ArgInfo::Context => quote! {ctx.clone(),},314			ArgInfo::Location => quote! {location,},315			ArgInfo::This => quote! {self,},316		});317318	let fields = attr.fields.iter().map(|field| {319		let attrs = &field.attrs;320		let name = &field.name;321		let ty = &field.ty;322		quote! {323			#(#attrs)*324			pub #name: #ty,325		}326	});327328	let name = &fun.sig.ident;329	let vis = &fun.vis;330	let static_ext = if attr.fields.is_empty() {331		quote! {332			impl #name {333				pub const INST: &'static dyn StaticBuiltin = &#name {};334			}335			impl StaticBuiltin for #name {}336		}337	} else {338		quote! {}339	};340	let static_derive_copy = if attr.fields.is_empty() {341		quote! {, Copy}342	} else {343		quote! {}344	};345346	Ok(quote! {347		#item348349		#[doc(hidden)]350		#[allow(non_camel_case_types)]351		#[derive(Clone, jrsonnet_gcmodule::Trace #static_derive_copy)]352		#vis struct #name {353			#(#fields)*354		}355		const _: () = {356			use ::jrsonnet_evaluator::{357				State, Val,358				function::{builtin::{Builtin, StaticBuiltin, BuiltinParam, ParamName}, CallLocation, ArgsLike, parse::parse_builtin_call},359				Result, Context, typed::Typed,360				parser::ExprLocation,361			};362			const PARAMS: &'static [BuiltinParam] = &[363				#(#params_desc)*364			];365366			#static_ext367			impl Builtin for #name368			where369				Self: 'static370			{371				fn name(&self) -> &str {372					stringify!(#name)373				}374				fn params(&self) -> &[BuiltinParam] {375					PARAMS376				}377				fn call(&self, ctx: Context, location: CallLocation, args: &dyn ArgsLike) -> Result<Val> {378					let parsed = parse_builtin_call(ctx.clone(), &PARAMS, args, false)?;379380					let result: #result = #name(#(#pass)*);381					<_ as Typed>::into_result(result)382				}383				fn as_any(&self) -> &dyn ::std::any::Any {384					self385				}386			}387		};388	})389}390391#[derive(Default)]392struct TypedAttr {393	rename: Option<String>,394	flatten: bool,395	/// flatten(ok) strategy for flattened optionals396	/// field would be None in case of any parsing error (as in serde)397	flatten_ok: bool,398	// Should it be `field+:` instead of `field:`399	add: bool,400	// Should it be `field::` instead of `field:`401	hide: bool,402}403impl Parse for TypedAttr {404	fn parse(input: ParseStream) -> syn::Result<Self> {405		let mut out = Self::default();406		loop {407			let lookahead = input.lookahead1();408			if lookahead.peek(kw::rename) {409				input.parse::<kw::rename>()?;410				input.parse::<Token![=]>()?;411				let name = input.parse::<LitStr>()?;412				if out.rename.is_some() {413					return Err(Error::new(414						name.span(),415						"rename attribute may only be specified once",416					));417				}418				out.rename = Some(name.value());419			} else if lookahead.peek(kw::flatten) {420				input.parse::<kw::flatten>()?;421				out.flatten = true;422				if input.peek(token::Paren) {423					let content;424					parenthesized!(content in input);425					let lookahead = content.lookahead1();426					if lookahead.peek(kw::ok) {427						content.parse::<kw::ok>()?;428						out.flatten_ok = true;429					} else {430						return Err(lookahead.error());431					}432				}433			} else if lookahead.peek(kw::add) {434				input.parse::<kw::add>()?;435				out.add = true;436			} else if lookahead.peek(kw::hide) {437				input.parse::<kw::hide>()?;438				out.hide = true;439			} else if input.is_empty() {440				break;441			} else {442				return Err(lookahead.error());443			}444			if input.peek(Token![,]) {445				input.parse::<Token![,]>()?;446			} else {447				break;448			}449		}450		Ok(out)451	}452}453454struct TypedField {455	attr: TypedAttr,456	ident: Ident,457	ty: Type,458	is_option: bool,459}460impl TypedField {461	fn parse(field: &syn::Field) -> Result<Self> {462		let attr = parse_attr::<TypedAttr, _>(&field.attrs, "typed")?.unwrap_or_default();463		let Some(ident) = field.ident.clone() else {464			return Err(Error::new(465				field.span(),466				"this field should appear in output object, but it has no visible name",467			));468		};469		let (is_option, ty) = if let Some(ty) = extract_type_from_option(&field.ty)? {470			(true, ty.clone())471		} else {472			(false, field.ty.clone())473		};474		if is_option && attr.flatten {475			if !attr.flatten_ok {476				return Err(Error::new(477					field.span(),478					"strategy should be set when flattening Option",479				));480			}481		} else if attr.flatten_ok {482			return Err(Error::new(483				field.span(),484				"flatten(ok) is only useable on optional fields",485			));486		}487488		Ok(Self {489			attr,490			ident,491			ty,492			is_option,493		})494	}495	/// None if this field is flattened in jsonnet output496	fn name(&self) -> Option<String> {497		if self.attr.flatten {498			return None;499		}500		Some(501			self.attr502				.rename503				.clone()504				.unwrap_or_else(|| self.ident.to_string()),505		)506	}507508	fn expand_field(&self) -> Option<TokenStream> {509		if self.is_option {510			return None;511		}512		let name = self.name()?;513		let ty = &self.ty;514		Some(quote! {515			(#name, <#ty as Typed>::TYPE)516		})517	}518	fn expand_parse(&self) -> TokenStream {519		let ident = &self.ident;520		let ty = &self.ty;521		if self.attr.flatten {522			// optional flatten is handled in same way as serde523			return if self.is_option {524				quote! {525					#ident: <#ty as TypedObj>::parse(&obj).ok(),526				}527			} else {528				quote! {529					#ident: <#ty as TypedObj>::parse(&obj)?,530				}531			};532		};533534		let name = self.name().unwrap();535		let value = if self.is_option {536			quote! {537				if let Some(value) = obj.get(#name.into())? {538					Some(<#ty as Typed>::from_untyped(value)?)539				} else {540					None541				}542			}543		} else {544			quote! {545				<#ty as Typed>::from_untyped(obj.get(#name.into())?.ok_or_else(|| ErrorKind::NoSuchField(#name.into(), vec![]))?)?546			}547		};548549		quote! {550			#ident: #value,551		}552	}553	fn expand_serialize(&self) -> Result<TokenStream> {554		let ident = &self.ident;555		let ty = &self.ty;556		Ok(if let Some(name) = self.name() {557			let hide = if self.attr.hide {558				quote! {.hide()}559			} else {560				quote! {}561			};562			let add = if self.attr.add {563				quote! {.add()}564			} else {565				quote! {}566			};567			if self.is_option {568				quote! {569					if let Some(value) = self.#ident {570						out.member(#name.into())571							#hide572							#add573							.value(<#ty as Typed>::into_untyped(value)?)?;574					}575				}576			} else {577				quote! {578					out.member(#name.into())579						#hide580						#add581						.value(<#ty as Typed>::into_untyped(self.#ident)?)?;582				}583			}584		} else if self.is_option {585			quote! {586				if let Some(value) = self.#ident {587					<#ty as TypedObj>::serialize(value, out)?;588				}589			}590		} else {591			quote! {592				<#ty as TypedObj>::serialize(self.#ident, out)?;593			}594		})595	}596}597598#[proc_macro_derive(Typed, attributes(typed))]599pub fn derive_typed(item: proc_macro::TokenStream) -> proc_macro::TokenStream {600	let input = parse_macro_input!(item as DeriveInput);601602	match derive_typed_inner(input) {603		Ok(v) => v.into(),604		Err(e) => e.to_compile_error().into(),605	}606}607608fn derive_typed_inner(input: DeriveInput) -> Result<TokenStream> {609	let syn::Data::Struct(data) = &input.data else {610		return Err(Error::new(input.span(), "only structs supported"));611	};612613	let ident = &input.ident;614	let fields = data615		.fields616		.iter()617		.map(TypedField::parse)618		.collect::<Result<Vec<_>>>()?;619620	let (impl_generics, ty_generics, where_clause) = input.generics.split_for_impl();621622	let typed = {623		let fields = fields624			.iter()625			.flat_map(TypedField::expand_field)626			.collect::<Vec<_>>();627		quote! {628			impl #impl_generics Typed for #ident #ty_generics #where_clause {629				const TYPE: &'static ComplexValType = &ComplexValType::ObjectRef(&[630					#(#fields,)*631				]);632633				fn from_untyped(value: Val) -> JrResult<Self> {634					let obj = value.as_obj().expect("shape is correct");635					Self::parse(&obj)636				}637638				fn into_untyped(value: Self) -> JrResult<Val> {639					let mut out = ObjValueBuilder::new();640					value.serialize(&mut out)?;641					Ok(Val::Obj(out.build()))642				}643644			}645		}646	};647648	let fields_parse = fields.iter().map(TypedField::expand_parse);649	let fields_serialize = fields650		.iter()651		.map(TypedField::expand_serialize)652		.collect::<Result<Vec<_>>>()?;653654	Ok(quote! {655		const _: () = {656			use ::jrsonnet_evaluator::{657				typed::{ComplexValType, Typed, TypedObj, CheckType},658				Val, State,659				error::{ErrorKind, Result as JrResult},660				ObjValueBuilder, ObjValue,661			};662663			#typed664665			impl #impl_generics TypedObj for #ident #ty_generics #where_clause {666				fn serialize(self, out: &mut ObjValueBuilder) -> JrResult<()> {667					#(#fields_serialize)*668669					Ok(())670				}671				fn parse(obj: &ObjValue) -> JrResult<Self> {672					Ok(Self {673						#(#fields_parse)*674					})675				}676			}677		};678	})679}
after · crates/jrsonnet-macros/src/lib.rs
1use proc_macro2::TokenStream;2use quote::quote;3use syn::{4	parenthesized,5	parse::{Parse, ParseStream},6	parse_macro_input,7	punctuated::Punctuated,8	spanned::Spanned,9	token::{self, Comma},10	Attribute, DeriveInput, Error, FnArg, GenericArgument, Ident, ItemFn, LitStr, Pat, Path,11	PathArguments, Result, ReturnType, Token, Type,12};1314fn parse_attr<A: Parse, I>(attrs: &[Attribute], ident: I) -> Result<Option<A>>15where16	Ident: PartialEq<I>,17{18	let attrs = attrs19		.iter()20		.filter(|a| a.path.is_ident(&ident))21		.collect::<Vec<_>>();22	if attrs.len() > 1 {23		return Err(Error::new(24			attrs[1].span(),25			"this attribute may be specified only once",26		));27	} else if attrs.is_empty() {28		return Ok(None);29	}30	let attr = attrs[0];31	let attr = attr.parse_args::<A>()?;3233	Ok(Some(attr))34}3536fn path_is(path: &Path, needed: &str) -> bool {37	path.leading_colon.is_none()38		&& !path.segments.is_empty()39		&& path.segments.iter().last().unwrap().ident == needed40}4142fn type_is_path<'ty>(ty: &'ty Type, needed: &str) -> Option<&'ty PathArguments> {43	match ty {44		Type::Path(path) if path.qself.is_none() && path_is(&path.path, needed) => {45			let args = &path.path.segments.iter().last().unwrap().arguments;46			Some(args)47		}48		_ => None,49	}50}5152fn extract_type_from_option(ty: &Type) -> Result<Option<&Type>> {53	let Some(args) = type_is_path(ty, "Option") else {54		return Ok(None);55	};56	// It should have only on angle-bracketed param ("<String>"):57	let PathArguments::AngleBracketed(params) = args else {58		return Err(Error::new(args.span(), "missing option generic"));59	};60	let generic_arg = params.args.iter().next().unwrap();61	// This argument must be a type:62	let GenericArgument::Type(ty) = generic_arg else {63		return Err(Error::new(64			generic_arg.span(),65			"option generic should be a type",66		));67	};68	Ok(Some(ty))69}7071struct Field {72	attrs: Vec<Attribute>,73	name: Ident,74	_colon: Token![:],75	ty: Type,76}77impl Parse for Field {78	fn parse(input: ParseStream) -> syn::Result<Self> {79		Ok(Self {80			attrs: input.call(Attribute::parse_outer)?,81			name: input.parse()?,82			_colon: input.parse()?,83			ty: input.parse()?,84		})85	}86}8788mod kw {89	syn::custom_keyword!(fields);90	syn::custom_keyword!(rename);91	syn::custom_keyword!(flatten);92	syn::custom_keyword!(add);93	syn::custom_keyword!(hide);94	syn::custom_keyword!(ok);95}9697struct EmptyAttr;98impl Parse for EmptyAttr {99	fn parse(_input: ParseStream) -> Result<Self> {100		Ok(Self)101	}102}103104struct BuiltinAttrs {105	fields: Vec<Field>,106}107impl Parse for BuiltinAttrs {108	fn parse(input: ParseStream) -> syn::Result<Self> {109		if input.is_empty() {110			return Ok(Self { fields: Vec::new() });111		}112		input.parse::<kw::fields>()?;113		let fields;114		parenthesized!(fields in input);115		let p = Punctuated::<Field, Comma>::parse_terminated(&fields)?;116		Ok(Self {117			fields: p.into_iter().collect(),118		})119	}120}121122enum ArgInfo {123	Normal {124		ty: Box<Type>,125		is_option: bool,126		name: Option<String>,127		cfg_attrs: Vec<Attribute>,128	},129	Lazy {130		is_option: bool,131		name: Option<String>,132	},133	Context,134	Location,135	This,136}137138impl ArgInfo {139	fn parse(name: &str, arg: &FnArg) -> Result<Self> {140		let FnArg::Typed(arg) = arg else {141			unreachable!()142		};143		let ident = match &arg.pat as &Pat {144			Pat::Ident(i) => Some(i.ident.clone()),145			_ => None,146		};147		let ty = &arg.ty;148		if type_is_path(ty, "Context").is_some() {149			return Ok(Self::Context);150		} else if type_is_path(ty, "CallLocation").is_some() {151			return Ok(Self::Location);152		} else if type_is_path(ty, "Thunk").is_some() {153			return Ok(Self::Lazy {154				is_option: false,155				name: ident.map(|v| v.to_string()),156			});157		}158159		match ty as &Type {160			Type::Reference(r) if type_is_path(&r.elem, name).is_some() => return Ok(Self::This),161			_ => {}162		}163164		let (is_option, ty) = if let Some(ty) = extract_type_from_option(ty)? {165			if type_is_path(ty, "Thunk").is_some() {166				return Ok(Self::Lazy {167					is_option: true,168					name: ident.map(|v| v.to_string()),169				});170			}171172			(true, Box::new(ty.clone()))173		} else {174			(false, ty.clone())175		};176177		let cfg_attrs = arg178			.attrs179			.iter()180			.filter(|a| a.path.is_ident("cfg"))181			.cloned()182			.collect();183184		Ok(Self::Normal {185			ty,186			is_option,187			name: ident.map(|v| v.to_string()),188			cfg_attrs,189		})190	}191}192193#[proc_macro_attribute]194pub fn builtin(195	attr: proc_macro::TokenStream,196	item: proc_macro::TokenStream,197) -> proc_macro::TokenStream {198	let attr = parse_macro_input!(attr as BuiltinAttrs);199	let item_fn = item.clone();200	let item_fn: ItemFn = parse_macro_input!(item_fn);201202	match builtin_inner(attr, item_fn, item.into()) {203		Ok(v) => v.into(),204		Err(e) => e.into_compile_error().into(),205	}206}207208fn builtin_inner(209	attr: BuiltinAttrs,210	fun: ItemFn,211	item: proc_macro2::TokenStream,212) -> syn::Result<TokenStream> {213	let ReturnType::Type(_, result) = &fun.sig.output else {214		return Err(Error::new(215			fun.sig.span(),216			"builtin should return something",217		));218	};219220	let name = fun.sig.ident.to_string();221	let args = fun222		.sig223		.inputs224		.iter()225		.map(|arg| ArgInfo::parse(&name, arg))226		.collect::<Result<Vec<_>>>()?;227228	let params_desc = args.iter().flat_map(|a| match a {229		ArgInfo::Normal {230			is_option,231			name,232			cfg_attrs,233			..234		} => {235			let name = name236				.as_ref()237				.map(|n| quote! {ParamName::new_static(#n)})238				.unwrap_or_else(|| quote! {None});239			Some(quote! {240				#(#cfg_attrs)*241				BuiltinParam::new(#name, #is_option),242			})243		}244		ArgInfo::Lazy { is_option, name } => {245			let name = name246				.as_ref()247				.map(|n| quote! {ParamName::new_static(#n)})248				.unwrap_or_else(|| quote! {None});249			Some(quote! {250				BuiltinParam::new(#name, #is_option),251			})252		}253		ArgInfo::Context => None,254		ArgInfo::Location => None,255		ArgInfo::This => None,256	});257258	let mut id = 0usize;259	let pass = args260		.iter()261		.map(|a| match a {262			ArgInfo::Normal { .. } | ArgInfo::Lazy { .. } => {263				let cid = id;264				id += 1;265				(quote! {#cid}, a)266			}267			ArgInfo::Context | ArgInfo::Location | ArgInfo::This => {268				(quote! {compile_error!("should not use id")}, a)269			}270		})271		.map(|(id, a)| match a {272			ArgInfo::Normal {273				ty,274				is_option,275				name,276				cfg_attrs,277			} => {278				let name = name.as_ref().map(|v| v.as_str()).unwrap_or("<unnamed>");279				let eval = quote! {jrsonnet_evaluator::State::push_description(280					|| format!("argument <{}> evaluation", #name),281					|| <#ty>::from_untyped(value.evaluate()?),282				)?};283				let value = if *is_option {284					quote! {if let Some(value) = &parsed[#id] {285						Some(#eval)286					} else {287						None288					},}289				} else {290					quote! {{291						let value = parsed[#id].as_ref().expect("args shape is checked");292						#eval293					},}294				};295				quote! {296					#(#cfg_attrs)*297					#value298				}299			}300			ArgInfo::Lazy { is_option, .. } => {301				if *is_option {302					quote! {if let Some(value) = &parsed[#id] {303						Some(value.clone())304					} else {305						None306					}}307				} else {308					quote! {309						parsed[#id].as_ref().expect("args shape is correct").clone(),310					}311				}312			}313			ArgInfo::Context => quote! {ctx.clone(),},314			ArgInfo::Location => quote! {location,},315			ArgInfo::This => quote! {self,},316		});317318	let fields = attr.fields.iter().map(|field| {319		let attrs = &field.attrs;320		let name = &field.name;321		let ty = &field.ty;322		quote! {323			#(#attrs)*324			pub #name: #ty,325		}326	});327328	let name = &fun.sig.ident;329	let vis = &fun.vis;330	let static_ext = if attr.fields.is_empty() {331		quote! {332			impl #name {333				pub const INST: &'static dyn StaticBuiltin = &#name {};334			}335			impl StaticBuiltin for #name {}336		}337	} else {338		quote! {}339	};340	let static_derive_copy = if attr.fields.is_empty() {341		quote! {, Copy}342	} else {343		quote! {}344	};345346	Ok(quote! {347		#item348349		#[doc(hidden)]350		#[allow(non_camel_case_types)]351		#[derive(Clone, jrsonnet_gcmodule::Trace #static_derive_copy)]352		#vis struct #name {353			#(#fields)*354		}355		const _: () = {356			use ::jrsonnet_evaluator::{357				State, Val,358				function::{builtin::{Builtin, StaticBuiltin, BuiltinParam, ParamName}, CallLocation, ArgsLike, parse::parse_builtin_call},359				Result, Context, typed::Typed,360				parser::ExprLocation,361			};362			const PARAMS: &'static [BuiltinParam] = &[363				#(#params_desc)*364			];365366			#static_ext367			impl Builtin for #name368			where369				Self: 'static370			{371				fn name(&self) -> &str {372					stringify!(#name)373				}374				fn params(&self) -> &[BuiltinParam] {375					PARAMS376				}377				fn call(&self, ctx: Context, location: CallLocation, args: &dyn ArgsLike) -> Result<Val> {378					let parsed = parse_builtin_call(ctx.clone(), &PARAMS, args, false)?;379380					let result: #result = #name(#(#pass)*);381					<_ as Typed>::into_result(result)382				}383				fn as_any(&self) -> &dyn ::std::any::Any {384					self385				}386			}387		};388	})389}390391#[derive(Default)]392struct TypedAttr {393	rename: Option<String>,394	flatten: bool,395	/// flatten(ok) strategy for flattened optionals396	/// field would be None in case of any parsing error (as in serde)397	flatten_ok: bool,398	// Should it be `field+:` instead of `field:`399	add: bool,400	// Should it be `field::` instead of `field:`401	hide: bool,402}403impl Parse for TypedAttr {404	fn parse(input: ParseStream) -> syn::Result<Self> {405		let mut out = Self::default();406		loop {407			let lookahead = input.lookahead1();408			if lookahead.peek(kw::rename) {409				input.parse::<kw::rename>()?;410				input.parse::<Token![=]>()?;411				let name = input.parse::<LitStr>()?;412				if out.rename.is_some() {413					return Err(Error::new(414						name.span(),415						"rename attribute may only be specified once",416					));417				}418				out.rename = Some(name.value());419			} else if lookahead.peek(kw::flatten) {420				input.parse::<kw::flatten>()?;421				out.flatten = true;422				if input.peek(token::Paren) {423					let content;424					parenthesized!(content in input);425					let lookahead = content.lookahead1();426					if lookahead.peek(kw::ok) {427						content.parse::<kw::ok>()?;428						out.flatten_ok = true;429					} else {430						return Err(lookahead.error());431					}432				}433			} else if lookahead.peek(kw::add) {434				input.parse::<kw::add>()?;435				out.add = true;436			} else if lookahead.peek(kw::hide) {437				input.parse::<kw::hide>()?;438				out.hide = true;439			} else if input.is_empty() {440				break;441			} else {442				return Err(lookahead.error());443			}444			if input.peek(Token![,]) {445				input.parse::<Token![,]>()?;446			} else {447				break;448			}449		}450		Ok(out)451	}452}453454struct TypedField {455	attr: TypedAttr,456	ident: Ident,457	ty: Type,458	is_option: bool,459}460impl TypedField {461	fn parse(field: &syn::Field) -> Result<Self> {462		let attr = parse_attr::<TypedAttr, _>(&field.attrs, "typed")?.unwrap_or_default();463		let Some(ident) = field.ident.clone() else {464			return Err(Error::new(465				field.span(),466				"this field should appear in output object, but it has no visible name",467			));468		};469		let (is_option, ty) = if let Some(ty) = extract_type_from_option(&field.ty)? {470			(true, ty.clone())471		} else {472			(false, field.ty.clone())473		};474		if is_option && attr.flatten {475			if !attr.flatten_ok {476				return Err(Error::new(477					field.span(),478					"strategy should be set when flattening Option",479				));480			}481		} else if attr.flatten_ok {482			return Err(Error::new(483				field.span(),484				"flatten(ok) is only useable on optional fields",485			));486		}487488		Ok(Self {489			attr,490			ident,491			ty,492			is_option,493		})494	}495	/// None if this field is flattened in jsonnet output496	fn name(&self) -> Option<String> {497		if self.attr.flatten {498			return None;499		}500		Some(501			self.attr502				.rename503				.clone()504				.unwrap_or_else(|| self.ident.to_string()),505		)506	}507508	fn expand_field(&self) -> Option<TokenStream> {509		if self.is_option {510			return None;511		}512		let name = self.name()?;513		let ty = &self.ty;514		Some(quote! {515			(#name, <#ty as Typed>::TYPE)516		})517	}518	fn expand_parse(&self) -> TokenStream {519		let ident = &self.ident;520		let ty = &self.ty;521		if self.attr.flatten {522			// optional flatten is handled in same way as serde523			return if self.is_option {524				quote! {525					#ident: <#ty as TypedObj>::parse(&obj).ok(),526				}527			} else {528				quote! {529					#ident: <#ty as TypedObj>::parse(&obj)?,530				}531			};532		};533534		let name = self.name().unwrap();535		let value = if self.is_option {536			quote! {537				if let Some(value) = obj.get(#name.into())? {538					Some(<#ty as Typed>::from_untyped(value)?)539				} else {540					None541				}542			}543		} else {544			quote! {545				<#ty as Typed>::from_untyped(obj.get(#name.into())?.ok_or_else(|| ErrorKind::NoSuchField(#name.into(), vec![]))?)?546			}547		};548549		quote! {550			#ident: #value,551		}552	}553	fn expand_serialize(&self) -> Result<TokenStream> {554		let ident = &self.ident;555		let ty = &self.ty;556		Ok(if let Some(name) = self.name() {557			let hide = if self.attr.hide {558				quote! {.hide()}559			} else {560				quote! {}561			};562			let add = if self.attr.add {563				quote! {.add()}564			} else {565				quote! {}566			};567			if self.is_option {568				quote! {569					if let Some(value) = self.#ident {570						out.field(#name)571							#hide572							#add573							.try_value(<#ty as Typed>::into_untyped(value)?)?;574					}575				}576			} else {577				quote! {578					out.field(#name)579						#hide580						#add581						.try_value(<#ty as Typed>::into_untyped(self.#ident)?)?;582				}583			}584		} else if self.is_option {585			quote! {586				if let Some(value) = self.#ident {587					<#ty as TypedObj>::serialize(value, out)?;588				}589			}590		} else {591			quote! {592				<#ty as TypedObj>::serialize(self.#ident, out)?;593			}594		})595	}596}597598#[proc_macro_derive(Typed, attributes(typed))]599pub fn derive_typed(item: proc_macro::TokenStream) -> proc_macro::TokenStream {600	let input = parse_macro_input!(item as DeriveInput);601602	match derive_typed_inner(input) {603		Ok(v) => v.into(),604		Err(e) => e.to_compile_error().into(),605	}606}607608fn derive_typed_inner(input: DeriveInput) -> Result<TokenStream> {609	let syn::Data::Struct(data) = &input.data else {610		return Err(Error::new(input.span(), "only structs supported"));611	};612613	let ident = &input.ident;614	let fields = data615		.fields616		.iter()617		.map(TypedField::parse)618		.collect::<Result<Vec<_>>>()?;619620	let (impl_generics, ty_generics, where_clause) = input.generics.split_for_impl();621622	let typed = {623		let fields = fields624			.iter()625			.flat_map(TypedField::expand_field)626			.collect::<Vec<_>>();627		quote! {628			impl #impl_generics Typed for #ident #ty_generics #where_clause {629				const TYPE: &'static ComplexValType = &ComplexValType::ObjectRef(&[630					#(#fields,)*631				]);632633				fn from_untyped(value: Val) -> JrResult<Self> {634					let obj = value.as_obj().expect("shape is correct");635					Self::parse(&obj)636				}637638				fn into_untyped(value: Self) -> JrResult<Val> {639					let mut out = ObjValueBuilder::new();640					value.serialize(&mut out)?;641					Ok(Val::Obj(out.build()))642				}643644			}645		}646	};647648	let fields_parse = fields.iter().map(TypedField::expand_parse);649	let fields_serialize = fields650		.iter()651		.map(TypedField::expand_serialize)652		.collect::<Result<Vec<_>>>()?;653654	Ok(quote! {655		const _: () = {656			use ::jrsonnet_evaluator::{657				typed::{ComplexValType, Typed, TypedObj, CheckType},658				Val, State,659				error::{ErrorKind, Result as JrResult},660				ObjValueBuilder, ObjValue,661			};662663			#typed664665			impl #impl_generics TypedObj for #ident #ty_generics #where_clause {666				fn serialize(self, out: &mut ObjValueBuilder) -> JrResult<()> {667					#(#fields_serialize)*668669					Ok(())670				}671				fn parse(obj: &ObjValue) -> JrResult<Self> {672					Ok(Self {673						#(#fields_parse)*674					})675				}676			}677		};678	})679}
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())))
 }