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

difftreelog

feat implement argument parsing with proc macro

Yaroslav Bolyukin2021-11-29parent: #cff8f6a.patch.diff
in: master

17 files changed

modifiedbindings/jsonnet/src/import.rsdiffbeforeafterboth
--- a/bindings/jsonnet/src/import.rs
+++ b/bindings/jsonnet/src/import.rs
@@ -49,8 +49,8 @@
 		};
 		// Release memory occipied by arguments passed
 		unsafe {
-			CString::from_raw(base);
-			CString::from_raw(rel);
+			let _ = CString::from_raw(base);
+			let _ = CString::from_raw(rel);
 		}
 		let result_raw = unsafe { CStr::from_ptr(result_ptr) };
 		let result_str = result_raw.to_str().unwrap();
@@ -64,7 +64,7 @@
 		let found_here_raw = unsafe { CStr::from_ptr(found_here) };
 		let found_here_buf = PathBuf::from(found_here_raw.to_str().unwrap());
 		unsafe {
-			CString::from_raw(found_here);
+			let _ = CString::from_raw(found_here);
 		}
 
 		let mut out = self.out.borrow_mut();
modifiedbindings/jsonnet/src/native.rsdiffbeforeafterboth
--- a/bindings/jsonnet/src/native.rs
+++ b/bindings/jsonnet/src/native.rs
@@ -3,10 +3,11 @@
 	error::{Error, LocError},
 	gc::TraceBox,
 	native::{NativeCallback, NativeCallbackHandler},
-	EvaluationState, Val,
+	EvaluationState, IStr, Val,
 };
 use jrsonnet_parser::{Param, ParamsDesc};
 use std::{
+	convert::TryFrom,
 	ffi::{c_void, CStr},
 	os::raw::{c_char, c_int},
 	path::Path,
@@ -45,7 +46,7 @@
 		if success == 1 {
 			Ok(v)
 		} else {
-			let e = v.try_cast_str("native error").expect("error msg");
+			let e = IStr::try_from(v).expect("error msg");
 			Err(Error::RuntimeError(e).into())
 		}
 	}
modifiedcrates/jrsonnet-evaluator/Cargo.tomldiffbeforeafterboth
--- a/crates/jrsonnet-evaluator/Cargo.toml
+++ b/crates/jrsonnet-evaluator/Cargo.toml
@@ -23,6 +23,7 @@
 jrsonnet-parser = { path = "../jrsonnet-parser", version = "0.4.2" }
 jrsonnet-stdlib = { path = "../jrsonnet-stdlib", version = "0.4.2" }
 jrsonnet-types = { path = "../jrsonnet-types", version = "0.4.2" }
+jrsonnet-macros = { path = "../jrsonnet-macros", version = "0.4.2" }
 pathdiff = "0.2.0"
 
 md5 = "0.7.0"
modifiedcrates/jrsonnet-evaluator/src/builtin/format.rsdiffbeforeafterboth
--- a/crates/jrsonnet-evaluator/src/builtin/format.rs
+++ b/crates/jrsonnet-evaluator/src/builtin/format.rs
@@ -5,6 +5,7 @@
 use gcmodule::Trace;
 use jrsonnet_interner::IStr;
 use jrsonnet_types::ValType;
+use std::convert::TryFrom;
 use thiserror::Error;
 
 #[derive(Debug, Clone, Error, Trace)]
@@ -484,7 +485,7 @@
 	match code.convtype {
 		ConvTypeV::String => tmp_out.push_str(&value.clone().to_string()?),
 		ConvTypeV::Decimal => {
-			let value = value.clone().try_cast_num("%d/%u/%i requires number")?;
+			let value = f64::try_from(value.clone())?;
 			render_decimal(
 				&mut tmp_out,
 				value as i64,
@@ -495,7 +496,7 @@
 			);
 		}
 		ConvTypeV::Octal => {
-			let value = value.clone().try_cast_num("%o requires number")?;
+			let value = f64::try_from(value.clone())?;
 			render_octal(
 				&mut tmp_out,
 				value as i64,
@@ -507,7 +508,7 @@
 			);
 		}
 		ConvTypeV::Hexadecimal => {
-			let value = value.clone().try_cast_num("%x/%X requires number")?;
+			let value = f64::try_from(value.clone())?;
 			render_hexadecimal(
 				&mut tmp_out,
 				value as i64,
@@ -520,7 +521,7 @@
 			);
 		}
 		ConvTypeV::Scientific => {
-			let value = value.clone().try_cast_num("%e/%E requires number")?;
+			let value = f64::try_from(value.clone())?;
 			render_float_sci(
 				&mut tmp_out,
 				value,
@@ -534,7 +535,7 @@
 			);
 		}
 		ConvTypeV::Float => {
-			let value = value.clone().try_cast_num("%e/%E requires number")?;
+			let value = f64::try_from(value.clone())?;
 			render_float(
 				&mut tmp_out,
 				value,
@@ -547,7 +548,7 @@
 			);
 		}
 		ConvTypeV::Shorter => {
-			let value = value.clone().try_cast_num("%g/%G requires number")?;
+			let value = f64::try_from(value.clone())?;
 			let exponent = value.log10().floor();
 			if exponent < -4.0 || exponent >= fpprec as f64 {
 				render_float_sci(
@@ -633,7 +634,7 @@
 						}
 						let value = &values[0];
 						values = &values[1..];
-						value.clone().try_cast_num("field width")? as usize
+						usize::try_from(value.clone())?
 					}
 					Width::Fixed(n) => n,
 				};
@@ -644,7 +645,7 @@
 						}
 						let value = &values[0];
 						values = &values[1..];
-						Some(value.clone().try_cast_num("field precision")? as usize)
+						Some(usize::try_from(value.clone())?)
 					}
 					Some(Width::Fixed(n)) => Some(n),
 					None => None,
modifiedcrates/jrsonnet-evaluator/src/builtin/mod.rsdiffbeforeafterboth
--- a/crates/jrsonnet-evaluator/src/builtin/mod.rs
+++ b/crates/jrsonnet-evaluator/src/builtin/mod.rs
@@ -1,10 +1,12 @@
+use crate::typed::{Any, Either, Null, PositiveF64, VecVal, M1};
+use crate::{self as jrsonnet_evaluator, ObjValue};
 use crate::{
 	builtin::manifest::{manifest_yaml_ex, ManifestYamlOptions},
 	equals,
 	error::{Error::*, Result},
 	operator::evaluate_mod_op,
 	parse_args, primitive_equals, push_frame, throw, with_state, ArrValue, Context, FuncVal,
-	IndexableVal, LazyVal, Val,
+	IndexableVal, Val,
 };
 use format::{format_arr, format_obj};
 use gcmodule::Cc;
@@ -13,7 +15,12 @@
 use jrsonnet_types::ty;
 use serde::Deserialize;
 use serde_yaml::DeserializingQuirks;
-use std::{collections::HashMap, convert::TryFrom, path::PathBuf, rc::Rc};
+use std::{
+	collections::HashMap,
+	convert::{TryFrom, TryInto},
+	path::PathBuf,
+	rc::Rc,
+};
 
 pub mod stdlib;
 pub use stdlib::*;
@@ -24,15 +31,15 @@
 pub mod manifest;
 pub mod sort;
 
-pub fn std_format(str: IStr, vals: Val) -> Result<Val> {
+pub fn std_format(str: IStr, vals: Val) -> Result<String> {
 	push_frame(
 		&ExprLocation(Rc::from(PathBuf::from("std.jsonnet")), 0, 0),
 		|| format!("std.format of {}", str),
 		|| {
 			Ok(match vals {
-				Val::Arr(vals) => Val::Str(format_arr(&str, &vals.evaluated()?)?.into()),
-				Val::Obj(obj) => Val::Str(format_obj(&str, &obj)?.into()),
-				o => Val::Str(format_arr(&str, &[o])?.into()),
+				Val::Arr(vals) => format_arr(&str, &vals.evaluated()?)?,
+				Val::Obj(obj) => format_obj(&str, &obj)?,
+				o => format_arr(&str, &[o])?,
 			})
 		},
 	)
@@ -139,265 +146,177 @@
 	};
 }
 
-fn builtin_length(context: Context, _loc: &ExprLocation, args: &ArgsDesc) -> Result<Val> {
-	parse_args!(context, "length", args, 1, [
-		0, x: ty!((string | object | array));
-	], {
-		Ok(match x {
-			Val::Str(n) => Val::Num(n.chars().count() as f64),
-			Val::Arr(a) => Val::Num(a.len() as f64),
-			Val::Obj(o) => Val::Num(
-				o.fields_visibility()
-					.into_iter()
-					.filter(|(_k, v)| *v)
-					.count() as f64,
-			),
-			_ => unreachable!(),
-		})
+#[jrsonnet_macros::builtin]
+fn builtin_length(x: Either<IStr, Either<VecVal, ObjValue>>) -> Result<usize> {
+	Ok(match x {
+		Either::Left(x) => x.len(),
+		Either::Right(Either::Left(x)) => x.0.len(),
+		Either::Right(Either::Right(x)) => x
+			.fields_visibility()
+			.into_iter()
+			.filter(|(_k, v)| *v)
+			.count(),
 	})
 }
 
-fn builtin_type(context: Context, _loc: &ExprLocation, args: &ArgsDesc) -> Result<Val> {
-	parse_args!(context, "type", args, 1, [
-		0, x: ty!(any);
-	], {
-		Ok(Val::Str(x.value_type().name().into()))
-	})
+#[jrsonnet_macros::builtin]
+fn builtin_type(x: Any) -> Result<IStr> {
+	Ok(x.0.value_type().name().into())
 }
 
-fn builtin_make_array(context: Context, _loc: &ExprLocation, args: &ArgsDesc) -> Result<Val> {
-	parse_args!(context, "makeArray", args, 2, [
-		0, sz: ty!(BoundedNumber<(Some(0.0)), (None)>) => Val::Num;
-		1, func: ty!(function) => Val::Func;
-	], {
-		let mut out = Vec::with_capacity(sz as usize);
-		for i in 0..sz as usize {
-			out.push(LazyVal::new_resolved(func.evaluate_values(
-				context.clone(),
-				&[Val::Num(i as f64)]
-			)?))
-		}
-		Ok(Val::Arr(out.into()))
-	})
+#[jrsonnet_macros::builtin]
+fn builtin_make_array(sz: usize, func: Cc<FuncVal>) -> Result<VecVal> {
+	let mut out = Vec::with_capacity(sz);
+	for i in 0..sz {
+		out.push(func.evaluate_values(&[Val::Num(i as f64)])?)
+	}
+	Ok(VecVal(out))
 }
 
-fn builtin_codepoint(context: Context, _loc: &ExprLocation, args: &ArgsDesc) -> Result<Val> {
-	parse_args!(context, "codepoint", args, 1, [
-		0, str: ty!(char) => Val::Str;
-	], {
-		Ok(Val::Num(str.chars().next().unwrap() as u32 as f64))
-	})
+#[jrsonnet_macros::builtin]
+const fn builtin_codepoint(str: char) -> Result<u32> {
+	Ok(str as u32)
 }
 
-fn builtin_object_fields_ex(context: Context, _loc: &ExprLocation, args: &ArgsDesc) -> Result<Val> {
-	parse_args!(context, "objectFieldsEx", args, 2, [
-		0, obj: ty!(object) => Val::Obj;
-		1, inc_hidden: ty!(boolean) => Val::Bool;
-	], {
-		let out = obj.fields_ex(inc_hidden);
-		Ok(Val::Arr(out.into_iter().map(Val::Str).collect::<Vec<_>>().into()))
-	})
+#[jrsonnet_macros::builtin]
+fn builtin_object_fields_ex(obj: ObjValue, inc_hidden: bool) -> Result<VecVal> {
+	let out = obj.fields_ex(inc_hidden);
+	Ok(VecVal(out.into_iter().map(Val::Str).collect::<Vec<_>>()))
 }
 
-fn builtin_object_has_ex(context: Context, _loc: &ExprLocation, args: &ArgsDesc) -> Result<Val> {
-	parse_args!(context, "objectHasEx", args, 3, [
-		0, obj: ty!(object) => Val::Obj;
-		1, f: ty!(string) => Val::Str;
-		2, inc_hidden: ty!(boolean) => Val::Bool;
-	], {
-		Ok(Val::Bool(obj.has_field_ex(f, inc_hidden)))
-	})
+#[jrsonnet_macros::builtin]
+fn builtin_object_has_ex(obj: ObjValue, f: IStr, inc_hidden: bool) -> Result<bool> {
+	Ok(obj.has_field_ex(f, inc_hidden))
 }
 
-fn builtin_parse_json(context: Context, _loc: &ExprLocation, args: &ArgsDesc) -> Result<Val> {
-	parse_args!(context, "parseJson", args, 1, [
-		0, s: ty!(string) => Val::Str;
-	], {
-		let value: serde_json::Value = serde_json::from_str(&s).map_err(|e| RuntimeError(format!("failed to parse json: {}", e).into()))?;
-		Ok(Val::try_from(&value)?)
-	})
+#[jrsonnet_macros::builtin]
+fn builtin_parse_json(s: IStr) -> Result<Any> {
+	let value: serde_json::Value = serde_json::from_str(&s)
+		.map_err(|e| RuntimeError(format!("failed to parse json: {}", e).into()))?;
+	Ok(Any(Val::try_from(&value)?))
 }
 
-fn builtin_parse_yaml(context: Context, _loc: &ExprLocation, args: &ArgsDesc) -> Result<Val> {
-	parse_args!(context, "parseYaml", args, 1, [
-		0, s: ty!(string) => Val::Str;
-	], {
-		let value = serde_yaml::Deserializer::from_str_with_quirks(&s, DeserializingQuirks { old_octals: true });
-		let mut out = vec![];
-		for item in value {
-			let value = serde_json::Value::deserialize(item)
-				.map_err(|e| RuntimeError(format!("failed to parse yaml: {}", e).into()))?;
-			let val = Val::try_from(&value)?;
-			out.push(val);
-		}
-		if out.is_empty() {
-			Ok(Val::Null)
-		} else if out.len() == 1 {
-			Ok(out.into_iter().next().unwrap())
-		} else {
-			Ok(Val::Arr(out.into()))
-		}
-	})
+#[jrsonnet_macros::builtin]
+fn builtin_parse_yaml(s: IStr) -> Result<Any> {
+	let value = serde_yaml::Deserializer::from_str_with_quirks(
+		&s,
+		DeserializingQuirks { old_octals: true },
+	);
+	let mut out = vec![];
+	for item in value {
+		let value = serde_json::Value::deserialize(item)
+			.map_err(|e| RuntimeError(format!("failed to parse yaml: {}", e).into()))?;
+		let val = Val::try_from(&value)?;
+		out.push(val);
+	}
+	Ok(Any(if out.is_empty() {
+		Val::Null
+	} else if out.len() == 1 {
+		out.into_iter().next().unwrap()
+	} else {
+		Val::Arr(out.into())
+	}))
 }
 
-fn builtin_slice(context: Context, _loc: &ExprLocation, args: &ArgsDesc) -> Result<Val> {
-	parse_args!(context, "slice", args, 4, [
-		0, indexable: ty!((string | array));
-		1, index: ty!((number | null));
-		2, end: ty!((number | null));
-		3, step: ty!((number | null));
-	], {
-		std_slice(
-			indexable.into_indexable()?,
-			index.try_cast_nullable_num("index")?.map(|v| v as usize),
-			end.try_cast_nullable_num("end")?.map(|v| v as usize),
-			step.try_cast_nullable_num("step")?.map(|v| v as usize),
-		)
-	})
+#[jrsonnet_macros::builtin]
+fn builtin_slice(
+	indexable: IndexableVal,
+	index: Either<usize, Null>,
+	end: Either<usize, Null>,
+	step: Either<usize, Null>,
+) -> Result<Any> {
+	std_slice(indexable, index.left(), end.left(), step.left()).map(Any)
 }
 
-fn builtin_substr(context: Context, _loc: &ExprLocation, args: &ArgsDesc) -> Result<Val> {
-	parse_args!(context, "substr", args, 3, [
-		0, str: ty!(string) => Val::Str;
-		1, from: ty!(BoundedNumber<(Some(0.0)), (None)>) => Val::Num;
-		2, len: ty!(BoundedNumber<(Some(0.0)), (None)>) => Val::Num;
-	], {
-		let out: String = str.chars().skip(from as usize).take(len as usize).collect();
-		Ok(Val::Str(out.into()))
-	})
+#[jrsonnet_macros::builtin]
+fn builtin_substr(str: IStr, from: usize, len: usize) -> Result<String> {
+	Ok(str.chars().skip(from as usize).take(len as usize).collect())
 }
 
-fn builtin_primitive_equals(context: Context, _loc: &ExprLocation, args: &ArgsDesc) -> Result<Val> {
-	parse_args!(context, "primitiveEquals", args, 2, [
-		0, a: ty!(any);
-		1, b: ty!(any);
-	], {
-		Ok(Val::Bool(primitive_equals(&a, &b)?))
-	})
+#[jrsonnet_macros::builtin]
+fn builtin_primitive_equals(a: Any, b: Any) -> Result<bool> {
+	primitive_equals(&a.0, &b.0)
 }
 
-fn builtin_equals(context: Context, _loc: &ExprLocation, args: &ArgsDesc) -> Result<Val> {
-	parse_args!(context, "equals", args, 2, [
-		0, a: ty!(any);
-		1, b: ty!(any);
-	], {
-		Ok(Val::Bool(equals(&a, &b)?))
-	})
+#[jrsonnet_macros::builtin]
+fn builtin_equals(a: Any, b: Any) -> Result<bool> {
+	equals(&a.0, &b.0)
 }
 
-fn builtin_modulo(context: Context, _loc: &ExprLocation, args: &ArgsDesc) -> Result<Val> {
-	parse_args!(context, "modulo", args, 2, [
-		0, a: ty!(number) => Val::Num;
-		1, b: ty!(number) => Val::Num;
-	], {
-		Ok(Val::Num(a % b))
-	})
+#[jrsonnet_macros::builtin]
+fn builtin_modulo(a: f64, b: f64) -> Result<f64> {
+	Ok(a % b)
 }
 
-fn builtin_mod(context: Context, _loc: &ExprLocation, args: &ArgsDesc) -> Result<Val> {
-	parse_args!(context, "mod", args, 2, [
-		0, a: ty!((number | string));
-		1, b: ty!(any);
-	], {
-		evaluate_mod_op(&a, &b)
-	})
+#[jrsonnet_macros::builtin]
+fn builtin_mod(a: Either<f64, IStr>, b: Any) -> Result<Any> {
+	Ok(Any(evaluate_mod_op(
+		&match a {
+			Either::Left(v) => Val::Num(v),
+			Either::Right(s) => Val::Str(s),
+		},
+		&b.0,
+	)?))
 }
 
-fn builtin_floor(context: Context, _loc: &ExprLocation, args: &ArgsDesc) -> Result<Val> {
-	parse_args!(context, "floor", args, 1, [
-		0, x: ty!(number) => Val::Num;
-	], {
-		Ok(Val::Num(x.floor()))
-	})
+#[jrsonnet_macros::builtin]
+fn builtin_floor(x: f64) -> Result<f64> {
+	Ok(x.floor())
 }
 
-fn builtin_ceil(context: Context, _loc: &ExprLocation, args: &ArgsDesc) -> Result<Val> {
-	parse_args!(context, "ceil", args, 1, [
-		0, x: ty!(number) => Val::Num;
-	], {
-		Ok(Val::Num(x.ceil()))
-	})
+#[jrsonnet_macros::builtin]
+fn builtin_ceil(x: f64) -> Result<f64> {
+	Ok(x.ceil())
 }
 
-fn builtin_log(context: Context, _loc: &ExprLocation, args: &ArgsDesc) -> Result<Val> {
-	parse_args!(context, "log", args, 1, [
-		0, n: ty!(number) => Val::Num;
-	], {
-		Ok(Val::Num(n.ln()))
-	})
+#[jrsonnet_macros::builtin]
+fn builtin_log(n: f64) -> Result<f64> {
+	Ok(n.ln())
 }
 
-fn builtin_pow(context: Context, _loc: &ExprLocation, args: &ArgsDesc) -> Result<Val> {
-	parse_args!(context, "pow", args, 2, [
-		0, x: ty!(number) => Val::Num;
-		1, n: ty!(number) => Val::Num;
-	], {
-		Ok(Val::Num(x.powf(n)))
-	})
+#[jrsonnet_macros::builtin]
+fn builtin_pow(x: f64, n: f64) -> Result<f64> {
+	Ok(x.powf(n))
 }
 
-fn builtin_sqrt(context: Context, _loc: &ExprLocation, args: &ArgsDesc) -> Result<Val> {
-	parse_args!(context, "sqrt", args, 1, [
-		0, x: ty!(BoundedNumber<(Some(0.0)), (None)>) => Val::Num;
-	], {
-		Ok(Val::Num(x.sqrt()))
-	})
+#[jrsonnet_macros::builtin]
+fn builtin_sqrt(x: PositiveF64) -> Result<f64> {
+	Ok(x.0.sqrt())
 }
 
-fn builtin_sin(context: Context, _loc: &ExprLocation, args: &ArgsDesc) -> Result<Val> {
-	parse_args!(context, "sin", args, 1, [
-		0, x: ty!(number) => Val::Num;
-	], {
-		Ok(Val::Num(x.sin()))
-	})
+#[jrsonnet_macros::builtin]
+fn builtin_sin(x: f64) -> Result<f64> {
+	Ok(x.sin())
 }
 
-fn builtin_cos(context: Context, _loc: &ExprLocation, args: &ArgsDesc) -> Result<Val> {
-	parse_args!(context, "cos", args, 1, [
-		0, x: ty!(number) => Val::Num;
-	], {
-		Ok(Val::Num(x.cos()))
-	})
+#[jrsonnet_macros::builtin]
+fn builtin_cos(x: f64) -> Result<f64> {
+	Ok(x.cos())
 }
 
-fn builtin_tan(context: Context, _loc: &ExprLocation, args: &ArgsDesc) -> Result<Val> {
-	parse_args!(context, "tan", args, 1, [
-		0, x: ty!(number) => Val::Num;
-	], {
-		Ok(Val::Num(x.tan()))
-	})
+#[jrsonnet_macros::builtin]
+fn builtin_tan(x: f64) -> Result<f64> {
+	Ok(x.tan())
 }
 
-fn builtin_asin(context: Context, _loc: &ExprLocation, args: &ArgsDesc) -> Result<Val> {
-	parse_args!(context, "asin", args, 1, [
-		0, x: ty!(number) => Val::Num;
-	], {
-		Ok(Val::Num(x.asin()))
-	})
+#[jrsonnet_macros::builtin]
+fn builtin_asin(x: f64) -> Result<f64> {
+	Ok(x.asin())
 }
 
-fn builtin_acos(context: Context, _loc: &ExprLocation, args: &ArgsDesc) -> Result<Val> {
-	parse_args!(context, "acos", args, 1, [
-		0, x: ty!(number) => Val::Num;
-	], {
-		Ok(Val::Num(x.acos()))
-	})
+#[jrsonnet_macros::builtin]
+fn builtin_acos(x: f64) -> Result<f64> {
+	Ok(x.acos())
 }
 
-fn builtin_atan(context: Context, _loc: &ExprLocation, args: &ArgsDesc) -> Result<Val> {
-	parse_args!(context, "atan", args, 1, [
-		0, x: ty!(number) => Val::Num;
-	], {
-		Ok(Val::Num(x.atan()))
-	})
+#[jrsonnet_macros::builtin]
+fn builtin_atan(x: f64) -> Result<f64> {
+	Ok(x.atan())
 }
 
-fn builtin_exp(context: Context, _loc: &ExprLocation, args: &ArgsDesc) -> Result<Val> {
-	parse_args!(context, "exp", args, 1, [
-		0, x: ty!(number) => Val::Num;
-	], {
-		Ok(Val::Num(x.exp()))
-	})
+#[jrsonnet_macros::builtin]
+fn builtin_exp(x: f64) -> Result<f64> {
+	Ok(x.exp())
 }
 
 fn frexp(s: f64) -> (f64, i16) {
@@ -411,198 +330,140 @@
 	}
 }
 
-fn builtin_mantissa(context: Context, _loc: &ExprLocation, args: &ArgsDesc) -> Result<Val> {
-	parse_args!(context, "mantissa", args, 1, [
-		0, x: ty!(number) => Val::Num;
-	], {
-		Ok(Val::Num(frexp(x).0))
-	})
+#[jrsonnet_macros::builtin]
+fn builtin_mantissa(x: f64) -> Result<f64> {
+	Ok(frexp(x).0)
 }
 
-fn builtin_exponent(context: Context, _loc: &ExprLocation, args: &ArgsDesc) -> Result<Val> {
-	parse_args!(context, "exponent", args, 1, [
-		0, x: ty!(number) => Val::Num;
-	], {
-		Ok(Val::Num(frexp(x).1.into()))
-	})
+#[jrsonnet_macros::builtin]
+fn builtin_exponent(x: f64) -> Result<i16> {
+	Ok(frexp(x).1)
 }
 
-fn builtin_ext_var(context: Context, _loc: &ExprLocation, args: &ArgsDesc) -> Result<Val> {
-	parse_args!(context, "extVar", args, 1, [
-		0, x: ty!(string) => Val::Str;
-	], {
-		Ok(with_state(|s| s.settings().ext_vars.get(&x).cloned()).ok_or(UndefinedExternalVariable(x))?)
-	})
+#[jrsonnet_macros::builtin]
+fn builtin_ext_var(x: IStr) -> Result<Any> {
+	Ok(Any(with_state(|s| s.settings().ext_vars.get(&x).cloned())
+		.ok_or(UndefinedExternalVariable(x))?))
 }
 
-fn builtin_native(context: Context, _loc: &ExprLocation, args: &ArgsDesc) -> Result<Val> {
-	parse_args!(context, "native", args, 1, [
-		0, x: ty!(string) => Val::Str;
-	], {
-		Ok(with_state(|s| s.settings().ext_natives.get(&x).cloned()).map(|v| Val::Func(Cc::new(FuncVal::NativeExt(x.clone(), v)))).ok_or(UndefinedExternalFunction(x))?)
-	})
+#[jrsonnet_macros::builtin]
+fn builtin_native(name: IStr) -> Result<Cc<FuncVal>> {
+	Ok(with_state(|s| s.settings().ext_natives.get(&name).cloned())
+		.map(|v| Cc::new(FuncVal::NativeExt(name.clone(), v)))
+		.ok_or(UndefinedExternalFunction(name))?)
 }
 
-fn builtin_filter(context: Context, _loc: &ExprLocation, args: &ArgsDesc) -> Result<Val> {
-	parse_args!(context, "filter", args, 2, [
-		0, func: ty!(function) => Val::Func;
-		1, arr: ty!(array) => Val::Arr;
-	], {
-		Ok(Val::Arr(arr.filter(|val| func
-			.evaluate_values(context.clone(), &[val.clone()])?
-			.try_cast_bool("filter predicate"))?))
-	})
+#[jrsonnet_macros::builtin]
+fn builtin_filter(func: Cc<FuncVal>, arr: ArrValue) -> Result<ArrValue> {
+	arr.filter(|val| bool::try_from(func.evaluate_values(&[val.clone()])?))
 }
 
-fn builtin_map(context: Context, _loc: &ExprLocation, args: &ArgsDesc) -> Result<Val> {
-	parse_args!(context, "map", args, 2, [
-		0, func: ty!(function) => Val::Func;
-		1, arr: ty!(array) => Val::Arr;
-	], {
-		Ok(Val::Arr(arr.map(|val| func
-			.evaluate_values(context.clone(), &[val]))?))
-	})
+#[jrsonnet_macros::builtin]
+fn builtin_map(func: Cc<FuncVal>, arr: ArrValue) -> Result<ArrValue> {
+	arr.map(|val| func.evaluate_values(&[val]))
 }
 
-fn builtin_flatmap(context: Context, _loc: &ExprLocation, args: &ArgsDesc) -> Result<Val> {
-	parse_args!(context, "flatMap", args, 2, [
-		0, func: ty!(function) => Val::Func;
-		1, arr: ty!((array | string));
-	], {
-		match arr {
-			Val::Str(s) => {
-				let mut out = String::new();
-				for c in s.chars() {
-					match func.evaluate_values(context.clone(), &[Val::Str(c.to_string().into())])? {
-						Val::Str(o) => out.push_str(&o),
-						_ => throw!(RuntimeError("in std.join all items should be strings".into())),
-					};
-				}
-				Ok(Val::Str(out.into()))
-			},
-			Val::Arr(a) => {
-				let mut out = Vec::new();
-				for el in a.iter() {
-					let el = el?;
-					match func.evaluate_values(context.clone(), &[el])? {
-						Val::Arr(o) => for oe in o.iter() {
+#[jrsonnet_macros::builtin]
+fn builtin_flatmap(func: Cc<FuncVal>, arr: IndexableVal) -> Result<IndexableVal> {
+	match arr {
+		IndexableVal::Str(s) => {
+			let mut out = String::new();
+			for c in s.chars() {
+				match func.evaluate_values(&[Val::Str(c.to_string().into())])? {
+					Val::Str(o) => out.push_str(&o),
+					_ => throw!(RuntimeError(
+						"in std.join all items should be strings".into()
+					)),
+				};
+			}
+			Ok(IndexableVal::Str(out.into()))
+		}
+		IndexableVal::Arr(a) => {
+			let mut out = Vec::new();
+			for el in a.iter() {
+				let el = el?;
+				match func.evaluate_values(&[el])? {
+					Val::Arr(o) => {
+						for oe in o.iter() {
 							out.push(oe?)
-						},
-						_ => throw!(RuntimeError("in std.join all items should be arrays".into())),
-					};
-				}
-				Ok(Val::Arr(out.into()))
-			},
-			_ => unreachable!(),
+						}
+					}
+					_ => throw!(RuntimeError(
+						"in std.join all items should be arrays".into()
+					)),
+				};
+			}
+			Ok(IndexableVal::Arr(out.into()))
 		}
-	})
+	}
 }
 
-fn builtin_foldl(context: Context, _loc: &ExprLocation, args: &ArgsDesc) -> Result<Val> {
-	parse_args!(context, "foldl", args, 3, [
-		0, func: ty!(function) => Val::Func;
-		1, arr: ty!(array) => Val::Arr;
-		2, init: ty!(any);
-	], {
-		let mut acc = init;
-		for i in arr.iter() {
-			acc = func.evaluate_values(context.clone(), &[acc, i?])?;
-		}
-		Ok(acc)
-	})
+#[jrsonnet_macros::builtin]
+fn builtin_foldl(func: Cc<FuncVal>, arr: ArrValue, init: Any) -> Result<Any> {
+	let mut acc = init.0;
+	for i in arr.iter() {
+		acc = func.evaluate_values(&[acc, i?])?;
+	}
+	Ok(Any(acc))
 }
 
-fn builtin_foldr(context: Context, _loc: &ExprLocation, args: &ArgsDesc) -> Result<Val> {
-	parse_args!(context, "foldr", args, 3, [
-		0, func: ty!(function) => Val::Func;
-		1, arr: ty!(array) => Val::Arr;
-		2, init: ty!(any);
-	], {
-		let mut acc = init;
-		for i in arr.iter().rev() {
-			acc = func.evaluate_values(context.clone(), &[i?, acc])?;
-		}
-		Ok(acc)
-	})
+#[jrsonnet_macros::builtin]
+fn builtin_foldr(func: Cc<FuncVal>, arr: ArrValue, init: Any) -> Result<Any> {
+	let mut acc = init.0;
+	for i in arr.iter().rev() {
+		acc = func.evaluate_values(&[i?, acc])?;
+	}
+	Ok(Any(acc))
 }
 
+#[jrsonnet_macros::builtin]
 #[allow(non_snake_case)]
-fn builtin_sort_impl(context: Context, _loc: &ExprLocation, args: &ArgsDesc) -> Result<Val> {
-	parse_args!(context, "sort", args, 2, [
-		0, arr: ty!(array) => Val::Arr;
-		1, keyF: ty!(function) => Val::Func;
-	], {
-		if arr.len() <= 1 {
-			return Ok(Val::Arr(arr))
-		}
-		Ok(Val::Arr(ArrValue::Eager(sort::sort(context, arr.evaluated()?, &keyF)?)))
-	})
+fn builtin_sort_impl(arr: ArrValue, keyF: Cc<FuncVal>) -> Result<ArrValue> {
+	if arr.len() <= 1 {
+		return Ok(arr);
+	}
+	Ok(ArrValue::Eager(sort::sort(arr.evaluated()?, &keyF)?))
 }
 
-fn builtin_format(context: Context, _loc: &ExprLocation, args: &ArgsDesc) -> Result<Val> {
-	parse_args!(context, "format", args, 2, [
-		0, str: ty!(string) => Val::Str;
-		1, vals: ty!(any)
-	], {
-		std_format(str, vals)
-	})
+#[jrsonnet_macros::builtin]
+fn builtin_format(str: IStr, vals: Any) -> Result<String> {
+	std_format(str, vals.0)
 }
 
-fn builtin_range(context: Context, _loc: &ExprLocation, args: &ArgsDesc) -> Result<Val> {
-	parse_args!(context, "range", args, 2, [
-		0, from: ty!(number) => Val::Num;
-		1, to: ty!(number) => Val::Num;
-	], {
-		if to < from {
-			return Ok(Val::Arr(ArrValue::new_eager()))
-		}
-		let mut out = Vec::with_capacity((1+to as usize-from as usize).max(0));
-		for i in from as usize..=to as usize {
-			out.push(Val::Num(i as f64));
-		}
-		Ok(Val::Arr(out.into()))
-	})
+#[jrsonnet_macros::builtin]
+fn builtin_range(from: i32, to: i32) -> Result<VecVal> {
+	if to < from {
+		return Ok(VecVal(Vec::new()));
+	}
+	let mut out = Vec::with_capacity((1 + to as usize - from as usize).max(0));
+	for i in from as usize..=to as usize {
+		out.push(Val::Num(i as f64));
+	}
+	Ok(VecVal(out))
 }
 
-fn builtin_char(context: Context, _loc: &ExprLocation, args: &ArgsDesc) -> Result<Val> {
-	parse_args!(context, "char", args, 1, [
-		0, n: ty!(number) => Val::Num;
-	], {
-		let mut out = String::new();
-		out.push(std::char::from_u32(n as u32).ok_or_else(||
-			InvalidUnicodeCodepointGot(n as u32)
-		)?);
-		Ok(Val::Str(out.into()))
-	})
+#[jrsonnet_macros::builtin]
+fn builtin_char(n: u32) -> Result<char> {
+	Ok(std::char::from_u32(n as u32).ok_or_else(|| InvalidUnicodeCodepointGot(n as u32))?)
 }
 
-fn builtin_encode_utf8(context: Context, _loc: &ExprLocation, args: &ArgsDesc) -> Result<Val> {
-	parse_args!(context, "encodeUTF8", args, 1, [
-		0, str: ty!(string) => Val::Str;
-	], {
-		Ok(Val::Arr((str.bytes().map(|b| Val::Num(b as f64)).collect::<Vec<Val>>()).into()))
-	})
+#[jrsonnet_macros::builtin]
+fn builtin_encode_utf8(str: IStr) -> Result<VecVal> {
+	Ok(VecVal(
+		str.bytes()
+			.map(|b| Val::Num(b as f64))
+			.collect::<Vec<Val>>(),
+	))
 }
 
-fn builtin_decode_utf8(context: Context, _loc: &ExprLocation, args: &ArgsDesc) -> Result<Val> {
-	parse_args!(context, "decodeUTF8", args, 1, [
-		0, arr: ty!((Array<ubyte>)) => Val::Arr;
-	], {
-		let data: Result<Vec<u8>> = arr.iter().map(|v| v.map(|v| match v{
-			Val::Num(n) => n as u8,
-			_ => unreachable!(),
-		})).collect();
-		let data = data?;
-		Ok(Val::Str(String::from_utf8(data).map_err(|_| RuntimeError("bad utf8".into()))?.into()))
-	})
+#[jrsonnet_macros::builtin]
+fn builtin_decode_utf8(arr: Vec<u8>) -> Result<String> {
+	Ok(String::from_utf8(arr).map_err(|_| RuntimeError("bad utf8".into()))?)
 }
 
-fn builtin_md5(context: Context, _loc: &ExprLocation, args: &ArgsDesc) -> Result<Val> {
-	parse_args!(context, "md5", args, 1, [
-		0, str: ty!(string) => Val::Str;
-	], {
-		Ok(Val::Str(format!("{:x}", md5::compute(&str.as_bytes())).into()))
-	})
+#[jrsonnet_macros::builtin]
+fn builtin_md5(str: IStr) -> Result<String> {
+	Ok(format!("{:x}", md5::compute(&str.as_bytes())))
 }
 
 fn builtin_trace(context: Context, loc: &ExprLocation, args: &ArgsDesc) -> Result<Val> {
@@ -620,251 +481,174 @@
 	})
 }
 
-fn builtin_base64(context: Context, _loc: &ExprLocation, args: &ArgsDesc) -> Result<Val> {
-	parse_args!(context, "base64", args, 1, [
-		0, input: ty!((string | (Array<number>)));
-	], {
-		Ok(Val::Str(match input {
-			Val::Str(s) => {
-				base64::encode(s.bytes().collect::<Vec<_>>()).into()
-			},
-			Val::Arr(a) => {
-				base64::encode(a.iter().map(|v| {
-					Ok(v?.unwrap_num()? as u8)
-				}).collect::<Result<Vec<_>>>()?).into()
-			},
-			_ => unreachable!()
-		}))
+#[jrsonnet_macros::builtin]
+fn builtin_base64(input: Either<Vec<u8>, IStr>) -> Result<String> {
+	Ok(match input {
+		Either::Left(a) => base64::encode(a),
+		Either::Right(l) => base64::encode(l.bytes().collect::<Vec<_>>()),
 	})
 }
 
-fn builtin_base64_decode_bytes(
-	context: Context,
-	_loc: &ExprLocation,
-	args: &ArgsDesc,
-) -> Result<Val> {
-	parse_args!(context, "base64DecodeBytes", args, 1, [
-		0, input: ty!(string) => Val::Str;
-	], {
-		Ok(Val::Arr(
-			base64::decode(&input.as_bytes())
-				.map_err(|_| RuntimeError("bad base64".into()))?
-				.iter()
-				.map(|v| Val::Num(*v as f64)).collect::<Vec<_>>().into()
-		))
-	})
+#[jrsonnet_macros::builtin]
+fn builtin_base64_decode_bytes(input: IStr) -> Result<Vec<u8>> {
+	Ok(base64::decode(&input.as_bytes()).map_err(|_| RuntimeError("bad base64".into()))?)
 }
 
-fn builtin_base64_decode(context: Context, _loc: &ExprLocation, args: &ArgsDesc) -> Result<Val> {
-	parse_args!(context, "base64Decode", args, 1, [
-		0, input: ty!(string) => Val::Str;
-	], {
-		Ok(Val::Str(
-			String::from_utf8(base64::decode(&input.as_bytes())
-				.map_err(|_| RuntimeError("bad base64".into()))?)
-				.map_err(|_| RuntimeError("bad utf8".into()))?.into()
-		))
-	})
+#[jrsonnet_macros::builtin]
+fn builtin_base64_decode(input: IStr) -> Result<String> {
+	let bytes = base64::decode(&input.as_bytes()).map_err(|_| RuntimeError("bad base64".into()))?;
+	Ok(String::from_utf8(bytes).map_err(|_| RuntimeError("bad utf8".into()))?)
 }
 
-fn builtin_join(context: Context, _loc: &ExprLocation, args: &ArgsDesc) -> Result<Val> {
-	parse_args!(context, "join", args, 2, [
-		0, sep: ty!((string | array));
-		1, arr: ty!(array) => Val::Arr;
-	], {
-		Ok(match sep {
-			Val::Arr(joiner_items) => {
-				let mut out = Vec::new();
+#[jrsonnet_macros::builtin]
+fn builtin_join(sep: IndexableVal, arr: ArrValue) -> Result<IndexableVal> {
+	Ok(match sep {
+		IndexableVal::Arr(joiner_items) => {
+			let mut out = Vec::new();
 
-				let mut first = true;
-				for item in arr.iter() {
-					let item = item?.clone();
-					if let Val::Arr(items) = item {
-						if !first {
-							out.reserve(joiner_items.len());
-							// TODO: extend
-							for item in joiner_items.iter() {
-								out.push(item?);
-							}
-						}
-						first = false;
-						out.reserve(items.len());
+			let mut first = true;
+			for item in arr.iter() {
+				let item = item?.clone();
+				if let Val::Arr(items) = item {
+					if !first {
+						out.reserve(joiner_items.len());
 						// TODO: extend
-						for item in items.iter() {
+						for item in joiner_items.iter() {
 							out.push(item?);
 						}
-					} else {
-						throw!(RuntimeError("in std.join all items should be arrays".into()));
 					}
+					first = false;
+					out.reserve(items.len());
+					// TODO: extend
+					for item in items.iter() {
+						out.push(item?);
+					}
+				} else {
+					throw!(RuntimeError(
+						"in std.join all items should be arrays".into()
+					));
 				}
+			}
 
-				Val::Arr(out.into())
-			},
-			Val::Str(sep) => {
-				let mut out = String::new();
+			IndexableVal::Arr(out.into())
+		}
+		IndexableVal::Str(sep) => {
+			let mut out = String::new();
 
-				let mut first = true;
-				for item in arr.iter() {
-					let item = item?.clone();
-					if let Val::Str(item) = item {
-						if !first {
-							out += &sep;
-						}
-						first = false;
-						out += &item;
-					} else {
-						throw!(RuntimeError("in std.join all items should be strings".into()));
+			let mut first = true;
+			for item in arr.iter() {
+				let item = item?.clone();
+				if let Val::Str(item) = item {
+					if !first {
+						out += &sep;
 					}
+					first = false;
+					out += &item;
+				} else {
+					throw!(RuntimeError(
+						"in std.join all items should be strings".into()
+					));
 				}
+			}
 
-				Val::Str(out.into())
-			},
-			_ => unreachable!()
-		})
+			IndexableVal::Str(out.into())
+		}
 	})
 }
 
-fn builtin_escape_string_json(
-	context: Context,
-	_loc: &ExprLocation,
-	args: &ArgsDesc,
-) -> Result<Val> {
-	parse_args!(context, "escapeStringJson", args, 1, [
-		0, str_: ty!(string) => Val::Str;
-	], {
-		Ok(Val::Str(escape_string_json(&str_).into()))
-	})
+#[jrsonnet_macros::builtin]
+fn builtin_escape_string_json(str_: IStr) -> Result<String> {
+	Ok(escape_string_json(&str_))
 }
 
-fn builtin_manifest_json_ex(context: Context, _loc: &ExprLocation, args: &ArgsDesc) -> Result<Val> {
-	parse_args!(context, "manifestJsonEx", args, 2, [
-		0, value: ty!(any);
-		1, indent: ty!(string) => Val::Str;
-	], {
-		Ok(Val::Str(manifest_json_ex(&value, &ManifestJsonOptions {
+#[jrsonnet_macros::builtin]
+fn builtin_manifest_json_ex(value: Any, indent: IStr) -> Result<String> {
+	manifest_json_ex(
+		&value.0,
+		&ManifestJsonOptions {
 			padding: &indent,
 			mtype: ManifestType::Std,
-		})?.into()))
-	})
+		},
+	)
 }
 
+#[jrsonnet_macros::builtin]
 fn builtin_manifest_yaml_doc(
-	context: Context,
-	_loc: &ExprLocation,
-	args: &ArgsDesc,
-) -> Result<Val> {
-	parse_args!(context, "manifestYamlDoc", args, 3, [
-		0, value: ty!(any);
-		1, indent_array_in_object: ty!(boolean) => Val::Bool;
-		2, quote_keys: ty!(boolean) => Val::Bool;
-	], {
-		Ok(Val::Str(manifest_yaml_ex(&value, &ManifestYamlOptions {
+	value: Any,
+	indent_array_in_object: bool,
+	quote_keys: bool,
+) -> Result<String> {
+	manifest_yaml_ex(
+		&value.0,
+		&ManifestYamlOptions {
 			padding: "  ",
 			arr_element_padding: if indent_array_in_object { "  " } else { "" },
 			quote_keys,
-		})?.into()))
-	})
+		},
+	)
 }
 
-fn builtin_reverse(context: Context, _loc: &ExprLocation, args: &ArgsDesc) -> Result<Val> {
-	parse_args!(context, "reverse", args, 1, [
-		0, value: ty!(array) => Val::Arr;
-	], {
-		Ok(Val::Arr(value.reversed()))
-	})
+#[jrsonnet_macros::builtin]
+fn builtin_reverse(value: ArrValue) -> Result<ArrValue> {
+	Ok(value.reversed())
 }
 
-fn builtin_id(context: Context, _loc: &ExprLocation, args: &ArgsDesc) -> Result<Val> {
-	parse_args!(context, "id", args, 1, [
-		0, v: ty!(any);
-	], {
-		Ok(v)
-	})
+#[jrsonnet_macros::builtin]
+const fn builtin_id(v: Any) -> Result<Any> {
+	Ok(v)
 }
 
-fn builtin_str_replace(context: Context, _loc: &ExprLocation, args: &ArgsDesc) -> Result<Val> {
-	parse_args!(context, "strReplace", args, 3, [
-		0, str: ty!(string) => Val::Str;
-		1, from: ty!(string) => Val::Str;
-		2, to: ty!(string) => Val::Str;
-	], {
-		Ok(Val::Str(str.replace(&from as &str, &to as &str).into()))
-	})
+#[jrsonnet_macros::builtin]
+fn builtin_str_replace(str: String, from: IStr, to: IStr) -> Result<String> {
+	Ok(str.replace(&from as &str, &to as &str))
 }
-
-fn builtin_splitlimit(context: Context, _loc: &ExprLocation, args: &ArgsDesc) -> Result<Val> {
-	parse_args!(context, "splitLimit", args, 3, [
-		0, str: ty!(string) => Val::Str;
-		1, c: ty!(char) => Val::Str;
-		2, maxsplits: ty!(number) => Val::Num;
-	], {
-		let maxsplits = maxsplits as isize;
-		let c = c.chars().next().unwrap();
 
-		let out: Vec<Val> = if maxsplits == -1 {
-			str.split(c).map(|s| Val::Str(s.into())).collect()
-		} else {
-			str.splitn(maxsplits as usize + 1, c).map(|s| Val::Str(s.into())).collect()
-		};
-
-		Ok(Val::Arr(out.into()))
-	})
+#[jrsonnet_macros::builtin]
+fn builtin_splitlimit(str: IStr, c: char, maxsplits: Either<usize, M1>) -> Result<VecVal> {
+	Ok(VecVal(match maxsplits {
+		Either::Left(n) => str.splitn(n + 1, c).map(|s| Val::Str(s.into())).collect(),
+		Either::Right(_) => str.split(c).map(|s| Val::Str(s.into())).collect(),
+	}))
 }
 
-fn builtin_ascii_upper(context: Context, _loc: &ExprLocation, args: &ArgsDesc) -> Result<Val> {
-	parse_args!(context, "asciiUpper", args, 1, [
-		0, str: ty!(string) => Val::Str;
-	], {
-		Ok(Val::Str(str.to_ascii_uppercase().into()))
-	})
+#[jrsonnet_macros::builtin]
+fn builtin_ascii_upper(str: IStr) -> Result<String> {
+	Ok(str.to_ascii_uppercase())
 }
 
-fn builtin_ascii_lower(context: Context, _loc: &ExprLocation, args: &ArgsDesc) -> Result<Val> {
-	parse_args!(context, "asciiLower", args, 1, [
-		0, str: ty!(string) => Val::Str;
-	], {
-		Ok(Val::Str(str.to_ascii_lowercase().into()))
-	})
+#[jrsonnet_macros::builtin]
+fn builtin_ascii_lower(str: IStr) -> Result<String> {
+	Ok(str.to_ascii_lowercase())
 }
 
-fn builtin_member(context: Context, _loc: &ExprLocation, args: &ArgsDesc) -> Result<Val> {
-	parse_args!(context, "member", args, 2, [
-		0, arr: ty!((array | string));
-		1, x: ty!(any);
-	], {
-		match arr {
-			Val::Str(s) => {
-				let x = x.try_cast_str("x should be string")?;
-				Ok(Val::Bool(!x.is_empty() && s.contains(&*x)))
-			}
-			Val::Arr(a) => {
-				for item in a.iter() {
-					let item = item?;
-					if equals(&item, &x)? {
-						return Ok(Val::Bool(true));
-					}
+#[jrsonnet_macros::builtin]
+fn builtin_member(arr: IndexableVal, x: Any) -> Result<bool> {
+	match arr {
+		IndexableVal::Str(s) => {
+			let x: IStr = IStr::try_from(x.0)?;
+			Ok(!x.is_empty() && s.contains(&*x))
+		}
+		IndexableVal::Arr(a) => {
+			for item in a.iter() {
+				let item = item?;
+				if equals(&item, &x.0)? {
+					return Ok(true);
 				}
-				Ok(Val::Bool(false))
 			}
-			_ => unreachable!(),
+			Ok(false)
 		}
-	})
+	}
 }
 
-fn builtin_count(context: Context, _loc: &ExprLocation, args: &ArgsDesc) -> Result<Val> {
-	parse_args!(context, "count", args, 2, [
-		0, arr: ty!(array) => Val::Arr;
-		1, x: ty!(any);
-	], {
-		let mut count = 0;
-		for item in arr.iter() {
-			let item = item?;
-			if equals(&item, &x)? {
-				count += 1;
-			}
+#[jrsonnet_macros::builtin]
+fn builtin_count(arr: Vec<Any>, v: Any) -> Result<usize> {
+	let mut count = 0;
+	for item in arr.iter() {
+		if equals(&item.0, &v.0)? {
+			count += 1;
 		}
-		Ok(Val::Num(count as f64))
-	})
+	}
+	Ok(count)
 }
 
 pub fn call_builtin(
modifiedcrates/jrsonnet-evaluator/src/builtin/sort.rsdiffbeforeafterboth
--- a/crates/jrsonnet-evaluator/src/builtin/sort.rs
+++ b/crates/jrsonnet-evaluator/src/builtin/sort.rs
@@ -1,6 +1,6 @@
 use crate::{
 	error::{Error, LocError, Result},
-	throw, Context, FuncVal, Val,
+	throw, FuncVal, Val,
 };
 use gcmodule::{Cc, Trace};
 
@@ -59,7 +59,7 @@
 	Ok(sort_type)
 }
 
-pub fn sort(ctx: Context, values: Cc<Vec<Val>>, key_getter: &FuncVal) -> Result<Cc<Vec<Val>>> {
+pub fn sort(values: Cc<Vec<Val>>, key_getter: &FuncVal) -> Result<Cc<Vec<Val>>> {
 	if values.len() <= 1 {
 		return Ok(values);
 	}
@@ -81,10 +81,7 @@
 	} else {
 		let mut vk = Vec::with_capacity(values.len());
 		for value in values.iter() {
-			vk.push((
-				value.clone(),
-				key_getter.evaluate_values(ctx.clone(), &[value.clone()])?,
-			));
+			vk.push((value.clone(), key_getter.evaluate_values(&[value.clone()])?));
 		}
 		let sort_type = get_sort_type(&mut vk, |v| &mut v.1)?;
 		match sort_type {
modifiedcrates/jrsonnet-evaluator/src/evaluate/mod.rsdiffbeforeafterboth
--- a/crates/jrsonnet-evaluator/src/evaluate/mod.rs
+++ b/crates/jrsonnet-evaluator/src/evaluate/mod.rs
@@ -1,3 +1,5 @@
+use std::convert::TryFrom;
+
 use crate::{
 	builtin::std_slice,
 	error::Error::*,
@@ -189,14 +191,18 @@
 ) -> Result<Option<IStr>> {
 	Ok(match field_name {
 		jrsonnet_parser::FieldName::Fixed(n) => Some(n.clone()),
-		jrsonnet_parser::FieldName::Dyn(expr) => {
-			let value = evaluate(context, expr)?;
-			if matches!(value, Val::Null) {
-				None
-			} else {
-				Some(value.try_cast_str("dynamic field name")?)
-			}
-		}
+		jrsonnet_parser::FieldName::Dyn(expr) => push_frame(
+			&expr.1,
+			|| "evaluating field name".to_string(),
+			|| {
+				let value = evaluate(context, expr)?;
+				if matches!(value, Val::Null) {
+					Ok(None)
+				} else {
+					Ok(Some(IStr::try_from(value)?))
+				}
+			},
+		)?,
 	})
 }
 
@@ -208,7 +214,7 @@
 	match specs.get(0) {
 		None => callback(context)?,
 		Some(CompSpec::IfSpec(IfSpecData(cond))) => {
-			if evaluate(context.clone(), cond)?.try_cast_bool("if spec")? {
+			if bool::try_from(evaluate(context.clone(), cond)?)? {
 				evaluate_comp(context, &specs[1..], callback)?
 			}
 		}
@@ -459,10 +465,7 @@
 	let assertion_result = push_frame(
 		&value.1,
 		|| "assertion condition".to_owned(),
-		|| {
-			evaluate(context.clone(), value)?
-				.try_cast_bool("assertion condition should be of type `boolean`")
-		},
+		|| bool::try_from(evaluate(context.clone(), value)?),
 	)?;
 	if !assertion_result {
 		push_frame(
@@ -633,11 +636,7 @@
 		ErrorStmt(e) => push_frame(
 			loc,
 			|| "error statement".to_owned(),
-			|| {
-				throw!(RuntimeError(
-					evaluate(context, e)?.try_cast_str("error text should be of type `string`")?,
-				))
-			},
+			|| throw!(RuntimeError(IStr::try_from(evaluate(context, e)?)?,)),
 		)?,
 		IfElse {
 			cond,
@@ -647,7 +646,7 @@
 			if push_frame(
 				loc,
 				|| "if condition".to_owned(),
-				|| evaluate(context.clone(), &cond.0)?.try_cast_bool("in if condition"),
+				|| bool::try_from(evaluate(context.clone(), &cond.0)?),
 			)? {
 				evaluate(context, cond_then)?
 			} else {
modifiedcrates/jrsonnet-evaluator/src/evaluate/operator.rsdiffbeforeafterboth
--- a/crates/jrsonnet-evaluator/src/evaluate/operator.rs
+++ b/crates/jrsonnet-evaluator/src/evaluate/operator.rs
@@ -1,3 +1,5 @@
+use std::convert::TryInto;
+
 use crate::builtin::std_format;
 use crate::{equals, evaluate, Context, Val};
 use crate::{error::Error::*, throw, Result};
@@ -46,7 +48,7 @@
 	use Val::*;
 	match (a, b) {
 		(Num(a), Num(b)) => Ok(Num(a % b)),
-		(Str(str), vals) => std_format(str.clone(), vals.clone()),
+		(Str(str), vals) => std_format(str.clone(), vals.clone())?.try_into(),
 		(a, b) => throw!(BinaryOperatorDoesNotOperateOnValues(
 			BinaryOpType::Mod,
 			a.value_type(),
modifiedcrates/jrsonnet-evaluator/src/function.rsdiffbeforeafterboth
--- a/crates/jrsonnet-evaluator/src/function.rs
+++ b/crates/jrsonnet-evaluator/src/function.rs
@@ -141,6 +141,93 @@
 	}
 }
 
+#[derive(Clone, Copy)]
+pub struct BuiltinParam {
+	pub name: &'static str,
+	pub has_default: bool,
+}
+
+/// You shouldn't probally use this function, use jrsonnet_macros::builtin instead
+///
+/// ## Parameters
+/// * `ctx`: used for passed argument expressions' execution and for body execution (if `body_ctx` is not set)
+/// * `params`: function parameters' definition
+/// * `args`: passed function arguments
+/// * `tailstrict`: if set to `true` function arguments are eagerly executed, otherwise - lazily
+pub fn parse_builtin_call<'k>(
+	ctx: Context,
+	params: &'static [BuiltinParam],
+	args: &'k ArgsDesc,
+	tailstrict: bool,
+) -> Result<GcHashMap<&'k str, LazyVal>> {
+	let mut passed_args = GcHashMap::with_capacity(params.len());
+	if args.unnamed.len() > params.len() {
+		throw!(TooManyArgsFunctionHas(params.len()))
+	}
+
+	let mut filled_args = 0;
+
+	for (id, arg) in args.unnamed.iter().enumerate() {
+		let name = params[id].name;
+		passed_args.insert(
+			name,
+			if tailstrict {
+				LazyVal::new_resolved(evaluate(ctx.clone(), arg)?)
+			} else {
+				LazyVal::new(TraceBox(Box::new(EvaluateLazyVal {
+					context: ctx.clone(),
+					expr: arg.clone(),
+				})))
+			},
+		);
+		filled_args += 1;
+	}
+
+	for (name, value) in args.named.iter() {
+		// FIXME: O(n) for arg existence check
+		if !params.iter().any(|p| p.name == name as &str) {
+			throw!(UnknownFunctionParameter((name as &str).to_owned()));
+		}
+		if passed_args
+			.insert(
+				name,
+				if tailstrict {
+					LazyVal::new_resolved(evaluate(ctx.clone(), value)?)
+				} else {
+					LazyVal::new(TraceBox(Box::new(EvaluateLazyVal {
+						context: ctx.clone(),
+						expr: value.clone(),
+					})))
+				},
+			)
+			.is_some()
+		{
+			throw!(BindingParameterASecondTime(name.clone()));
+		}
+		filled_args += 1;
+	}
+
+	if filled_args < params.len() {
+		for param in params.iter().filter(|p| p.has_default) {
+			if passed_args.contains_key(&param.name) {
+				continue;
+			}
+			filled_args += 1;
+		}
+
+		// Some args still wasn't filled
+		if filled_args != params.len() {
+			for param in params.iter().skip(args.unnamed.len()) {
+				if !args.named.iter().any(|a| &a.0 as &str == param.name) {
+					throw!(FunctionParameterNotBoundInCall(param.name.into()));
+				}
+			}
+			unreachable!();
+		}
+	}
+	Ok(passed_args)
+}
+
 pub fn parse_function_call_map(
 	ctx: Context,
 	body_ctx: Option<Context>,
@@ -201,12 +288,7 @@
 	Ok(body_ctx.unwrap_or(ctx).extend(out, None, None, None))
 }
 
-pub fn place_args(
-	ctx: Context,
-	body_ctx: Option<Context>,
-	params: &ParamsDesc,
-	args: &[Val],
-) -> Result<Context> {
+pub fn place_args(body_ctx: Context, params: &ParamsDesc, args: &[Val]) -> Result<Context> {
 	let mut out = GcHashMap::with_capacity(params.len());
 	let mut positioned_args = vec![None; params.0.len()];
 	for (id, arg) in args.iter().enumerate() {
@@ -220,14 +302,14 @@
 		let val = if let Some(arg) = &positioned_args[id] {
 			(*arg).clone()
 		} else if let Some(default) = &p.1 {
-			evaluate(ctx.clone(), default)?
+			evaluate(body_ctx.clone(), default)?
 		} else {
 			throw!(FunctionParameterNotBoundInCall(p.0.clone()));
 		};
 		out.insert(p.0.clone(), LazyVal::new_resolved(val));
 	}
 
-	Ok(body_ctx.unwrap_or(ctx).extend(out, None, None, None))
+	Ok(body_ctx.extend(out, None, None, None))
 }
 
 #[macro_export]
modifiedcrates/jrsonnet-evaluator/src/trace/mod.rsdiffbeforeafterboth
--- a/crates/jrsonnet-evaluator/src/trace/mod.rs
+++ b/crates/jrsonnet-evaluator/src/trace/mod.rs
@@ -122,6 +122,7 @@
 			.map(|el| &el.location)
 			.map(|location| {
 				use std::fmt::Write;
+				#[allow(clippy::option_if_let_else)]
 				if let Some(location) = location {
 					let mut resolved_path = self.resolver.resolve(&location.0);
 					// TODO: Process all trace elements first
deletedcrates/jrsonnet-evaluator/src/typed.rsdiffbeforeafterboth
--- a/crates/jrsonnet-evaluator/src/typed.rs
+++ /dev/null
@@ -1,265 +0,0 @@
-use std::{fmt::Display, rc::Rc};
-
-use crate::{
-	error::{Error, LocError, Result},
-	push_description_frame, Val,
-};
-use gcmodule::Trace;
-use jrsonnet_types::{ComplexValType, ValType};
-use thiserror::Error;
-
-#[macro_export]
-macro_rules! unwrap_type {
-	($desc: expr, $value: expr, $typ: expr => $match: path) => {{
-		use $crate::{push_stack_frame, typed::CheckType};
-		push_stack_frame(None, $desc, || Ok($typ.check(&$value)?))?;
-		match $value {
-			$match(v) => v,
-			_ => unreachable!(),
-		}
-	}};
-}
-
-#[derive(Debug, Error, Clone, Trace)]
-pub enum TypeError {
-	#[error("expected {0}, got {1}")]
-	ExpectedGot(ComplexValType, ValType),
-	#[error("missing property {0} from {1:?}")]
-	MissingProperty(#[skip_trace] Rc<str>, ComplexValType),
-	#[error("every failed from {0}:\n{1}")]
-	UnionFailed(ComplexValType, TypeLocErrorList),
-	#[error(
-		"number out of bounds: {0} not in {}..{}",
-		.1.map(|v|v.to_string()).unwrap_or_else(|| "".to_owned()),
-		.2.map(|v|v.to_string()).unwrap_or_else(|| "".to_owned()),
-	)]
-	BoundsFailed(f64, Option<f64>, Option<f64>),
-}
-impl From<TypeError> for LocError {
-	fn from(e: TypeError) -> Self {
-		Error::TypeError(e.into()).into()
-	}
-}
-
-#[derive(Debug, Clone, Trace)]
-pub struct TypeLocError(Box<TypeError>, ValuePathStack);
-impl From<TypeError> for TypeLocError {
-	fn from(e: TypeError) -> Self {
-		Self(Box::new(e), ValuePathStack(Vec::new()))
-	}
-}
-impl From<TypeLocError> for LocError {
-	fn from(e: TypeLocError) -> Self {
-		Error::TypeError(e).into()
-	}
-}
-impl Display for TypeLocError {
-	fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
-		write!(f, "{}", self.0)?;
-		if !(self.1).0.is_empty() {
-			write!(f, " at {}", self.1)?;
-		}
-		Ok(())
-	}
-}
-
-#[derive(Debug, Clone, Trace)]
-pub struct TypeLocErrorList(Vec<TypeLocError>);
-impl Display for TypeLocErrorList {
-	fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
-		use std::fmt::Write;
-		let mut out = String::new();
-		for (i, err) in self.0.iter().enumerate() {
-			if i != 0 {
-				writeln!(f)?;
-			}
-			out.clear();
-			write!(out, "{}", err)?;
-
-			for (i, line) in out.lines().enumerate() {
-				if line.trim().is_empty() {
-					continue;
-				}
-				if i != 0 {
-					writeln!(f)?;
-					write!(f, "    ")?;
-				} else {
-					write!(f, "  - ")?;
-				}
-				write!(f, "{}", line)?;
-			}
-		}
-		Ok(())
-	}
-}
-
-fn push_type_description(
-	error_reason: impl Fn() -> String,
-	path: impl Fn() -> ValuePathItem,
-	item: impl Fn() -> Result<()>,
-) -> Result<()> {
-	push_description_frame(error_reason, || match item() {
-		Ok(_) => Ok(()),
-		Err(mut e) => {
-			if let Error::TypeError(e) = &mut e.error_mut() {
-				(e.1).0.push(path())
-			}
-			Err(e)
-		}
-	})
-}
-
-// TODO: check_fast for fast path of union type checking
-pub trait CheckType {
-	fn check(&self, value: &Val) -> Result<()>;
-}
-
-impl CheckType for ValType {
-	fn check(&self, value: &Val) -> Result<()> {
-		let got = value.value_type();
-		if got != *self {
-			let loc_error: TypeLocError = TypeError::ExpectedGot((*self).into(), got).into();
-			return Err(loc_error.into());
-		}
-		Ok(())
-	}
-}
-
-#[derive(Clone, Debug, Trace)]
-enum ValuePathItem {
-	Field(#[skip_trace] Rc<str>),
-	Index(u64),
-}
-impl Display for ValuePathItem {
-	fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
-		match self {
-			Self::Field(name) => write!(f, ".{}", name)?,
-			Self::Index(idx) => write!(f, "[{}]", idx)?,
-		}
-		Ok(())
-	}
-}
-
-#[derive(Clone, Debug, Trace)]
-struct ValuePathStack(Vec<ValuePathItem>);
-impl Display for ValuePathStack {
-	fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
-		write!(f, "self")?;
-		for elem in self.0.iter().rev() {
-			write!(f, "{}", elem)?;
-		}
-		Ok(())
-	}
-}
-
-impl CheckType for ComplexValType {
-	fn check(&self, value: &Val) -> Result<()> {
-		match self {
-			Self::Any => Ok(()),
-			Self::Simple(s) => s.check(value),
-			Self::Char => match value {
-				Val::Str(s) if s.len() == 1 || s.chars().count() == 1 => Ok(()),
-				v => Err(TypeError::ExpectedGot(self.clone(), v.value_type()).into()),
-			},
-			Self::BoundedNumber(from, to) => {
-				if let Val::Num(n) = value {
-					if from.map(|from| from > *n).unwrap_or(false)
-						|| to.map(|to| to <= *n).unwrap_or(false)
-					{
-						return Err(TypeError::BoundsFailed(*n, *from, *to).into());
-					}
-					Ok(())
-				} else {
-					Err(TypeError::ExpectedGot(self.clone(), value.value_type()).into())
-				}
-			}
-			Self::Array(elem_type) => match value {
-				Val::Arr(a) => {
-					for (i, item) in a.iter().enumerate() {
-						push_type_description(
-							|| format!("array index {}", i),
-							|| ValuePathItem::Index(i as u64),
-							|| elem_type.check(&item.clone()?),
-						)?;
-					}
-					Ok(())
-				}
-				v => Err(TypeError::ExpectedGot(self.clone(), v.value_type()).into()),
-			},
-			Self::ArrayRef(elem_type) => match value {
-				Val::Arr(a) => {
-					for (i, item) in a.iter().enumerate() {
-						push_type_description(
-							|| format!("array index {}", i),
-							|| ValuePathItem::Index(i as u64),
-							|| elem_type.check(&item.clone()?),
-						)?;
-					}
-					Ok(())
-				}
-				v => Err(TypeError::ExpectedGot(self.clone(), v.value_type()).into()),
-			},
-			Self::ObjectRef(elems) => match value {
-				Val::Obj(obj) => {
-					for (k, v) in elems.iter() {
-						if let Some(got_v) = obj.get((*k).into())? {
-							push_type_description(
-								|| format!("property {}", k),
-								|| ValuePathItem::Field((*k).into()),
-								|| v.check(&got_v),
-							)?
-						} else {
-							return Err(
-								TypeError::MissingProperty((*k).into(), self.clone()).into()
-							);
-						}
-					}
-					Ok(())
-				}
-				v => Err(TypeError::ExpectedGot(self.clone(), v.value_type()).into()),
-			},
-			Self::Union(types) => {
-				let mut errors = Vec::new();
-				for ty in types.iter() {
-					match ty.check(value) {
-						Ok(()) => {
-							return Ok(());
-						}
-						Err(e) => match e.error() {
-							Error::TypeError(e) => errors.push(e.clone()),
-							_ => return Err(e),
-						},
-					}
-				}
-				Err(TypeError::UnionFailed(self.clone(), TypeLocErrorList(errors)).into())
-			}
-			Self::UnionRef(types) => {
-				let mut errors = Vec::new();
-				for ty in types.iter() {
-					match ty.check(value) {
-						Ok(()) => {
-							return Ok(());
-						}
-						Err(e) => match e.error() {
-							Error::TypeError(e) => errors.push(e.clone()),
-							_ => return Err(e),
-						},
-					}
-				}
-				Err(TypeError::UnionFailed(self.clone(), TypeLocErrorList(errors)).into())
-			}
-			Self::Sum(types) => {
-				for ty in types.iter() {
-					ty.check(value)?
-				}
-				Ok(())
-			}
-			Self::SumRef(types) => {
-				for ty in types.iter() {
-					ty.check(value)?
-				}
-				Ok(())
-			}
-		}
-	}
-}
addedcrates/jrsonnet-evaluator/src/typed/conversions.rsdiffbeforeafterboth
--- /dev/null
+++ b/crates/jrsonnet-evaluator/src/typed/conversions.rs
@@ -0,0 +1,508 @@
+use std::convert::{TryFrom, TryInto};
+
+use gcmodule::Cc;
+use jrsonnet_interner::IStr;
+use jrsonnet_types::{ComplexValType, ValType};
+
+use crate::{
+	error::{Error::*, LocError, Result},
+	throw,
+	typed::CheckType,
+	ArrValue, FuncVal, IndexableVal, ObjValue, Val,
+};
+
+pub trait Typed: TryFrom<Val, Error = LocError> + TryInto<Val, Error = LocError> {
+	const TYPE: &'static ComplexValType;
+}
+
+macro_rules! impl_int {
+	($($ty:ty)*) => {$(
+		impl Typed for $ty {
+			const TYPE: &'static ComplexValType =
+				&ComplexValType::BoundedNumber(Some(<$ty>::MIN as f64), Some(<$ty>::MAX as f64));
+		}
+		impl TryFrom<Val> for $ty {
+			type Error = LocError;
+
+			fn try_from(value: Val) -> Result<Self> {
+				<Self as Typed>::TYPE.check(&value)?;
+				match value {
+					Val::Num(n) => {
+						if n.trunc() != n {
+							throw!(RuntimeError(
+								format!(
+									"cannot convert number with fractional part to {}",
+									stringify!($ty)
+								)
+								.into()
+							))
+						}
+						Ok(n as $ty)
+					}
+					_ => unreachable!(),
+				}
+			}
+		}
+		impl TryFrom<$ty> for Val {
+			type Error = LocError;
+
+			fn try_from(value: $ty) -> Result<Self> {
+				Ok(Self::Num(value as f64))
+			}
+		}
+	)*};
+}
+
+impl_int!(i8 u8 i16 u16 i32 u32);
+
+impl Typed for f64 {
+	const TYPE: &'static ComplexValType = &ComplexValType::Simple(ValType::Num);
+}
+impl TryFrom<Val> for f64 {
+	type Error = LocError;
+
+	fn try_from(value: Val) -> Result<Self> {
+		<Self as Typed>::TYPE.check(&value)?;
+		match value {
+			Val::Num(n) => Ok(n),
+			_ => unreachable!(),
+		}
+	}
+}
+impl TryFrom<f64> for Val {
+	type Error = LocError;
+
+	fn try_from(value: f64) -> Result<Self> {
+		Ok(Self::Num(value))
+	}
+}
+
+pub struct PositiveF64(pub f64);
+impl Typed for PositiveF64 {
+	const TYPE: &'static ComplexValType = &ComplexValType::BoundedNumber(Some(0.0), None);
+}
+impl TryFrom<Val> for PositiveF64 {
+	type Error = LocError;
+
+	fn try_from(value: Val) -> Result<Self> {
+		<Self as Typed>::TYPE.check(&value)?;
+		match value {
+			Val::Num(n) => Ok(Self(n)),
+			_ => unreachable!(),
+		}
+	}
+}
+impl TryFrom<PositiveF64> for Val {
+	type Error = LocError;
+
+	fn try_from(value: PositiveF64) -> Result<Self> {
+		Ok(Self::Num(value.0))
+	}
+}
+
+impl Typed for usize {
+	// It is possible to store 54 bits of precision in f64, but leaving u32::MAX here for compatibility
+	const TYPE: &'static ComplexValType =
+		&ComplexValType::BoundedNumber(Some(0.0), Some(4294967295.0));
+}
+impl TryFrom<Val> for usize {
+	type Error = LocError;
+
+	fn try_from(value: Val) -> Result<Self> {
+		<Self as Typed>::TYPE.check(&value)?;
+		match value {
+			Val::Num(n) => {
+				if n.trunc() != n {
+					throw!(RuntimeError(
+						"cannot convert number with fractional part to usize".into()
+					))
+				}
+				Ok(n as Self)
+			}
+			_ => unreachable!(),
+		}
+	}
+}
+impl TryFrom<usize> for Val {
+	type Error = LocError;
+
+	fn try_from(value: usize) -> Result<Self> {
+		if value > u32::MAX as usize {
+			throw!(RuntimeError("number is too large".into()))
+		}
+		Ok(Self::Num(value as f64))
+	}
+}
+
+impl Typed for IStr {
+	const TYPE: &'static ComplexValType = &ComplexValType::Simple(ValType::Str);
+}
+impl TryFrom<Val> for IStr {
+	type Error = LocError;
+
+	fn try_from(value: Val) -> Result<Self> {
+		<Self as Typed>::TYPE.check(&value)?;
+		match value {
+			Val::Str(s) => Ok(s),
+			_ => unreachable!(),
+		}
+	}
+}
+impl TryFrom<IStr> for Val {
+	type Error = LocError;
+
+	fn try_from(value: IStr) -> Result<Self> {
+		Ok(Self::Str(value))
+	}
+}
+
+impl Typed for String {
+	const TYPE: &'static ComplexValType = &ComplexValType::Simple(ValType::Str);
+}
+impl TryFrom<Val> for String {
+	type Error = LocError;
+
+	fn try_from(value: Val) -> Result<Self> {
+		<Self as Typed>::TYPE.check(&value)?;
+		match value {
+			Val::Str(s) => Ok(s.to_string()),
+			_ => unreachable!(),
+		}
+	}
+}
+impl TryFrom<String> for Val {
+	type Error = LocError;
+
+	fn try_from(value: String) -> Result<Self> {
+		Ok(Self::Str(value.into()))
+	}
+}
+
+impl Typed for char {
+	const TYPE: &'static ComplexValType = &ComplexValType::Char;
+}
+impl TryFrom<Val> for char {
+	type Error = LocError;
+
+	fn try_from(value: Val) -> Result<Self> {
+		<Self as Typed>::TYPE.check(&value)?;
+		match value {
+			Val::Str(s) => Ok(s.chars().next().unwrap()),
+			_ => unreachable!(),
+		}
+	}
+}
+impl TryFrom<char> for Val {
+	type Error = LocError;
+
+	fn try_from(value: char) -> Result<Self> {
+		Ok(Self::Str(value.to_string().into()))
+	}
+}
+
+impl<T> Typed for Vec<T>
+where
+	T: Typed,
+	T: TryFrom<Val, Error = LocError>,
+	T: TryInto<Val, Error = LocError>,
+{
+	const TYPE: &'static ComplexValType = &ComplexValType::ArrayRef(T::TYPE);
+}
+impl<T> TryFrom<Val> for Vec<T>
+where
+	T: Typed,
+	T: TryFrom<Val, Error = LocError>,
+	T: TryInto<Val, Error = LocError>,
+{
+	type Error = LocError;
+
+	fn try_from(value: Val) -> Result<Self> {
+		<Self as Typed>::TYPE.check(&value)?;
+		match value {
+			Val::Arr(a) => {
+				let mut o = Self::with_capacity(a.len());
+				for i in a.iter() {
+					o.push(T::try_from(i?)?);
+				}
+				Ok(o)
+			}
+			_ => unreachable!(),
+		}
+	}
+}
+impl<T> TryFrom<Vec<T>> for Val
+where
+	T: Typed,
+	T: TryFrom<Self, Error = LocError>,
+	T: TryInto<Self, Error = LocError>,
+{
+	type Error = LocError;
+
+	fn try_from(value: Vec<T>) -> Result<Self> {
+		let mut o = Vec::with_capacity(value.len());
+		for i in value {
+			o.push(i.try_into()?);
+		}
+		Ok(Self::Arr(o.into()))
+	}
+}
+
+/// To be used in Vec<Any>
+/// Regular Val can't be used here, because it has wrong TryFrom::Error type
+pub struct Any(pub Val);
+
+impl Typed for Any {
+	const TYPE: &'static ComplexValType = &ComplexValType::Any;
+}
+impl TryFrom<Val> for Any {
+	type Error = LocError;
+
+	fn try_from(value: Val) -> Result<Self> {
+		Ok(Self(value))
+	}
+}
+impl TryFrom<Any> for Val {
+	type Error = LocError;
+
+	fn try_from(value: Any) -> Result<Self> {
+		Ok(value.0)
+	}
+}
+
+/// Specialization, provides faster TryFrom<VecVal> for Val
+pub struct VecVal(pub Vec<Val>);
+
+impl Typed for VecVal {
+	const TYPE: &'static ComplexValType = &ComplexValType::Simple(ValType::Arr);
+}
+impl TryFrom<Val> for VecVal {
+	type Error = LocError;
+
+	fn try_from(value: Val) -> Result<Self> {
+		<Self as Typed>::TYPE.check(&value)?;
+		match value {
+			Val::Arr(a) => Ok(Self(a.evaluated()?.to_vec())),
+			_ => unreachable!(),
+		}
+	}
+}
+impl TryFrom<VecVal> for Val {
+	type Error = LocError;
+
+	fn try_from(value: VecVal) -> Result<Self> {
+		Ok(Self::Arr(value.0.into()))
+	}
+}
+
+pub struct M1;
+impl Typed for M1 {
+	const TYPE: &'static ComplexValType = &ComplexValType::BoundedNumber(Some(-1.0), Some(-1.0));
+}
+impl TryFrom<Val> for M1 {
+	type Error = LocError;
+
+	fn try_from(value: Val) -> Result<Self> {
+		<Self as Typed>::TYPE.check(&value)?;
+		Ok(Self)
+	}
+}
+impl TryFrom<M1> for Val {
+	type Error = LocError;
+
+	fn try_from(_: M1) -> Result<Self> {
+		Ok(Self::Num(-1.0))
+	}
+}
+
+pub enum Either<A, B> {
+	Left(A),
+	Right(B),
+}
+
+impl<A, B> Either<A, B> {
+	pub fn to_left(self, f: impl FnOnce(B) -> A) -> A {
+		match self {
+			Either::Left(l) => l,
+			Either::Right(r) => f(r),
+		}
+	}
+	#[allow(clippy::missing_const_for_fn)]
+	pub fn left(self) -> Option<A> {
+		match self {
+			Either::Left(a) => Some(a),
+			Either::Right(_) => None,
+		}
+	}
+}
+
+impl<A, B> Typed for Either<A, B>
+where
+	A: Typed,
+	B: Typed,
+{
+	const TYPE: &'static ComplexValType = &ComplexValType::UnionRef(&[A::TYPE, B::TYPE]);
+}
+impl<A, B> TryFrom<Val> for Either<A, B>
+where
+	A: Typed,
+	B: Typed,
+{
+	type Error = LocError;
+
+	fn try_from(value: Val) -> Result<Self> {
+		if A::TYPE.check(&value).is_ok() {
+			A::try_from(value).map(Self::Left)
+		} else if B::TYPE.check(&value).is_ok() {
+			B::try_from(value).map(Self::Right)
+		} else {
+			<Self as Typed>::TYPE.check(&value)?;
+			unreachable!()
+		}
+	}
+}
+impl<A, B> TryFrom<Either<A, B>> for Val
+where
+	A: Typed,
+	B: Typed,
+{
+	type Error = LocError;
+
+	fn try_from(value: Either<A, B>) -> Result<Self> {
+		match value {
+			Either::Left(a) => a.try_into(),
+			Either::Right(b) => b.try_into(),
+		}
+	}
+}
+
+impl Typed for ArrValue {
+	const TYPE: &'static ComplexValType = &ComplexValType::Simple(ValType::Arr);
+}
+impl TryFrom<Val> for ArrValue {
+	type Error = LocError;
+
+	fn try_from(value: Val) -> Result<Self> {
+		<Self as Typed>::TYPE.check(&value)?;
+		match value {
+			Val::Arr(a) => Ok(a),
+			_ => unreachable!(),
+		}
+	}
+}
+impl TryFrom<ArrValue> for Val {
+	type Error = LocError;
+
+	fn try_from(value: ArrValue) -> Result<Self> {
+		Ok(Self::Arr(value))
+	}
+}
+
+impl Typed for Cc<FuncVal> {
+	const TYPE: &'static ComplexValType = &ComplexValType::Simple(ValType::Func);
+}
+impl TryFrom<Val> for Cc<FuncVal> {
+	type Error = LocError;
+
+	fn try_from(value: Val) -> Result<Self> {
+		<Self as Typed>::TYPE.check(&value)?;
+		match value {
+			Val::Func(a) => Ok(a),
+			_ => unreachable!(),
+		}
+	}
+}
+impl TryFrom<Cc<FuncVal>> for Val {
+	type Error = LocError;
+
+	fn try_from(value: Cc<FuncVal>) -> Result<Self> {
+		Ok(Self::Func(value))
+	}
+}
+impl Typed for ObjValue {
+	const TYPE: &'static ComplexValType = &ComplexValType::Simple(ValType::Obj);
+}
+impl TryFrom<Val> for ObjValue {
+	type Error = LocError;
+
+	fn try_from(value: Val) -> Result<Self> {
+		<Self as Typed>::TYPE.check(&value)?;
+		match value {
+			Val::Obj(a) => Ok(a),
+			_ => unreachable!(),
+		}
+	}
+}
+impl TryFrom<ObjValue> for Val {
+	type Error = LocError;
+
+	fn try_from(value: ObjValue) -> Result<Self> {
+		Ok(Self::Obj(value))
+	}
+}
+
+impl Typed for bool {
+	const TYPE: &'static ComplexValType = &ComplexValType::Simple(ValType::Bool);
+}
+impl TryFrom<Val> for bool {
+	type Error = LocError;
+
+	fn try_from(value: Val) -> Result<Self> {
+		<Self as Typed>::TYPE.check(&value)?;
+		match value {
+			Val::Bool(a) => Ok(a),
+			_ => unreachable!(),
+		}
+	}
+}
+impl TryFrom<bool> for Val {
+	type Error = LocError;
+
+	fn try_from(value: bool) -> Result<Self> {
+		Ok(Self::Bool(value))
+	}
+}
+
+impl Typed for IndexableVal {
+	const TYPE: &'static ComplexValType = &ComplexValType::UnionRef(&[
+		&ComplexValType::Simple(ValType::Arr),
+		&ComplexValType::Simple(ValType::Str),
+	]);
+}
+impl TryFrom<Val> for IndexableVal {
+	type Error = LocError;
+
+	fn try_from(value: Val) -> Result<Self> {
+		<Self as Typed>::TYPE.check(&value)?;
+		value.into_indexable()
+	}
+}
+impl TryFrom<IndexableVal> for Val {
+	type Error = LocError;
+
+	fn try_from(value: IndexableVal) -> Result<Self> {
+		match value {
+			IndexableVal::Str(s) => Ok(Self::Str(s)),
+			IndexableVal::Arr(a) => Ok(Self::Arr(a)),
+		}
+	}
+}
+
+pub struct Null;
+impl Typed for Null {
+	const TYPE: &'static ComplexValType = &ComplexValType::Simple(ValType::Null);
+}
+impl TryFrom<Val> for Null {
+	type Error = LocError;
+
+	fn try_from(value: Val) -> Result<Self> {
+		<Self as Typed>::TYPE.check(&value)?;
+		Ok(Self)
+	}
+}
+impl TryFrom<Null> for Val {
+	type Error = LocError;
+
+	fn try_from(_: Null) -> Result<Self> {
+		Ok(Self::Null)
+	}
+}
addedcrates/jrsonnet-evaluator/src/typed/mod.rsdiffbeforeafterboth
--- /dev/null
+++ b/crates/jrsonnet-evaluator/src/typed/mod.rs
@@ -0,0 +1,268 @@
+use std::{fmt::Display, rc::Rc};
+
+mod conversions;
+pub use conversions::*;
+
+use crate::{
+	error::{Error, LocError, Result},
+	push_description_frame, Val,
+};
+use gcmodule::Trace;
+use jrsonnet_types::{ComplexValType, ValType};
+use thiserror::Error;
+
+#[macro_export]
+macro_rules! unwrap_type {
+	($desc: expr, $value: expr, $typ: expr => $match: path) => {{
+		use $crate::{push_stack_frame, typed::CheckType};
+		push_stack_frame(None, $desc, || Ok($typ.check(&$value)?))?;
+		match $value {
+			$match(v) => v,
+			_ => unreachable!(),
+		}
+	}};
+}
+
+#[derive(Debug, Error, Clone, Trace)]
+pub enum TypeError {
+	#[error("expected {0}, got {1}")]
+	ExpectedGot(ComplexValType, ValType),
+	#[error("missing property {0} from {1:?}")]
+	MissingProperty(#[skip_trace] Rc<str>, ComplexValType),
+	#[error("every failed from {0}:\n{1}")]
+	UnionFailed(ComplexValType, TypeLocErrorList),
+	#[error(
+		"number out of bounds: {0} not in {}..{}",
+		.1.map(|v|v.to_string()).unwrap_or_else(|| "".to_owned()),
+		.2.map(|v|v.to_string()).unwrap_or_else(|| "".to_owned()),
+	)]
+	BoundsFailed(f64, Option<f64>, Option<f64>),
+}
+impl From<TypeError> for LocError {
+	fn from(e: TypeError) -> Self {
+		Error::TypeError(e.into()).into()
+	}
+}
+
+#[derive(Debug, Clone, Trace)]
+pub struct TypeLocError(Box<TypeError>, ValuePathStack);
+impl From<TypeError> for TypeLocError {
+	fn from(e: TypeError) -> Self {
+		Self(Box::new(e), ValuePathStack(Vec::new()))
+	}
+}
+impl From<TypeLocError> for LocError {
+	fn from(e: TypeLocError) -> Self {
+		Error::TypeError(e).into()
+	}
+}
+impl Display for TypeLocError {
+	fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
+		write!(f, "{}", self.0)?;
+		if !(self.1).0.is_empty() {
+			write!(f, " at {}", self.1)?;
+		}
+		Ok(())
+	}
+}
+
+#[derive(Debug, Clone, Trace)]
+pub struct TypeLocErrorList(Vec<TypeLocError>);
+impl Display for TypeLocErrorList {
+	fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
+		use std::fmt::Write;
+		let mut out = String::new();
+		for (i, err) in self.0.iter().enumerate() {
+			if i != 0 {
+				writeln!(f)?;
+			}
+			out.clear();
+			write!(out, "{}", err)?;
+
+			for (i, line) in out.lines().enumerate() {
+				if line.trim().is_empty() {
+					continue;
+				}
+				if i != 0 {
+					writeln!(f)?;
+					write!(f, "    ")?;
+				} else {
+					write!(f, "  - ")?;
+				}
+				write!(f, "{}", line)?;
+			}
+		}
+		Ok(())
+	}
+}
+
+fn push_type_description(
+	error_reason: impl Fn() -> String,
+	path: impl Fn() -> ValuePathItem,
+	item: impl Fn() -> Result<()>,
+) -> Result<()> {
+	push_description_frame(error_reason, || match item() {
+		Ok(_) => Ok(()),
+		Err(mut e) => {
+			if let Error::TypeError(e) = &mut e.error_mut() {
+				(e.1).0.push(path())
+			}
+			Err(e)
+		}
+	})
+}
+
+// TODO: check_fast for fast path of union type checking
+pub trait CheckType {
+	fn check(&self, value: &Val) -> Result<()>;
+}
+
+impl CheckType for ValType {
+	fn check(&self, value: &Val) -> Result<()> {
+		let got = value.value_type();
+		if got != *self {
+			let loc_error: TypeLocError = TypeError::ExpectedGot((*self).into(), got).into();
+			return Err(loc_error.into());
+		}
+		Ok(())
+	}
+}
+
+#[derive(Clone, Debug, Trace)]
+enum ValuePathItem {
+	Field(#[skip_trace] Rc<str>),
+	Index(u64),
+}
+impl Display for ValuePathItem {
+	fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
+		match self {
+			Self::Field(name) => write!(f, ".{}", name)?,
+			Self::Index(idx) => write!(f, "[{}]", idx)?,
+		}
+		Ok(())
+	}
+}
+
+#[derive(Clone, Debug, Trace)]
+struct ValuePathStack(Vec<ValuePathItem>);
+impl Display for ValuePathStack {
+	fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
+		write!(f, "self")?;
+		for elem in self.0.iter().rev() {
+			write!(f, "{}", elem)?;
+		}
+		Ok(())
+	}
+}
+
+impl CheckType for ComplexValType {
+	fn check(&self, value: &Val) -> Result<()> {
+		match self {
+			Self::Any => Ok(()),
+			Self::Simple(s) => s.check(value),
+			Self::Char => match value {
+				Val::Str(s) if s.len() == 1 || s.chars().count() == 1 => Ok(()),
+				v => Err(TypeError::ExpectedGot(self.clone(), v.value_type()).into()),
+			},
+			Self::BoundedNumber(from, to) => {
+				if let Val::Num(n) = value {
+					if from.map(|from| from > *n).unwrap_or(false)
+						|| to.map(|to| to < *n).unwrap_or(false)
+					{
+						return Err(TypeError::BoundsFailed(*n, *from, *to).into());
+					}
+					Ok(())
+				} else {
+					Err(TypeError::ExpectedGot(self.clone(), value.value_type()).into())
+				}
+			}
+			Self::Array(elem_type) => match value {
+				Val::Arr(a) => {
+					for (i, item) in a.iter().enumerate() {
+						push_type_description(
+							|| format!("array index {}", i),
+							|| ValuePathItem::Index(i as u64),
+							|| elem_type.check(&item.clone()?),
+						)?;
+					}
+					Ok(())
+				}
+				v => Err(TypeError::ExpectedGot(self.clone(), v.value_type()).into()),
+			},
+			Self::ArrayRef(elem_type) => match value {
+				Val::Arr(a) => {
+					for (i, item) in a.iter().enumerate() {
+						push_type_description(
+							|| format!("array index {}", i),
+							|| ValuePathItem::Index(i as u64),
+							|| elem_type.check(&item.clone()?),
+						)?;
+					}
+					Ok(())
+				}
+				v => Err(TypeError::ExpectedGot(self.clone(), v.value_type()).into()),
+			},
+			Self::ObjectRef(elems) => match value {
+				Val::Obj(obj) => {
+					for (k, v) in elems.iter() {
+						if let Some(got_v) = obj.get((*k).into())? {
+							push_type_description(
+								|| format!("property {}", k),
+								|| ValuePathItem::Field((*k).into()),
+								|| v.check(&got_v),
+							)?
+						} else {
+							return Err(
+								TypeError::MissingProperty((*k).into(), self.clone()).into()
+							);
+						}
+					}
+					Ok(())
+				}
+				v => Err(TypeError::ExpectedGot(self.clone(), v.value_type()).into()),
+			},
+			Self::Union(types) => {
+				let mut errors = Vec::new();
+				for ty in types.iter() {
+					match ty.check(value) {
+						Ok(()) => {
+							return Ok(());
+						}
+						Err(e) => match e.error() {
+							Error::TypeError(e) => errors.push(e.clone()),
+							_ => return Err(e),
+						},
+					}
+				}
+				Err(TypeError::UnionFailed(self.clone(), TypeLocErrorList(errors)).into())
+			}
+			Self::UnionRef(types) => {
+				let mut errors = Vec::new();
+				for ty in types.iter() {
+					match ty.check(value) {
+						Ok(()) => {
+							return Ok(());
+						}
+						Err(e) => match e.error() {
+							Error::TypeError(e) => errors.push(e.clone()),
+							_ => return Err(e),
+						},
+					}
+				}
+				Err(TypeError::UnionFailed(self.clone(), TypeLocErrorList(errors)).into())
+			}
+			Self::Sum(types) => {
+				for ty in types.iter() {
+					ty.check(value)?
+				}
+				Ok(())
+			}
+			Self::SumRef(types) => {
+				for ty in types.iter() {
+					ty.check(value)?
+				}
+				Ok(())
+			}
+		}
+	}
+}
modifiedcrates/jrsonnet-evaluator/src/val.rsdiffbeforeafterboth
before · crates/jrsonnet-evaluator/src/val.rs
1use crate::{2	builtin::{3		call_builtin,4		manifest::{5			manifest_json_ex, manifest_yaml_ex, ManifestJsonOptions, ManifestType,6			ManifestYamlOptions,7		},8	},9	cc_ptr_eq,10	error::{Error::*, LocError},11	evaluate,12	function::{parse_function_call, parse_function_call_map, place_args},13	gc::TraceBox,14	native::NativeCallback,15	throw, Context, ObjValue, Result,16};17use gcmodule::{Cc, Trace};18use jrsonnet_interner::IStr;19use jrsonnet_parser::{ArgsDesc, ExprLocation, LocExpr, ParamsDesc};20use jrsonnet_types::ValType;21use std::{cell::RefCell, collections::HashMap, fmt::Debug, rc::Rc};2223pub trait LazyValValue: Trace {24	fn get(self: Box<Self>) -> Result<Val>;25}2627#[derive(Trace)]28enum LazyValInternals {29	Computed(Val),30	Errored(LocError),31	Waiting(TraceBox<dyn LazyValValue>),32	Pending,33}3435#[derive(Clone, Trace)]36pub struct LazyVal(Cc<RefCell<LazyValInternals>>);37impl LazyVal {38	pub fn new(f: TraceBox<dyn LazyValValue>) -> Self {39		Self(Cc::new(RefCell::new(LazyValInternals::Waiting(f))))40	}41	pub fn new_resolved(val: Val) -> Self {42		Self(Cc::new(RefCell::new(LazyValInternals::Computed(val))))43	}44	pub fn evaluate(&self) -> Result<Val> {45		match &*self.0.borrow() {46			LazyValInternals::Computed(v) => return Ok(v.clone()),47			LazyValInternals::Errored(e) => return Err(e.clone()),48			LazyValInternals::Pending => return Err(RecursiveLazyValueEvaluation.into()),49			_ => (),50		};51		let value = if let LazyValInternals::Waiting(value) =52			std::mem::replace(&mut *self.0.borrow_mut(), LazyValInternals::Pending)53		{54			value55		} else {56			unreachable!()57		};58		let new_value = match value.0.get() {59			Ok(v) => v,60			Err(e) => {61				*self.0.borrow_mut() = LazyValInternals::Errored(e.clone());62				return Err(e);63			}64		};65		*self.0.borrow_mut() = LazyValInternals::Computed(new_value.clone());66		Ok(new_value)67	}68}6970impl Debug for LazyVal {71	fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {72		write!(f, "Lazy")73	}74}75impl PartialEq for LazyVal {76	fn eq(&self, other: &Self) -> bool {77		cc_ptr_eq(&self.0, &other.0)78	}79}8081#[derive(Debug, PartialEq, Trace)]82pub struct FuncDesc {83	pub name: IStr,84	pub ctx: Context,85	pub params: ParamsDesc,86	pub body: LocExpr,87}8889#[derive(Debug, Trace)]90pub enum FuncVal {91	/// Plain function implemented in jsonnet92	Normal(FuncDesc),93	/// Standard library function94	Intrinsic(IStr),95	/// Library functions implemented in native96	NativeExt(IStr, Cc<NativeCallback>),97}9899impl PartialEq for FuncVal {100	fn eq(&self, other: &Self) -> bool {101		match (self, other) {102			(Self::Normal(a), Self::Normal(b)) => a == b,103			(Self::Intrinsic(an), Self::Intrinsic(bn)) => an == bn,104			(Self::NativeExt(an, _), Self::NativeExt(bn, _)) => an == bn,105			(..) => false,106		}107	}108}109impl FuncVal {110	pub fn is_ident(&self) -> bool {111		matches!(&self, Self::Intrinsic(n) if n as &str == "id")112	}113	pub fn name(&self) -> IStr {114		match self {115			Self::Normal(normal) => normal.name.clone(),116			Self::Intrinsic(name) => format!("std.{}", name).into(),117			Self::NativeExt(n, _) => format!("native.{}", n).into(),118		}119	}120	pub fn evaluate(121		&self,122		call_ctx: Context,123		loc: &ExprLocation,124		args: &ArgsDesc,125		tailstrict: bool,126	) -> Result<Val> {127		match self {128			Self::Normal(func) => {129				let ctx = parse_function_call(130					call_ctx,131					func.ctx.clone(),132					&func.params,133					args,134					tailstrict,135				)?;136				evaluate(ctx, &func.body)137			}138			Self::Intrinsic(name) => call_builtin(call_ctx, loc, name, args),139			Self::NativeExt(_name, handler) => {140				let args =141					parse_function_call(call_ctx, Context::new(), &handler.params, args, true)?;142				let mut out_args = Vec::with_capacity(handler.params.len());143				for p in handler.params.0.iter() {144					out_args.push(args.binding(p.0.clone())?.evaluate()?);145				}146				Ok(handler.call(loc.0.clone(), &out_args)?)147			}148		}149	}150151	pub fn evaluate_map(152		&self,153		call_ctx: Context,154		args: &HashMap<IStr, Val>,155		tailstrict: bool,156	) -> Result<Val> {157		match self {158			Self::Normal(func) => {159				let ctx = parse_function_call_map(160					call_ctx,161					Some(func.ctx.clone()),162					&func.params,163					args,164					tailstrict,165				)?;166				evaluate(ctx, &func.body)167			}168			Self::Intrinsic(_) => todo!(),169			Self::NativeExt(_, _) => todo!(),170		}171	}172173	pub fn evaluate_values(&self, call_ctx: Context, args: &[Val]) -> Result<Val> {174		match self {175			Self::Normal(func) => {176				let ctx = place_args(call_ctx, Some(func.ctx.clone()), &func.params, args)?;177				evaluate(ctx, &func.body)178			}179			Self::Intrinsic(_) => todo!(),180			Self::NativeExt(_, _) => todo!(),181		}182	}183}184185#[derive(Clone)]186pub enum ManifestFormat {187	YamlStream(Box<ManifestFormat>),188	Yaml(usize),189	Json(usize),190	ToString,191	String,192}193194#[derive(Debug, Clone, Trace)]195#[force_tracking]196pub enum ArrValue {197	Lazy(Cc<Vec<LazyVal>>),198	Eager(Cc<Vec<Val>>),199	Extended(Box<(Self, Self)>),200}201impl ArrValue {202	pub fn new_eager() -> Self {203		Self::Eager(Cc::new(Vec::new()))204	}205206	pub fn len(&self) -> usize {207		match self {208			Self::Lazy(l) => l.len(),209			Self::Eager(e) => e.len(),210			Self::Extended(v) => v.0.len() + v.1.len(),211		}212	}213214	pub fn is_empty(&self) -> bool {215		self.len() == 0216	}217218	pub fn get(&self, index: usize) -> Result<Option<Val>> {219		match self {220			Self::Lazy(vec) => {221				if let Some(v) = vec.get(index) {222					Ok(Some(v.evaluate()?))223				} else {224					Ok(None)225				}226			}227			Self::Eager(vec) => Ok(vec.get(index).cloned()),228			Self::Extended(v) => {229				let a_len = v.0.len();230				if a_len > index {231					v.0.get(index)232				} else {233					v.1.get(index - a_len)234				}235			}236		}237	}238239	pub fn get_lazy(&self, index: usize) -> Option<LazyVal> {240		match self {241			Self::Lazy(vec) => vec.get(index).cloned(),242			Self::Eager(vec) => vec.get(index).cloned().map(LazyVal::new_resolved),243			Self::Extended(v) => {244				let a_len = v.0.len();245				if a_len > index {246					v.0.get_lazy(index)247				} else {248					v.1.get_lazy(index - a_len)249				}250			}251		}252	}253254	pub fn evaluated(&self) -> Result<Cc<Vec<Val>>> {255		Ok(match self {256			Self::Lazy(vec) => {257				let mut out = Vec::with_capacity(vec.len());258				for item in vec.iter() {259					out.push(item.evaluate()?);260				}261				Cc::new(out)262			}263			Self::Eager(vec) => vec.clone(),264			Self::Extended(_v) => {265				let mut out = Vec::with_capacity(self.len());266				for item in self.iter() {267					out.push(item?);268				}269				Cc::new(out)270			}271		})272	}273274	pub fn iter(&self) -> impl DoubleEndedIterator<Item = Result<Val>> + '_ {275		(0..self.len()).map(move |idx| match self {276			Self::Lazy(l) => l[idx].evaluate(),277			Self::Eager(e) => Ok(e[idx].clone()),278			Self::Extended(_) => self.get(idx).map(|e| e.unwrap()),279		})280	}281282	pub fn iter_lazy(&self) -> impl DoubleEndedIterator<Item = LazyVal> + '_ {283		(0..self.len()).map(move |idx| match self {284			Self::Lazy(l) => l[idx].clone(),285			Self::Eager(e) => LazyVal::new_resolved(e[idx].clone()),286			Self::Extended(_) => self.get_lazy(idx).unwrap(),287		})288	}289290	pub fn reversed(self) -> Self {291		match self {292			Self::Lazy(vec) => {293				let mut out = (&vec as &Vec<_>).clone();294				out.reverse();295				Self::Lazy(Cc::new(out))296			}297			Self::Eager(vec) => {298				let mut out = (&vec as &Vec<_>).clone();299				out.reverse();300				Self::Eager(Cc::new(out))301			}302			Self::Extended(b) => Self::Extended(Box::new((b.1.reversed(), b.0.reversed()))),303		}304	}305306	pub fn map(self, mapper: impl Fn(Val) -> Result<Val>) -> Result<Self> {307		let mut out = Vec::with_capacity(self.len());308309		for value in self.iter() {310			out.push(mapper(value?)?);311		}312313		Ok(Self::Eager(Cc::new(out)))314	}315316	pub fn filter(self, filter: impl Fn(&Val) -> Result<bool>) -> Result<Self> {317		let mut out = Vec::with_capacity(self.len());318319		for value in self.iter() {320			let value = value?;321			if filter(&value)? {322				out.push(value);323			}324		}325326		Ok(Self::Eager(Cc::new(out)))327	}328329	pub fn ptr_eq(a: &Self, b: &Self) -> bool {330		match (a, b) {331			(Self::Lazy(a), Self::Lazy(b)) => cc_ptr_eq(a, b),332			(Self::Eager(a), Self::Eager(b)) => cc_ptr_eq(a, b),333			_ => false,334		}335	}336}337338impl From<Vec<LazyVal>> for ArrValue {339	fn from(v: Vec<LazyVal>) -> Self {340		Self::Lazy(Cc::new(v))341	}342}343344impl From<Vec<Val>> for ArrValue {345	fn from(v: Vec<Val>) -> Self {346		Self::Eager(Cc::new(v))347	}348}349350pub enum IndexableVal {351	Str(IStr),352	Arr(ArrValue),353}354355#[derive(Debug, Clone, Trace)]356pub enum Val {357	Bool(bool),358	Null,359	Str(IStr),360	Num(f64),361	Arr(ArrValue),362	Obj(ObjValue),363	Func(Cc<FuncVal>),364}365366macro_rules! matches_unwrap {367	($e: expr, $p: pat, $r: expr) => {368		match $e {369			$p => $r,370			_ => panic!("no match"),371		}372	};373}374impl Val {375	/// Creates `Val::Num` after checking for numeric overflow.376	/// As numbers are `f64`, we can just check for their finity.377	pub fn new_checked_num(num: f64) -> Result<Self> {378		if num.is_finite() {379			Ok(Self::Num(num))380		} else {381			throw!(RuntimeError("overflow".into()))382		}383	}384385	pub fn assert_type(&self, context: &'static str, val_type: ValType) -> Result<()> {386		let this_type = self.value_type();387		if this_type != val_type {388			throw!(TypeMismatch(context, vec![val_type], this_type))389		} else {390			Ok(())391		}392	}393	pub fn unwrap_num(self) -> Result<f64> {394		Ok(matches_unwrap!(self, Self::Num(v), v))395	}396	pub fn unwrap_str(self) -> Result<IStr> {397		Ok(matches_unwrap!(self, Self::Str(v), v))398	}399	pub fn unwrap_arr(self) -> Result<ArrValue> {400		Ok(matches_unwrap!(self, Self::Arr(v), v))401	}402	pub fn unwrap_func(self) -> Result<Cc<FuncVal>> {403		Ok(matches_unwrap!(self, Self::Func(v), v))404	}405	pub fn try_cast_bool(self, context: &'static str) -> Result<bool> {406		self.assert_type(context, ValType::Bool)?;407		Ok(matches_unwrap!(self, Self::Bool(v), v))408	}409	pub fn try_cast_str(self, context: &'static str) -> Result<IStr> {410		self.assert_type(context, ValType::Str)?;411		Ok(matches_unwrap!(self, Self::Str(v), v))412	}413	pub fn try_cast_num(self, context: &'static str) -> Result<f64> {414		self.assert_type(context, ValType::Num)?;415		self.unwrap_num()416	}417	pub fn try_cast_nullable_num(self, context: &'static str) -> Result<Option<f64>> {418		Ok(match self {419			Val::Null => None,420			Val::Num(num) => Some(num),421			_ => throw!(TypeMismatch(422				context,423				vec![ValType::Null, ValType::Num],424				self.value_type()425			)),426		})427	}428	pub const fn value_type(&self) -> ValType {429		match self {430			Self::Str(..) => ValType::Str,431			Self::Num(..) => ValType::Num,432			Self::Arr(..) => ValType::Arr,433			Self::Obj(..) => ValType::Obj,434			Self::Bool(_) => ValType::Bool,435			Self::Null => ValType::Null,436			Self::Func(..) => ValType::Func,437		}438	}439440	pub fn to_string(&self) -> Result<IStr> {441		Ok(match self {442			Self::Bool(true) => "true".into(),443			Self::Bool(false) => "false".into(),444			Self::Null => "null".into(),445			Self::Str(s) => s.clone(),446			v => manifest_json_ex(447				v,448				&ManifestJsonOptions {449					padding: "",450					mtype: ManifestType::ToString,451				},452			)?453			.into(),454		})455	}456457	/// Expects value to be object, outputs (key, manifested value) pairs458	pub fn manifest_multi(&self, ty: &ManifestFormat) -> Result<Vec<(IStr, IStr)>> {459		let obj = match self {460			Self::Obj(obj) => obj,461			_ => throw!(MultiManifestOutputIsNotAObject),462		};463		let keys = obj.fields();464		let mut out = Vec::with_capacity(keys.len());465		for key in keys {466			let value = obj467				.get(key.clone())?468				.expect("item in object")469				.manifest(ty)?;470			out.push((key, value));471		}472		Ok(out)473	}474475	/// Expects value to be array, outputs manifested values476	pub fn manifest_stream(&self, ty: &ManifestFormat) -> Result<Vec<IStr>> {477		let arr = match self {478			Self::Arr(a) => a,479			_ => throw!(StreamManifestOutputIsNotAArray),480		};481		let mut out = Vec::with_capacity(arr.len());482		for i in arr.iter() {483			out.push(i?.manifest(ty)?);484		}485		Ok(out)486	}487488	pub fn manifest(&self, ty: &ManifestFormat) -> Result<IStr> {489		Ok(match ty {490			ManifestFormat::YamlStream(format) => {491				let arr = match self {492					Self::Arr(a) => a,493					_ => throw!(StreamManifestOutputIsNotAArray),494				};495				let mut out = String::new();496497				match format as &ManifestFormat {498					ManifestFormat::YamlStream(_) => throw!(StreamManifestOutputCannotBeRecursed),499					ManifestFormat::String => throw!(StreamManifestCannotNestString),500					_ => {}501				};502503				if !arr.is_empty() {504					for v in arr.iter() {505						out.push_str("---\n");506						out.push_str(&v?.manifest(format)?);507						out.push('\n');508					}509					out.push_str("...");510				}511512				out.into()513			}514			ManifestFormat::Yaml(padding) => self.to_yaml(*padding)?,515			ManifestFormat::Json(padding) => self.to_json(*padding)?,516			ManifestFormat::ToString => self.to_string()?,517			ManifestFormat::String => match self {518				Self::Str(s) => s.clone(),519				_ => throw!(StringManifestOutputIsNotAString),520			},521		})522	}523524	/// For manifestification525	pub fn to_json(&self, padding: usize) -> Result<IStr> {526		manifest_json_ex(527			self,528			&ManifestJsonOptions {529				padding: &" ".repeat(padding),530				mtype: if padding == 0 {531					ManifestType::Minify532				} else {533					ManifestType::Manifest534				},535			},536		)537		.map(|s| s.into())538	}539540	/// Calls `std.manifestJson`541	pub fn to_std_json(&self, padding: usize) -> Result<Rc<str>> {542		manifest_json_ex(543			self,544			&ManifestJsonOptions {545				padding: &" ".repeat(padding),546				mtype: ManifestType::Std,547			},548		)549		.map(|s| s.into())550	}551552	pub fn to_yaml(&self, padding: usize) -> Result<IStr> {553		let padding = &" ".repeat(padding);554		manifest_yaml_ex(555			self,556			&ManifestYamlOptions {557				padding,558				arr_element_padding: padding,559				quote_keys: false,560			},561		)562		.map(|s| s.into())563	}564	pub fn into_indexable(self) -> Result<IndexableVal> {565		Ok(match self {566			Val::Str(s) => IndexableVal::Str(s),567			Val::Arr(arr) => IndexableVal::Arr(arr),568			_ => throw!(ValueIsNotIndexable(self.value_type())),569		})570	}571}572573const fn is_function_like(val: &Val) -> bool {574	matches!(val, Val::Func(_))575}576577/// Native implementation of `std.primitiveEquals`578pub fn primitive_equals(val_a: &Val, val_b: &Val) -> Result<bool> {579	Ok(match (val_a, val_b) {580		(Val::Bool(a), Val::Bool(b)) => a == b,581		(Val::Null, Val::Null) => true,582		(Val::Str(a), Val::Str(b)) => a == b,583		(Val::Num(a), Val::Num(b)) => (a - b).abs() <= f64::EPSILON,584		(Val::Arr(_), Val::Arr(_)) => throw!(RuntimeError(585			"primitiveEquals operates on primitive types, got array".into(),586		)),587		(Val::Obj(_), Val::Obj(_)) => throw!(RuntimeError(588			"primitiveEquals operates on primitive types, got object".into(),589		)),590		(a, b) if is_function_like(a) && is_function_like(b) => {591			throw!(RuntimeError("cannot test equality of functions".into()))592		}593		(_, _) => false,594	})595}596597/// Native implementation of `std.equals`598pub fn equals(val_a: &Val, val_b: &Val) -> Result<bool> {599	if val_a.value_type() != val_b.value_type() {600		return Ok(false);601	}602	match (val_a, val_b) {603		(Val::Arr(a), Val::Arr(b)) => {604			if ArrValue::ptr_eq(a, b) {605				return Ok(true);606			}607			if a.len() != b.len() {608				return Ok(false);609			}610			for (a, b) in a.iter().zip(b.iter()) {611				if !equals(&a?, &b?)? {612					return Ok(false);613				}614			}615			Ok(true)616		}617		(Val::Obj(a), Val::Obj(b)) => {618			if ObjValue::ptr_eq(a, b) {619				return Ok(true);620			}621			let fields = a.fields();622			if fields != b.fields() {623				return Ok(false);624			}625			for field in fields {626				if !equals(&a.get(field.clone())?.unwrap(), &b.get(field)?.unwrap())? {627					return Ok(false);628				}629			}630			Ok(true)631		}632		(a, b) => Ok(primitive_equals(a, b)?),633	}634}
addedcrates/jrsonnet-macros/Cargo.tomldiffbeforeafterboth
--- /dev/null
+++ b/crates/jrsonnet-macros/Cargo.toml
@@ -0,0 +1,12 @@
+[package]
+name = "jrsonnet-macros"
+version = "0.4.2"
+edition = "2021"
+
+[lib]
+proc-macro = true
+
+[dependencies]
+proc-macro2 = "1.0.32"
+quote = "1.0.10"
+syn = { version = "1.0.82", features = ["full"] }
addedcrates/jrsonnet-macros/src/lib.rsdiffbeforeafterboth
--- /dev/null
+++ b/crates/jrsonnet-macros/src/lib.rs
@@ -0,0 +1,87 @@
+use proc_macro2::Span;
+use quote::quote;
+use syn::{parse_macro_input, FnArg, Ident, ItemFn, Pat};
+
+#[proc_macro_attribute]
+pub fn builtin(
+	_attr: proc_macro::TokenStream,
+	item: proc_macro::TokenStream,
+) -> proc_macro::TokenStream {
+	// syn::ItemFn::parse(input)
+	let fun: ItemFn = parse_macro_input!(item);
+
+	let inner_name = Ident::new("inner", Span::call_site());
+	let mut inner_fun = fun.clone();
+	inner_fun.sig.ident = inner_name.clone();
+	let result = match fun.sig.output {
+		syn::ReturnType::Default => panic!("builtin should return something"),
+		syn::ReturnType::Type(_, ty) => ty,
+	};
+
+	let params = fun
+		.sig
+		.inputs
+		.iter()
+		.map(|i| match i {
+			FnArg::Receiver(_) => unreachable!(),
+			FnArg::Typed(t) => t,
+		})
+		.map(|t| {
+			let ident = match &t.pat as &Pat {
+				Pat::Ident(i) => i.ident.to_string(),
+				_ => panic!("only idents supported yet"),
+			};
+			// TODO: Check if ty == Option<_>
+			let optional = false;
+			quote! {
+				BuiltinParam {
+					name: #ident,
+					has_default: #optional,
+				}
+			}
+		});
+
+	let args = fun
+		.sig
+		.inputs
+		.iter()
+		.map(|i| match i {
+			FnArg::Receiver(_) => unreachable!(),
+			FnArg::Typed(t) => t,
+		})
+		.map(|t| {
+			let ident = match &t.pat as &Pat {
+				Pat::Ident(i) => i.ident.to_string(),
+				_ => panic!("only idents supported yet"),
+			};
+			let ty = &t.ty;
+			quote! {{
+				let value = parsed.get(#ident).unwrap();
+
+				jrsonnet_evaluator::push_description_frame(
+					|| format!("argument <{}> evaluation", #ident),
+					|| <#ty>::try_from(value.evaluate()?),
+				)?
+			}}
+		});
+
+	let attrs = &fun.attrs;
+	let vis = &fun.vis;
+	let name = &fun.sig.ident;
+	(quote! {
+		#(#attrs)*
+		#vis fn #name(context: Context, _loc: &ExprLocation, args: &ArgsDesc) -> Result<Val> {
+			#inner_fun
+			use jrsonnet_evaluator::function::BuiltinParam;
+			const PARAMS: &'static [BuiltinParam] = &[
+				#(#params),*
+			];
+			let parsed = jrsonnet_evaluator::function::parse_builtin_call(context, &PARAMS, args, false)?;
+
+			let result: #result = #inner_name(#(#args),*);
+			let result = result?;
+			result.try_into()
+		}
+	})
+	.into()
+}
modifiedcrates/jrsonnet-types/src/lib.rsdiffbeforeafterboth
--- a/crates/jrsonnet-types/src/lib.rs
+++ b/crates/jrsonnet-types/src/lib.rs
@@ -42,14 +42,14 @@
 		$crate::ComplexValType::Simple($crate::ValType::Func)
 	};
 	(($($a:tt) |+)) => {{
-		static CONTENTS: &'static [$crate::ComplexValType] = &[
-			$(ty!($a)),+
+		static CONTENTS: &'static [&'static $crate::ComplexValType] = &[
+			$(&ty!($a)),+
 		];
 		$crate::ComplexValType::UnionRef(CONTENTS)
 	}};
 	(($($a:tt) &+)) => {{
-		static CONTENTS: &'static [$crate::ComplexValType] = &[
-			$(ty!($a)),+
+		static CONTENTS: &'static [&'static $crate::ComplexValType] = &[
+			$(&ty!($a)),+
 		];
 		$crate::ComplexValType::SumRef(CONTENTS)
 	}};
@@ -66,8 +66,8 @@
 	assert_eq!(
 		ty!((string | number)),
 		ComplexValType::UnionRef(&[
-			ComplexValType::Simple(ValType::Str),
-			ComplexValType::Simple(ValType::Num)
+			&ComplexValType::Simple(ValType::Str),
+			&ComplexValType::Simple(ValType::Num)
 		])
 	);
 	assert_eq!(
@@ -124,9 +124,9 @@
 	ArrayRef(&'static ComplexValType),
 	ObjectRef(&'static [(&'static str, ComplexValType)]),
 	Union(Vec<ComplexValType>),
-	UnionRef(&'static [ComplexValType]),
+	UnionRef(&'static [&'static ComplexValType]),
 	Sum(Vec<ComplexValType>),
-	SumRef(&'static [ComplexValType]),
+	SumRef(&'static [&'static ComplexValType]),
 }
 
 impl From<ValType> for ComplexValType {
@@ -135,12 +135,12 @@
 	}
 }
 
-fn write_union(
+fn write_union<'i>(
 	f: &mut std::fmt::Formatter<'_>,
 	is_union: bool,
-	union: &[ComplexValType],
+	union: impl Iterator<Item = &'i ComplexValType>,
 ) -> std::fmt::Result {
-	for (i, v) in union.iter().enumerate() {
+	for (i, v) in union.enumerate() {
 		let should_add_braces =
 			matches!(v, ComplexValType::UnionRef(_) | ComplexValType::Union(_) if !is_union);
 		if i != 0 {
@@ -190,10 +190,10 @@
 				}
 				write!(f, "}}")?;
 			}
-			ComplexValType::Union(v) => write_union(f, true, v)?,
-			ComplexValType::UnionRef(v) => write_union(f, true, v)?,
-			ComplexValType::Sum(v) => write_union(f, false, v)?,
-			ComplexValType::SumRef(v) => write_union(f, false, v)?,
+			ComplexValType::Union(v) => write_union(f, true, v.iter())?,
+			ComplexValType::UnionRef(v) => write_union(f, true, v.iter().map(|v| *v))?,
+			ComplexValType::Sum(v) => write_union(f, false, v.iter())?,
+			ComplexValType::SumRef(v) => write_union(f, false, v.iter().map(|v| *v))?,
 		};
 		Ok(())
 	}