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
before · crates/jrsonnet-evaluator/src/builtin/mod.rs
1use crate::{2	builtin::manifest::{manifest_yaml_ex, ManifestYamlOptions},3	equals,4	error::{Error::*, Result},5	operator::evaluate_mod_op,6	parse_args, primitive_equals, push_frame, throw, with_state, ArrValue, Context, FuncVal,7	IndexableVal, LazyVal, Val,8};9use format::{format_arr, format_obj};10use gcmodule::Cc;11use jrsonnet_interner::IStr;12use jrsonnet_parser::{ArgsDesc, ExprLocation};13use jrsonnet_types::ty;14use serde::Deserialize;15use serde_yaml::DeserializingQuirks;16use std::{collections::HashMap, convert::TryFrom, path::PathBuf, rc::Rc};1718pub mod stdlib;19pub use stdlib::*;2021use self::manifest::{escape_string_json, manifest_json_ex, ManifestJsonOptions, ManifestType};2223pub mod format;24pub mod manifest;25pub mod sort;2627pub fn std_format(str: IStr, vals: Val) -> Result<Val> {28	push_frame(29		&ExprLocation(Rc::from(PathBuf::from("std.jsonnet")), 0, 0),30		|| format!("std.format of {}", str),31		|| {32			Ok(match vals {33				Val::Arr(vals) => Val::Str(format_arr(&str, &vals.evaluated()?)?.into()),34				Val::Obj(obj) => Val::Str(format_obj(&str, &obj)?.into()),35				o => Val::Str(format_arr(&str, &[o])?.into()),36			})37		},38	)39}4041pub fn std_slice(42	indexable: IndexableVal,43	index: Option<usize>,44	end: Option<usize>,45	step: Option<usize>,46) -> Result<Val> {47	let index = index.unwrap_or(0);48	let end = end.unwrap_or_else(|| match &indexable {49		IndexableVal::Str(_) => usize::MAX,50		IndexableVal::Arr(v) => v.len(),51	});52	let step = step.unwrap_or(1);53	match &indexable {54		IndexableVal::Str(s) => Ok(Val::Str(55			(s.chars()56				.skip(index)57				.take(end - index)58				.step_by(step)59				.collect::<String>())60			.into(),61		)),62		IndexableVal::Arr(arr) => Ok(Val::Arr(63			(arr.iter()64				.skip(index)65				.take(end - index)66				.step_by(step)67				.collect::<Result<Vec<Val>>>()?)68			.into(),69		)),70	}71}7273type Builtin = fn(context: Context, loc: &ExprLocation, args: &ArgsDesc) -> Result<Val>;7475type BuiltinsType = HashMap<Box<str>, Builtin>;7677thread_local! {78	static BUILTINS: BuiltinsType = {79		[80			("length".into(), builtin_length as Builtin),81			("type".into(), builtin_type),82			("makeArray".into(), builtin_make_array),83			("codepoint".into(), builtin_codepoint),84			("objectFieldsEx".into(), builtin_object_fields_ex),85			("objectHasEx".into(), builtin_object_has_ex),86			("slice".into(), builtin_slice),87			("substr".into(), builtin_substr),88			("primitiveEquals".into(), builtin_primitive_equals),89			("equals".into(), builtin_equals),90			("modulo".into(), builtin_modulo),91			("mod".into(), builtin_mod),92			("floor".into(), builtin_floor),93			("ceil".into(), builtin_ceil),94			("log".into(), builtin_log),95			("pow".into(), builtin_pow),96			("sqrt".into(), builtin_sqrt),97			("sin".into(), builtin_sin),98			("cos".into(), builtin_cos),99			("tan".into(), builtin_tan),100			("asin".into(), builtin_asin),101			("acos".into(), builtin_acos),102			("atan".into(), builtin_atan),103			("exp".into(), builtin_exp),104			("mantissa".into(), builtin_mantissa),105			("exponent".into(), builtin_exponent),106			("extVar".into(), builtin_ext_var),107			("native".into(), builtin_native),108			("filter".into(), builtin_filter),109			("map".into(), builtin_map),110			("flatMap".into(), builtin_flatmap),111			("foldl".into(), builtin_foldl),112			("foldr".into(), builtin_foldr),113			("sortImpl".into(), builtin_sort_impl),114			("format".into(), builtin_format),115			("range".into(), builtin_range),116			("char".into(), builtin_char),117			("encodeUTF8".into(), builtin_encode_utf8),118			("decodeUTF8".into(), builtin_decode_utf8),119			("md5".into(), builtin_md5),120			("base64".into(), builtin_base64),121			("base64DecodeBytes".into(), builtin_base64_decode_bytes),122			("base64Decode".into(), builtin_base64_decode),123			("trace".into(), builtin_trace),124			("join".into(), builtin_join),125			("escapeStringJson".into(), builtin_escape_string_json),126			("manifestJsonEx".into(), builtin_manifest_json_ex),127			("manifestYamlDocImpl".into(), builtin_manifest_yaml_doc),128			("reverse".into(), builtin_reverse),129			("id".into(), builtin_id),130			("strReplace".into(), builtin_str_replace),131			("splitLimit".into(), builtin_splitlimit),132			("parseJson".into(), builtin_parse_json),133			("parseYaml".into(), builtin_parse_yaml),134			("asciiUpper".into(), builtin_ascii_upper),135			("asciiLower".into(), builtin_ascii_lower),136			("member".into(), builtin_member),137			("count".into(), builtin_count),138		].iter().cloned().collect()139	};140}141142fn builtin_length(context: Context, _loc: &ExprLocation, args: &ArgsDesc) -> Result<Val> {143	parse_args!(context, "length", args, 1, [144		0, x: ty!((string | object | array));145	], {146		Ok(match x {147			Val::Str(n) => Val::Num(n.chars().count() as f64),148			Val::Arr(a) => Val::Num(a.len() as f64),149			Val::Obj(o) => Val::Num(150				o.fields_visibility()151					.into_iter()152					.filter(|(_k, v)| *v)153					.count() as f64,154			),155			_ => unreachable!(),156		})157	})158}159160fn builtin_type(context: Context, _loc: &ExprLocation, args: &ArgsDesc) -> Result<Val> {161	parse_args!(context, "type", args, 1, [162		0, x: ty!(any);163	], {164		Ok(Val::Str(x.value_type().name().into()))165	})166}167168fn builtin_make_array(context: Context, _loc: &ExprLocation, args: &ArgsDesc) -> Result<Val> {169	parse_args!(context, "makeArray", args, 2, [170		0, sz: ty!(BoundedNumber<(Some(0.0)), (None)>) => Val::Num;171		1, func: ty!(function) => Val::Func;172	], {173		let mut out = Vec::with_capacity(sz as usize);174		for i in 0..sz as usize {175			out.push(LazyVal::new_resolved(func.evaluate_values(176				context.clone(),177				&[Val::Num(i as f64)]178			)?))179		}180		Ok(Val::Arr(out.into()))181	})182}183184fn builtin_codepoint(context: Context, _loc: &ExprLocation, args: &ArgsDesc) -> Result<Val> {185	parse_args!(context, "codepoint", args, 1, [186		0, str: ty!(char) => Val::Str;187	], {188		Ok(Val::Num(str.chars().next().unwrap() as u32 as f64))189	})190}191192fn builtin_object_fields_ex(context: Context, _loc: &ExprLocation, args: &ArgsDesc) -> Result<Val> {193	parse_args!(context, "objectFieldsEx", args, 2, [194		0, obj: ty!(object) => Val::Obj;195		1, inc_hidden: ty!(boolean) => Val::Bool;196	], {197		let out = obj.fields_ex(inc_hidden);198		Ok(Val::Arr(out.into_iter().map(Val::Str).collect::<Vec<_>>().into()))199	})200}201202fn builtin_object_has_ex(context: Context, _loc: &ExprLocation, args: &ArgsDesc) -> Result<Val> {203	parse_args!(context, "objectHasEx", args, 3, [204		0, obj: ty!(object) => Val::Obj;205		1, f: ty!(string) => Val::Str;206		2, inc_hidden: ty!(boolean) => Val::Bool;207	], {208		Ok(Val::Bool(obj.has_field_ex(f, inc_hidden)))209	})210}211212fn builtin_parse_json(context: Context, _loc: &ExprLocation, args: &ArgsDesc) -> Result<Val> {213	parse_args!(context, "parseJson", args, 1, [214		0, s: ty!(string) => Val::Str;215	], {216		let value: serde_json::Value = serde_json::from_str(&s).map_err(|e| RuntimeError(format!("failed to parse json: {}", e).into()))?;217		Ok(Val::try_from(&value)?)218	})219}220221fn builtin_parse_yaml(context: Context, _loc: &ExprLocation, args: &ArgsDesc) -> Result<Val> {222	parse_args!(context, "parseYaml", args, 1, [223		0, s: ty!(string) => Val::Str;224	], {225		let value = serde_yaml::Deserializer::from_str_with_quirks(&s, DeserializingQuirks { old_octals: true });226		let mut out = vec![];227		for item in value {228			let value = serde_json::Value::deserialize(item)229				.map_err(|e| RuntimeError(format!("failed to parse yaml: {}", e).into()))?;230			let val = Val::try_from(&value)?;231			out.push(val);232		}233		if out.is_empty() {234			Ok(Val::Null)235		} else if out.len() == 1 {236			Ok(out.into_iter().next().unwrap())237		} else {238			Ok(Val::Arr(out.into()))239		}240	})241}242243fn builtin_slice(context: Context, _loc: &ExprLocation, args: &ArgsDesc) -> Result<Val> {244	parse_args!(context, "slice", args, 4, [245		0, indexable: ty!((string | array));246		1, index: ty!((number | null));247		2, end: ty!((number | null));248		3, step: ty!((number | null));249	], {250		std_slice(251			indexable.into_indexable()?,252			index.try_cast_nullable_num("index")?.map(|v| v as usize),253			end.try_cast_nullable_num("end")?.map(|v| v as usize),254			step.try_cast_nullable_num("step")?.map(|v| v as usize),255		)256	})257}258259fn builtin_substr(context: Context, _loc: &ExprLocation, args: &ArgsDesc) -> Result<Val> {260	parse_args!(context, "substr", args, 3, [261		0, str: ty!(string) => Val::Str;262		1, from: ty!(BoundedNumber<(Some(0.0)), (None)>) => Val::Num;263		2, len: ty!(BoundedNumber<(Some(0.0)), (None)>) => Val::Num;264	], {265		let out: String = str.chars().skip(from as usize).take(len as usize).collect();266		Ok(Val::Str(out.into()))267	})268}269270fn builtin_primitive_equals(context: Context, _loc: &ExprLocation, args: &ArgsDesc) -> Result<Val> {271	parse_args!(context, "primitiveEquals", args, 2, [272		0, a: ty!(any);273		1, b: ty!(any);274	], {275		Ok(Val::Bool(primitive_equals(&a, &b)?))276	})277}278279fn builtin_equals(context: Context, _loc: &ExprLocation, args: &ArgsDesc) -> Result<Val> {280	parse_args!(context, "equals", args, 2, [281		0, a: ty!(any);282		1, b: ty!(any);283	], {284		Ok(Val::Bool(equals(&a, &b)?))285	})286}287288fn builtin_modulo(context: Context, _loc: &ExprLocation, args: &ArgsDesc) -> Result<Val> {289	parse_args!(context, "modulo", args, 2, [290		0, a: ty!(number) => Val::Num;291		1, b: ty!(number) => Val::Num;292	], {293		Ok(Val::Num(a % b))294	})295}296297fn builtin_mod(context: Context, _loc: &ExprLocation, args: &ArgsDesc) -> Result<Val> {298	parse_args!(context, "mod", args, 2, [299		0, a: ty!((number | string));300		1, b: ty!(any);301	], {302		evaluate_mod_op(&a, &b)303	})304}305306fn builtin_floor(context: Context, _loc: &ExprLocation, args: &ArgsDesc) -> Result<Val> {307	parse_args!(context, "floor", args, 1, [308		0, x: ty!(number) => Val::Num;309	], {310		Ok(Val::Num(x.floor()))311	})312}313314fn builtin_ceil(context: Context, _loc: &ExprLocation, args: &ArgsDesc) -> Result<Val> {315	parse_args!(context, "ceil", args, 1, [316		0, x: ty!(number) => Val::Num;317	], {318		Ok(Val::Num(x.ceil()))319	})320}321322fn builtin_log(context: Context, _loc: &ExprLocation, args: &ArgsDesc) -> Result<Val> {323	parse_args!(context, "log", args, 1, [324		0, n: ty!(number) => Val::Num;325	], {326		Ok(Val::Num(n.ln()))327	})328}329330fn builtin_pow(context: Context, _loc: &ExprLocation, args: &ArgsDesc) -> Result<Val> {331	parse_args!(context, "pow", args, 2, [332		0, x: ty!(number) => Val::Num;333		1, n: ty!(number) => Val::Num;334	], {335		Ok(Val::Num(x.powf(n)))336	})337}338339fn builtin_sqrt(context: Context, _loc: &ExprLocation, args: &ArgsDesc) -> Result<Val> {340	parse_args!(context, "sqrt", args, 1, [341		0, x: ty!(BoundedNumber<(Some(0.0)), (None)>) => Val::Num;342	], {343		Ok(Val::Num(x.sqrt()))344	})345}346347fn builtin_sin(context: Context, _loc: &ExprLocation, args: &ArgsDesc) -> Result<Val> {348	parse_args!(context, "sin", args, 1, [349		0, x: ty!(number) => Val::Num;350	], {351		Ok(Val::Num(x.sin()))352	})353}354355fn builtin_cos(context: Context, _loc: &ExprLocation, args: &ArgsDesc) -> Result<Val> {356	parse_args!(context, "cos", args, 1, [357		0, x: ty!(number) => Val::Num;358	], {359		Ok(Val::Num(x.cos()))360	})361}362363fn builtin_tan(context: Context, _loc: &ExprLocation, args: &ArgsDesc) -> Result<Val> {364	parse_args!(context, "tan", args, 1, [365		0, x: ty!(number) => Val::Num;366	], {367		Ok(Val::Num(x.tan()))368	})369}370371fn builtin_asin(context: Context, _loc: &ExprLocation, args: &ArgsDesc) -> Result<Val> {372	parse_args!(context, "asin", args, 1, [373		0, x: ty!(number) => Val::Num;374	], {375		Ok(Val::Num(x.asin()))376	})377}378379fn builtin_acos(context: Context, _loc: &ExprLocation, args: &ArgsDesc) -> Result<Val> {380	parse_args!(context, "acos", args, 1, [381		0, x: ty!(number) => Val::Num;382	], {383		Ok(Val::Num(x.acos()))384	})385}386387fn builtin_atan(context: Context, _loc: &ExprLocation, args: &ArgsDesc) -> Result<Val> {388	parse_args!(context, "atan", args, 1, [389		0, x: ty!(number) => Val::Num;390	], {391		Ok(Val::Num(x.atan()))392	})393}394395fn builtin_exp(context: Context, _loc: &ExprLocation, args: &ArgsDesc) -> Result<Val> {396	parse_args!(context, "exp", args, 1, [397		0, x: ty!(number) => Val::Num;398	], {399		Ok(Val::Num(x.exp()))400	})401}402403fn frexp(s: f64) -> (f64, i16) {404	if 0.0 == s {405		(s, 0)406	} else {407		let lg = s.abs().log2();408		let x = (lg - lg.floor() - 1.0).exp2();409		let exp = lg.floor() + 1.0;410		(s.signum() * x, exp as i16)411	}412}413414fn builtin_mantissa(context: Context, _loc: &ExprLocation, args: &ArgsDesc) -> Result<Val> {415	parse_args!(context, "mantissa", args, 1, [416		0, x: ty!(number) => Val::Num;417	], {418		Ok(Val::Num(frexp(x).0))419	})420}421422fn builtin_exponent(context: Context, _loc: &ExprLocation, args: &ArgsDesc) -> Result<Val> {423	parse_args!(context, "exponent", args, 1, [424		0, x: ty!(number) => Val::Num;425	], {426		Ok(Val::Num(frexp(x).1.into()))427	})428}429430fn builtin_ext_var(context: Context, _loc: &ExprLocation, args: &ArgsDesc) -> Result<Val> {431	parse_args!(context, "extVar", args, 1, [432		0, x: ty!(string) => Val::Str;433	], {434		Ok(with_state(|s| s.settings().ext_vars.get(&x).cloned()).ok_or(UndefinedExternalVariable(x))?)435	})436}437438fn builtin_native(context: Context, _loc: &ExprLocation, args: &ArgsDesc) -> Result<Val> {439	parse_args!(context, "native", args, 1, [440		0, x: ty!(string) => Val::Str;441	], {442		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))?)443	})444}445446fn builtin_filter(context: Context, _loc: &ExprLocation, args: &ArgsDesc) -> Result<Val> {447	parse_args!(context, "filter", args, 2, [448		0, func: ty!(function) => Val::Func;449		1, arr: ty!(array) => Val::Arr;450	], {451		Ok(Val::Arr(arr.filter(|val| func452			.evaluate_values(context.clone(), &[val.clone()])?453			.try_cast_bool("filter predicate"))?))454	})455}456457fn builtin_map(context: Context, _loc: &ExprLocation, args: &ArgsDesc) -> Result<Val> {458	parse_args!(context, "map", args, 2, [459		0, func: ty!(function) => Val::Func;460		1, arr: ty!(array) => Val::Arr;461	], {462		Ok(Val::Arr(arr.map(|val| func463			.evaluate_values(context.clone(), &[val]))?))464	})465}466467fn builtin_flatmap(context: Context, _loc: &ExprLocation, args: &ArgsDesc) -> Result<Val> {468	parse_args!(context, "flatMap", args, 2, [469		0, func: ty!(function) => Val::Func;470		1, arr: ty!((array | string));471	], {472		match arr {473			Val::Str(s) => {474				let mut out = String::new();475				for c in s.chars() {476					match func.evaluate_values(context.clone(), &[Val::Str(c.to_string().into())])? {477						Val::Str(o) => out.push_str(&o),478						_ => throw!(RuntimeError("in std.join all items should be strings".into())),479					};480				}481				Ok(Val::Str(out.into()))482			},483			Val::Arr(a) => {484				let mut out = Vec::new();485				for el in a.iter() {486					let el = el?;487					match func.evaluate_values(context.clone(), &[el])? {488						Val::Arr(o) => for oe in o.iter() {489							out.push(oe?)490						},491						_ => throw!(RuntimeError("in std.join all items should be arrays".into())),492					};493				}494				Ok(Val::Arr(out.into()))495			},496			_ => unreachable!(),497		}498	})499}500501fn builtin_foldl(context: Context, _loc: &ExprLocation, args: &ArgsDesc) -> Result<Val> {502	parse_args!(context, "foldl", args, 3, [503		0, func: ty!(function) => Val::Func;504		1, arr: ty!(array) => Val::Arr;505		2, init: ty!(any);506	], {507		let mut acc = init;508		for i in arr.iter() {509			acc = func.evaluate_values(context.clone(), &[acc, i?])?;510		}511		Ok(acc)512	})513}514515fn builtin_foldr(context: Context, _loc: &ExprLocation, args: &ArgsDesc) -> Result<Val> {516	parse_args!(context, "foldr", args, 3, [517		0, func: ty!(function) => Val::Func;518		1, arr: ty!(array) => Val::Arr;519		2, init: ty!(any);520	], {521		let mut acc = init;522		for i in arr.iter().rev() {523			acc = func.evaluate_values(context.clone(), &[i?, acc])?;524		}525		Ok(acc)526	})527}528529#[allow(non_snake_case)]530fn builtin_sort_impl(context: Context, _loc: &ExprLocation, args: &ArgsDesc) -> Result<Val> {531	parse_args!(context, "sort", args, 2, [532		0, arr: ty!(array) => Val::Arr;533		1, keyF: ty!(function) => Val::Func;534	], {535		if arr.len() <= 1 {536			return Ok(Val::Arr(arr))537		}538		Ok(Val::Arr(ArrValue::Eager(sort::sort(context, arr.evaluated()?, &keyF)?)))539	})540}541542fn builtin_format(context: Context, _loc: &ExprLocation, args: &ArgsDesc) -> Result<Val> {543	parse_args!(context, "format", args, 2, [544		0, str: ty!(string) => Val::Str;545		1, vals: ty!(any)546	], {547		std_format(str, vals)548	})549}550551fn builtin_range(context: Context, _loc: &ExprLocation, args: &ArgsDesc) -> Result<Val> {552	parse_args!(context, "range", args, 2, [553		0, from: ty!(number) => Val::Num;554		1, to: ty!(number) => Val::Num;555	], {556		if to < from {557			return Ok(Val::Arr(ArrValue::new_eager()))558		}559		let mut out = Vec::with_capacity((1+to as usize-from as usize).max(0));560		for i in from as usize..=to as usize {561			out.push(Val::Num(i as f64));562		}563		Ok(Val::Arr(out.into()))564	})565}566567fn builtin_char(context: Context, _loc: &ExprLocation, args: &ArgsDesc) -> Result<Val> {568	parse_args!(context, "char", args, 1, [569		0, n: ty!(number) => Val::Num;570	], {571		let mut out = String::new();572		out.push(std::char::from_u32(n as u32).ok_or_else(||573			InvalidUnicodeCodepointGot(n as u32)574		)?);575		Ok(Val::Str(out.into()))576	})577}578579fn builtin_encode_utf8(context: Context, _loc: &ExprLocation, args: &ArgsDesc) -> Result<Val> {580	parse_args!(context, "encodeUTF8", args, 1, [581		0, str: ty!(string) => Val::Str;582	], {583		Ok(Val::Arr((str.bytes().map(|b| Val::Num(b as f64)).collect::<Vec<Val>>()).into()))584	})585}586587fn builtin_decode_utf8(context: Context, _loc: &ExprLocation, args: &ArgsDesc) -> Result<Val> {588	parse_args!(context, "decodeUTF8", args, 1, [589		0, arr: ty!((Array<ubyte>)) => Val::Arr;590	], {591		let data: Result<Vec<u8>> = arr.iter().map(|v| v.map(|v| match v{592			Val::Num(n) => n as u8,593			_ => unreachable!(),594		})).collect();595		let data = data?;596		Ok(Val::Str(String::from_utf8(data).map_err(|_| RuntimeError("bad utf8".into()))?.into()))597	})598}599600fn builtin_md5(context: Context, _loc: &ExprLocation, args: &ArgsDesc) -> Result<Val> {601	parse_args!(context, "md5", args, 1, [602		0, str: ty!(string) => Val::Str;603	], {604		Ok(Val::Str(format!("{:x}", md5::compute(&str.as_bytes())).into()))605	})606}607608fn builtin_trace(context: Context, loc: &ExprLocation, args: &ArgsDesc) -> Result<Val> {609	parse_args!(context, "trace", args, 2, [610		0, str: ty!(string) => Val::Str;611		1, rest: ty!(any);612	], {613		eprint!("TRACE:");614			with_state(|s|{615				let locs = s.map_source_locations(&loc.0, &[loc.1]);616				eprint!(" {}:{}", loc.0.file_name().unwrap().to_str().unwrap(), locs[0].line);617			});618		eprintln!(" {}", str);619		Ok(rest)620	})621}622623fn builtin_base64(context: Context, _loc: &ExprLocation, args: &ArgsDesc) -> Result<Val> {624	parse_args!(context, "base64", args, 1, [625		0, input: ty!((string | (Array<number>)));626	], {627		Ok(Val::Str(match input {628			Val::Str(s) => {629				base64::encode(s.bytes().collect::<Vec<_>>()).into()630			},631			Val::Arr(a) => {632				base64::encode(a.iter().map(|v| {633					Ok(v?.unwrap_num()? as u8)634				}).collect::<Result<Vec<_>>>()?).into()635			},636			_ => unreachable!()637		}))638	})639}640641fn builtin_base64_decode_bytes(642	context: Context,643	_loc: &ExprLocation,644	args: &ArgsDesc,645) -> Result<Val> {646	parse_args!(context, "base64DecodeBytes", args, 1, [647		0, input: ty!(string) => Val::Str;648	], {649		Ok(Val::Arr(650			base64::decode(&input.as_bytes())651				.map_err(|_| RuntimeError("bad base64".into()))?652				.iter()653				.map(|v| Val::Num(*v as f64)).collect::<Vec<_>>().into()654		))655	})656}657658fn builtin_base64_decode(context: Context, _loc: &ExprLocation, args: &ArgsDesc) -> Result<Val> {659	parse_args!(context, "base64Decode", args, 1, [660		0, input: ty!(string) => Val::Str;661	], {662		Ok(Val::Str(663			String::from_utf8(base64::decode(&input.as_bytes())664				.map_err(|_| RuntimeError("bad base64".into()))?)665				.map_err(|_| RuntimeError("bad utf8".into()))?.into()666		))667	})668}669670fn builtin_join(context: Context, _loc: &ExprLocation, args: &ArgsDesc) -> Result<Val> {671	parse_args!(context, "join", args, 2, [672		0, sep: ty!((string | array));673		1, arr: ty!(array) => Val::Arr;674	], {675		Ok(match sep {676			Val::Arr(joiner_items) => {677				let mut out = Vec::new();678679				let mut first = true;680				for item in arr.iter() {681					let item = item?.clone();682					if let Val::Arr(items) = item {683						if !first {684							out.reserve(joiner_items.len());685							// TODO: extend686							for item in joiner_items.iter() {687								out.push(item?);688							}689						}690						first = false;691						out.reserve(items.len());692						// TODO: extend693						for item in items.iter() {694							out.push(item?);695						}696					} else {697						throw!(RuntimeError("in std.join all items should be arrays".into()));698					}699				}700701				Val::Arr(out.into())702			},703			Val::Str(sep) => {704				let mut out = String::new();705706				let mut first = true;707				for item in arr.iter() {708					let item = item?.clone();709					if let Val::Str(item) = item {710						if !first {711							out += &sep;712						}713						first = false;714						out += &item;715					} else {716						throw!(RuntimeError("in std.join all items should be strings".into()));717					}718				}719720				Val::Str(out.into())721			},722			_ => unreachable!()723		})724	})725}726727fn builtin_escape_string_json(728	context: Context,729	_loc: &ExprLocation,730	args: &ArgsDesc,731) -> Result<Val> {732	parse_args!(context, "escapeStringJson", args, 1, [733		0, str_: ty!(string) => Val::Str;734	], {735		Ok(Val::Str(escape_string_json(&str_).into()))736	})737}738739fn builtin_manifest_json_ex(context: Context, _loc: &ExprLocation, args: &ArgsDesc) -> Result<Val> {740	parse_args!(context, "manifestJsonEx", args, 2, [741		0, value: ty!(any);742		1, indent: ty!(string) => Val::Str;743	], {744		Ok(Val::Str(manifest_json_ex(&value, &ManifestJsonOptions {745			padding: &indent,746			mtype: ManifestType::Std,747		})?.into()))748	})749}750751fn builtin_manifest_yaml_doc(752	context: Context,753	_loc: &ExprLocation,754	args: &ArgsDesc,755) -> Result<Val> {756	parse_args!(context, "manifestYamlDoc", args, 3, [757		0, value: ty!(any);758		1, indent_array_in_object: ty!(boolean) => Val::Bool;759		2, quote_keys: ty!(boolean) => Val::Bool;760	], {761		Ok(Val::Str(manifest_yaml_ex(&value, &ManifestYamlOptions {762			padding: "  ",763			arr_element_padding: if indent_array_in_object { "  " } else { "" },764			quote_keys,765		})?.into()))766	})767}768769fn builtin_reverse(context: Context, _loc: &ExprLocation, args: &ArgsDesc) -> Result<Val> {770	parse_args!(context, "reverse", args, 1, [771		0, value: ty!(array) => Val::Arr;772	], {773		Ok(Val::Arr(value.reversed()))774	})775}776777fn builtin_id(context: Context, _loc: &ExprLocation, args: &ArgsDesc) -> Result<Val> {778	parse_args!(context, "id", args, 1, [779		0, v: ty!(any);780	], {781		Ok(v)782	})783}784785fn builtin_str_replace(context: Context, _loc: &ExprLocation, args: &ArgsDesc) -> Result<Val> {786	parse_args!(context, "strReplace", args, 3, [787		0, str: ty!(string) => Val::Str;788		1, from: ty!(string) => Val::Str;789		2, to: ty!(string) => Val::Str;790	], {791		Ok(Val::Str(str.replace(&from as &str, &to as &str).into()))792	})793}794795fn builtin_splitlimit(context: Context, _loc: &ExprLocation, args: &ArgsDesc) -> Result<Val> {796	parse_args!(context, "splitLimit", args, 3, [797		0, str: ty!(string) => Val::Str;798		1, c: ty!(char) => Val::Str;799		2, maxsplits: ty!(number) => Val::Num;800	], {801		let maxsplits = maxsplits as isize;802		let c = c.chars().next().unwrap();803804		let out: Vec<Val> = if maxsplits == -1 {805			str.split(c).map(|s| Val::Str(s.into())).collect()806		} else {807			str.splitn(maxsplits as usize + 1, c).map(|s| Val::Str(s.into())).collect()808		};809810		Ok(Val::Arr(out.into()))811	})812}813814fn builtin_ascii_upper(context: Context, _loc: &ExprLocation, args: &ArgsDesc) -> Result<Val> {815	parse_args!(context, "asciiUpper", args, 1, [816		0, str: ty!(string) => Val::Str;817	], {818		Ok(Val::Str(str.to_ascii_uppercase().into()))819	})820}821822fn builtin_ascii_lower(context: Context, _loc: &ExprLocation, args: &ArgsDesc) -> Result<Val> {823	parse_args!(context, "asciiLower", args, 1, [824		0, str: ty!(string) => Val::Str;825	], {826		Ok(Val::Str(str.to_ascii_lowercase().into()))827	})828}829830fn builtin_member(context: Context, _loc: &ExprLocation, args: &ArgsDesc) -> Result<Val> {831	parse_args!(context, "member", args, 2, [832		0, arr: ty!((array | string));833		1, x: ty!(any);834	], {835		match arr {836			Val::Str(s) => {837				let x = x.try_cast_str("x should be string")?;838				Ok(Val::Bool(!x.is_empty() && s.contains(&*x)))839			}840			Val::Arr(a) => {841				for item in a.iter() {842					let item = item?;843					if equals(&item, &x)? {844						return Ok(Val::Bool(true));845					}846				}847				Ok(Val::Bool(false))848			}849			_ => unreachable!(),850		}851	})852}853854fn builtin_count(context: Context, _loc: &ExprLocation, args: &ArgsDesc) -> Result<Val> {855	parse_args!(context, "count", args, 2, [856		0, arr: ty!(array) => Val::Arr;857		1, x: ty!(any);858	], {859		let mut count = 0;860		for item in arr.iter() {861			let item = item?;862			if equals(&item, &x)? {863				count += 1;864			}865		}866		Ok(Val::Num(count as f64))867	})868}869870pub fn call_builtin(871	context: Context,872	loc: &ExprLocation,873	name: &str,874	args: &ArgsDesc,875) -> Result<Val> {876	BUILTINS877		.with(|builtins| builtins.get(name).copied())878		.ok_or_else(|| IntrinsicNotFound(name.into()))?(context, loc, args)879}
after · crates/jrsonnet-evaluator/src/builtin/mod.rs
1use crate::typed::{Any, Either, Null, PositiveF64, VecVal, M1};2use crate::{self as jrsonnet_evaluator, ObjValue};3use crate::{4	builtin::manifest::{manifest_yaml_ex, ManifestYamlOptions},5	equals,6	error::{Error::*, Result},7	operator::evaluate_mod_op,8	parse_args, primitive_equals, push_frame, throw, with_state, ArrValue, Context, FuncVal,9	IndexableVal, Val,10};11use format::{format_arr, format_obj};12use gcmodule::Cc;13use jrsonnet_interner::IStr;14use jrsonnet_parser::{ArgsDesc, ExprLocation};15use jrsonnet_types::ty;16use serde::Deserialize;17use serde_yaml::DeserializingQuirks;18use std::{19	collections::HashMap,20	convert::{TryFrom, TryInto},21	path::PathBuf,22	rc::Rc,23};2425pub mod stdlib;26pub use stdlib::*;2728use self::manifest::{escape_string_json, manifest_json_ex, ManifestJsonOptions, ManifestType};2930pub mod format;31pub mod manifest;32pub mod sort;3334pub fn std_format(str: IStr, vals: Val) -> Result<String> {35	push_frame(36		&ExprLocation(Rc::from(PathBuf::from("std.jsonnet")), 0, 0),37		|| format!("std.format of {}", str),38		|| {39			Ok(match vals {40				Val::Arr(vals) => format_arr(&str, &vals.evaluated()?)?,41				Val::Obj(obj) => format_obj(&str, &obj)?,42				o => format_arr(&str, &[o])?,43			})44		},45	)46}4748pub fn std_slice(49	indexable: IndexableVal,50	index: Option<usize>,51	end: Option<usize>,52	step: Option<usize>,53) -> Result<Val> {54	let index = index.unwrap_or(0);55	let end = end.unwrap_or_else(|| match &indexable {56		IndexableVal::Str(_) => usize::MAX,57		IndexableVal::Arr(v) => v.len(),58	});59	let step = step.unwrap_or(1);60	match &indexable {61		IndexableVal::Str(s) => Ok(Val::Str(62			(s.chars()63				.skip(index)64				.take(end - index)65				.step_by(step)66				.collect::<String>())67			.into(),68		)),69		IndexableVal::Arr(arr) => Ok(Val::Arr(70			(arr.iter()71				.skip(index)72				.take(end - index)73				.step_by(step)74				.collect::<Result<Vec<Val>>>()?)75			.into(),76		)),77	}78}7980type Builtin = fn(context: Context, loc: &ExprLocation, args: &ArgsDesc) -> Result<Val>;8182type BuiltinsType = HashMap<Box<str>, Builtin>;8384thread_local! {85	static BUILTINS: BuiltinsType = {86		[87			("length".into(), builtin_length as Builtin),88			("type".into(), builtin_type),89			("makeArray".into(), builtin_make_array),90			("codepoint".into(), builtin_codepoint),91			("objectFieldsEx".into(), builtin_object_fields_ex),92			("objectHasEx".into(), builtin_object_has_ex),93			("slice".into(), builtin_slice),94			("substr".into(), builtin_substr),95			("primitiveEquals".into(), builtin_primitive_equals),96			("equals".into(), builtin_equals),97			("modulo".into(), builtin_modulo),98			("mod".into(), builtin_mod),99			("floor".into(), builtin_floor),100			("ceil".into(), builtin_ceil),101			("log".into(), builtin_log),102			("pow".into(), builtin_pow),103			("sqrt".into(), builtin_sqrt),104			("sin".into(), builtin_sin),105			("cos".into(), builtin_cos),106			("tan".into(), builtin_tan),107			("asin".into(), builtin_asin),108			("acos".into(), builtin_acos),109			("atan".into(), builtin_atan),110			("exp".into(), builtin_exp),111			("mantissa".into(), builtin_mantissa),112			("exponent".into(), builtin_exponent),113			("extVar".into(), builtin_ext_var),114			("native".into(), builtin_native),115			("filter".into(), builtin_filter),116			("map".into(), builtin_map),117			("flatMap".into(), builtin_flatmap),118			("foldl".into(), builtin_foldl),119			("foldr".into(), builtin_foldr),120			("sortImpl".into(), builtin_sort_impl),121			("format".into(), builtin_format),122			("range".into(), builtin_range),123			("char".into(), builtin_char),124			("encodeUTF8".into(), builtin_encode_utf8),125			("decodeUTF8".into(), builtin_decode_utf8),126			("md5".into(), builtin_md5),127			("base64".into(), builtin_base64),128			("base64DecodeBytes".into(), builtin_base64_decode_bytes),129			("base64Decode".into(), builtin_base64_decode),130			("trace".into(), builtin_trace),131			("join".into(), builtin_join),132			("escapeStringJson".into(), builtin_escape_string_json),133			("manifestJsonEx".into(), builtin_manifest_json_ex),134			("manifestYamlDocImpl".into(), builtin_manifest_yaml_doc),135			("reverse".into(), builtin_reverse),136			("id".into(), builtin_id),137			("strReplace".into(), builtin_str_replace),138			("splitLimit".into(), builtin_splitlimit),139			("parseJson".into(), builtin_parse_json),140			("parseYaml".into(), builtin_parse_yaml),141			("asciiUpper".into(), builtin_ascii_upper),142			("asciiLower".into(), builtin_ascii_lower),143			("member".into(), builtin_member),144			("count".into(), builtin_count),145		].iter().cloned().collect()146	};147}148149#[jrsonnet_macros::builtin]150fn builtin_length(x: Either<IStr, Either<VecVal, ObjValue>>) -> Result<usize> {151	Ok(match x {152		Either::Left(x) => x.len(),153		Either::Right(Either::Left(x)) => x.0.len(),154		Either::Right(Either::Right(x)) => x155			.fields_visibility()156			.into_iter()157			.filter(|(_k, v)| *v)158			.count(),159	})160}161162#[jrsonnet_macros::builtin]163fn builtin_type(x: Any) -> Result<IStr> {164	Ok(x.0.value_type().name().into())165}166167#[jrsonnet_macros::builtin]168fn builtin_make_array(sz: usize, func: Cc<FuncVal>) -> Result<VecVal> {169	let mut out = Vec::with_capacity(sz);170	for i in 0..sz {171		out.push(func.evaluate_values(&[Val::Num(i as f64)])?)172	}173	Ok(VecVal(out))174}175176#[jrsonnet_macros::builtin]177const fn builtin_codepoint(str: char) -> Result<u32> {178	Ok(str as u32)179}180181#[jrsonnet_macros::builtin]182fn builtin_object_fields_ex(obj: ObjValue, inc_hidden: bool) -> Result<VecVal> {183	let out = obj.fields_ex(inc_hidden);184	Ok(VecVal(out.into_iter().map(Val::Str).collect::<Vec<_>>()))185}186187#[jrsonnet_macros::builtin]188fn builtin_object_has_ex(obj: ObjValue, f: IStr, inc_hidden: bool) -> Result<bool> {189	Ok(obj.has_field_ex(f, inc_hidden))190}191192#[jrsonnet_macros::builtin]193fn builtin_parse_json(s: IStr) -> Result<Any> {194	let value: serde_json::Value = serde_json::from_str(&s)195		.map_err(|e| RuntimeError(format!("failed to parse json: {}", e).into()))?;196	Ok(Any(Val::try_from(&value)?))197}198199#[jrsonnet_macros::builtin]200fn builtin_parse_yaml(s: IStr) -> Result<Any> {201	let value = serde_yaml::Deserializer::from_str_with_quirks(202		&s,203		DeserializingQuirks { old_octals: true },204	);205	let mut out = vec![];206	for item in value {207		let value = serde_json::Value::deserialize(item)208			.map_err(|e| RuntimeError(format!("failed to parse yaml: {}", e).into()))?;209		let val = Val::try_from(&value)?;210		out.push(val);211	}212	Ok(Any(if out.is_empty() {213		Val::Null214	} else if out.len() == 1 {215		out.into_iter().next().unwrap()216	} else {217		Val::Arr(out.into())218	}))219}220221#[jrsonnet_macros::builtin]222fn builtin_slice(223	indexable: IndexableVal,224	index: Either<usize, Null>,225	end: Either<usize, Null>,226	step: Either<usize, Null>,227) -> Result<Any> {228	std_slice(indexable, index.left(), end.left(), step.left()).map(Any)229}230231#[jrsonnet_macros::builtin]232fn builtin_substr(str: IStr, from: usize, len: usize) -> Result<String> {233	Ok(str.chars().skip(from as usize).take(len as usize).collect())234}235236#[jrsonnet_macros::builtin]237fn builtin_primitive_equals(a: Any, b: Any) -> Result<bool> {238	primitive_equals(&a.0, &b.0)239}240241#[jrsonnet_macros::builtin]242fn builtin_equals(a: Any, b: Any) -> Result<bool> {243	equals(&a.0, &b.0)244}245246#[jrsonnet_macros::builtin]247fn builtin_modulo(a: f64, b: f64) -> Result<f64> {248	Ok(a % b)249}250251#[jrsonnet_macros::builtin]252fn builtin_mod(a: Either<f64, IStr>, b: Any) -> Result<Any> {253	Ok(Any(evaluate_mod_op(254		&match a {255			Either::Left(v) => Val::Num(v),256			Either::Right(s) => Val::Str(s),257		},258		&b.0,259	)?))260}261262#[jrsonnet_macros::builtin]263fn builtin_floor(x: f64) -> Result<f64> {264	Ok(x.floor())265}266267#[jrsonnet_macros::builtin]268fn builtin_ceil(x: f64) -> Result<f64> {269	Ok(x.ceil())270}271272#[jrsonnet_macros::builtin]273fn builtin_log(n: f64) -> Result<f64> {274	Ok(n.ln())275}276277#[jrsonnet_macros::builtin]278fn builtin_pow(x: f64, n: f64) -> Result<f64> {279	Ok(x.powf(n))280}281282#[jrsonnet_macros::builtin]283fn builtin_sqrt(x: PositiveF64) -> Result<f64> {284	Ok(x.0.sqrt())285}286287#[jrsonnet_macros::builtin]288fn builtin_sin(x: f64) -> Result<f64> {289	Ok(x.sin())290}291292#[jrsonnet_macros::builtin]293fn builtin_cos(x: f64) -> Result<f64> {294	Ok(x.cos())295}296297#[jrsonnet_macros::builtin]298fn builtin_tan(x: f64) -> Result<f64> {299	Ok(x.tan())300}301302#[jrsonnet_macros::builtin]303fn builtin_asin(x: f64) -> Result<f64> {304	Ok(x.asin())305}306307#[jrsonnet_macros::builtin]308fn builtin_acos(x: f64) -> Result<f64> {309	Ok(x.acos())310}311312#[jrsonnet_macros::builtin]313fn builtin_atan(x: f64) -> Result<f64> {314	Ok(x.atan())315}316317#[jrsonnet_macros::builtin]318fn builtin_exp(x: f64) -> Result<f64> {319	Ok(x.exp())320}321322fn frexp(s: f64) -> (f64, i16) {323	if 0.0 == s {324		(s, 0)325	} else {326		let lg = s.abs().log2();327		let x = (lg - lg.floor() - 1.0).exp2();328		let exp = lg.floor() + 1.0;329		(s.signum() * x, exp as i16)330	}331}332333#[jrsonnet_macros::builtin]334fn builtin_mantissa(x: f64) -> Result<f64> {335	Ok(frexp(x).0)336}337338#[jrsonnet_macros::builtin]339fn builtin_exponent(x: f64) -> Result<i16> {340	Ok(frexp(x).1)341}342343#[jrsonnet_macros::builtin]344fn builtin_ext_var(x: IStr) -> Result<Any> {345	Ok(Any(with_state(|s| s.settings().ext_vars.get(&x).cloned())346		.ok_or(UndefinedExternalVariable(x))?))347}348349#[jrsonnet_macros::builtin]350fn builtin_native(name: IStr) -> Result<Cc<FuncVal>> {351	Ok(with_state(|s| s.settings().ext_natives.get(&name).cloned())352		.map(|v| Cc::new(FuncVal::NativeExt(name.clone(), v)))353		.ok_or(UndefinedExternalFunction(name))?)354}355356#[jrsonnet_macros::builtin]357fn builtin_filter(func: Cc<FuncVal>, arr: ArrValue) -> Result<ArrValue> {358	arr.filter(|val| bool::try_from(func.evaluate_values(&[val.clone()])?))359}360361#[jrsonnet_macros::builtin]362fn builtin_map(func: Cc<FuncVal>, arr: ArrValue) -> Result<ArrValue> {363	arr.map(|val| func.evaluate_values(&[val]))364}365366#[jrsonnet_macros::builtin]367fn builtin_flatmap(func: Cc<FuncVal>, arr: IndexableVal) -> Result<IndexableVal> {368	match arr {369		IndexableVal::Str(s) => {370			let mut out = String::new();371			for c in s.chars() {372				match func.evaluate_values(&[Val::Str(c.to_string().into())])? {373					Val::Str(o) => out.push_str(&o),374					_ => throw!(RuntimeError(375						"in std.join all items should be strings".into()376					)),377				};378			}379			Ok(IndexableVal::Str(out.into()))380		}381		IndexableVal::Arr(a) => {382			let mut out = Vec::new();383			for el in a.iter() {384				let el = el?;385				match func.evaluate_values(&[el])? {386					Val::Arr(o) => {387						for oe in o.iter() {388							out.push(oe?)389						}390					}391					_ => throw!(RuntimeError(392						"in std.join all items should be arrays".into()393					)),394				};395			}396			Ok(IndexableVal::Arr(out.into()))397		}398	}399}400401#[jrsonnet_macros::builtin]402fn builtin_foldl(func: Cc<FuncVal>, arr: ArrValue, init: Any) -> Result<Any> {403	let mut acc = init.0;404	for i in arr.iter() {405		acc = func.evaluate_values(&[acc, i?])?;406	}407	Ok(Any(acc))408}409410#[jrsonnet_macros::builtin]411fn builtin_foldr(func: Cc<FuncVal>, arr: ArrValue, init: Any) -> Result<Any> {412	let mut acc = init.0;413	for i in arr.iter().rev() {414		acc = func.evaluate_values(&[i?, acc])?;415	}416	Ok(Any(acc))417}418419#[jrsonnet_macros::builtin]420#[allow(non_snake_case)]421fn builtin_sort_impl(arr: ArrValue, keyF: Cc<FuncVal>) -> Result<ArrValue> {422	if arr.len() <= 1 {423		return Ok(arr);424	}425	Ok(ArrValue::Eager(sort::sort(arr.evaluated()?, &keyF)?))426}427428#[jrsonnet_macros::builtin]429fn builtin_format(str: IStr, vals: Any) -> Result<String> {430	std_format(str, vals.0)431}432433#[jrsonnet_macros::builtin]434fn builtin_range(from: i32, to: i32) -> Result<VecVal> {435	if to < from {436		return Ok(VecVal(Vec::new()));437	}438	let mut out = Vec::with_capacity((1 + to as usize - from as usize).max(0));439	for i in from as usize..=to as usize {440		out.push(Val::Num(i as f64));441	}442	Ok(VecVal(out))443}444445#[jrsonnet_macros::builtin]446fn builtin_char(n: u32) -> Result<char> {447	Ok(std::char::from_u32(n as u32).ok_or_else(|| InvalidUnicodeCodepointGot(n as u32))?)448}449450#[jrsonnet_macros::builtin]451fn builtin_encode_utf8(str: IStr) -> Result<VecVal> {452	Ok(VecVal(453		str.bytes()454			.map(|b| Val::Num(b as f64))455			.collect::<Vec<Val>>(),456	))457}458459#[jrsonnet_macros::builtin]460fn builtin_decode_utf8(arr: Vec<u8>) -> Result<String> {461	Ok(String::from_utf8(arr).map_err(|_| RuntimeError("bad utf8".into()))?)462}463464#[jrsonnet_macros::builtin]465fn builtin_md5(str: IStr) -> Result<String> {466	Ok(format!("{:x}", md5::compute(&str.as_bytes())))467}468469fn builtin_trace(context: Context, loc: &ExprLocation, args: &ArgsDesc) -> Result<Val> {470	parse_args!(context, "trace", args, 2, [471		0, str: ty!(string) => Val::Str;472		1, rest: ty!(any);473	], {474		eprint!("TRACE:");475			with_state(|s|{476				let locs = s.map_source_locations(&loc.0, &[loc.1]);477				eprint!(" {}:{}", loc.0.file_name().unwrap().to_str().unwrap(), locs[0].line);478			});479		eprintln!(" {}", str);480		Ok(rest)481	})482}483484#[jrsonnet_macros::builtin]485fn builtin_base64(input: Either<Vec<u8>, IStr>) -> Result<String> {486	Ok(match input {487		Either::Left(a) => base64::encode(a),488		Either::Right(l) => base64::encode(l.bytes().collect::<Vec<_>>()),489	})490}491492#[jrsonnet_macros::builtin]493fn builtin_base64_decode_bytes(input: IStr) -> Result<Vec<u8>> {494	Ok(base64::decode(&input.as_bytes()).map_err(|_| RuntimeError("bad base64".into()))?)495}496497#[jrsonnet_macros::builtin]498fn builtin_base64_decode(input: IStr) -> Result<String> {499	let bytes = base64::decode(&input.as_bytes()).map_err(|_| RuntimeError("bad base64".into()))?;500	Ok(String::from_utf8(bytes).map_err(|_| RuntimeError("bad utf8".into()))?)501}502503#[jrsonnet_macros::builtin]504fn builtin_join(sep: IndexableVal, arr: ArrValue) -> Result<IndexableVal> {505	Ok(match sep {506		IndexableVal::Arr(joiner_items) => {507			let mut out = Vec::new();508509			let mut first = true;510			for item in arr.iter() {511				let item = item?.clone();512				if let Val::Arr(items) = item {513					if !first {514						out.reserve(joiner_items.len());515						// TODO: extend516						for item in joiner_items.iter() {517							out.push(item?);518						}519					}520					first = false;521					out.reserve(items.len());522					// TODO: extend523					for item in items.iter() {524						out.push(item?);525					}526				} else {527					throw!(RuntimeError(528						"in std.join all items should be arrays".into()529					));530				}531			}532533			IndexableVal::Arr(out.into())534		}535		IndexableVal::Str(sep) => {536			let mut out = String::new();537538			let mut first = true;539			for item in arr.iter() {540				let item = item?.clone();541				if let Val::Str(item) = item {542					if !first {543						out += &sep;544					}545					first = false;546					out += &item;547				} else {548					throw!(RuntimeError(549						"in std.join all items should be strings".into()550					));551				}552			}553554			IndexableVal::Str(out.into())555		}556	})557}558559#[jrsonnet_macros::builtin]560fn builtin_escape_string_json(str_: IStr) -> Result<String> {561	Ok(escape_string_json(&str_))562}563564#[jrsonnet_macros::builtin]565fn builtin_manifest_json_ex(value: Any, indent: IStr) -> Result<String> {566	manifest_json_ex(567		&value.0,568		&ManifestJsonOptions {569			padding: &indent,570			mtype: ManifestType::Std,571		},572	)573}574575#[jrsonnet_macros::builtin]576fn builtin_manifest_yaml_doc(577	value: Any,578	indent_array_in_object: bool,579	quote_keys: bool,580) -> Result<String> {581	manifest_yaml_ex(582		&value.0,583		&ManifestYamlOptions {584			padding: "  ",585			arr_element_padding: if indent_array_in_object { "  " } else { "" },586			quote_keys,587		},588	)589}590591#[jrsonnet_macros::builtin]592fn builtin_reverse(value: ArrValue) -> Result<ArrValue> {593	Ok(value.reversed())594}595596#[jrsonnet_macros::builtin]597const fn builtin_id(v: Any) -> Result<Any> {598	Ok(v)599}600601#[jrsonnet_macros::builtin]602fn builtin_str_replace(str: String, from: IStr, to: IStr) -> Result<String> {603	Ok(str.replace(&from as &str, &to as &str))604}605606#[jrsonnet_macros::builtin]607fn builtin_splitlimit(str: IStr, c: char, maxsplits: Either<usize, M1>) -> Result<VecVal> {608	Ok(VecVal(match maxsplits {609		Either::Left(n) => str.splitn(n + 1, c).map(|s| Val::Str(s.into())).collect(),610		Either::Right(_) => str.split(c).map(|s| Val::Str(s.into())).collect(),611	}))612}613614#[jrsonnet_macros::builtin]615fn builtin_ascii_upper(str: IStr) -> Result<String> {616	Ok(str.to_ascii_uppercase())617}618619#[jrsonnet_macros::builtin]620fn builtin_ascii_lower(str: IStr) -> Result<String> {621	Ok(str.to_ascii_lowercase())622}623624#[jrsonnet_macros::builtin]625fn builtin_member(arr: IndexableVal, x: Any) -> Result<bool> {626	match arr {627		IndexableVal::Str(s) => {628			let x: IStr = IStr::try_from(x.0)?;629			Ok(!x.is_empty() && s.contains(&*x))630		}631		IndexableVal::Arr(a) => {632			for item in a.iter() {633				let item = item?;634				if equals(&item, &x.0)? {635					return Ok(true);636				}637			}638			Ok(false)639		}640	}641}642643#[jrsonnet_macros::builtin]644fn builtin_count(arr: Vec<Any>, v: Any) -> Result<usize> {645	let mut count = 0;646	for item in arr.iter() {647		if equals(&item.0, &v.0)? {648			count += 1;649		}650	}651	Ok(count)652}653654pub fn call_builtin(655	context: Context,656	loc: &ExprLocation,657	name: &str,658	args: &ArgsDesc,659) -> Result<Val> {660	BUILTINS661		.with(|builtins| builtins.get(name).copied())662		.ok_or_else(|| IntrinsicNotFound(name.into()))?(context, loc, args)663}
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
--- a/crates/jrsonnet-evaluator/src/val.rs
+++ b/crates/jrsonnet-evaluator/src/val.rs
@@ -170,10 +170,10 @@
 		}
 	}
 
-	pub fn evaluate_values(&self, call_ctx: Context, args: &[Val]) -> Result<Val> {
+	pub fn evaluate_values(&self, args: &[Val]) -> Result<Val> {
 		match self {
 			Self::Normal(func) => {
-				let ctx = place_args(call_ctx, Some(func.ctx.clone()), &func.params, args)?;
+				let ctx = place_args(func.ctx.clone(), &func.params, args)?;
 				evaluate(ctx, &func.body)
 			}
 			Self::Intrinsic(_) => todo!(),
@@ -363,14 +363,6 @@
 	Func(Cc<FuncVal>),
 }
 
-macro_rules! matches_unwrap {
-	($e: expr, $p: pat, $r: expr) => {
-		match $e {
-			$p => $r,
-			_ => panic!("no match"),
-		}
-	};
-}
 impl Val {
 	/// Creates `Val::Num` after checking for numeric overflow.
 	/// As numbers are `f64`, we can just check for their finity.
@@ -382,38 +374,6 @@
 		}
 	}
 
-	pub fn assert_type(&self, context: &'static str, val_type: ValType) -> Result<()> {
-		let this_type = self.value_type();
-		if this_type != val_type {
-			throw!(TypeMismatch(context, vec![val_type], this_type))
-		} else {
-			Ok(())
-		}
-	}
-	pub fn unwrap_num(self) -> Result<f64> {
-		Ok(matches_unwrap!(self, Self::Num(v), v))
-	}
-	pub fn unwrap_str(self) -> Result<IStr> {
-		Ok(matches_unwrap!(self, Self::Str(v), v))
-	}
-	pub fn unwrap_arr(self) -> Result<ArrValue> {
-		Ok(matches_unwrap!(self, Self::Arr(v), v))
-	}
-	pub fn unwrap_func(self) -> Result<Cc<FuncVal>> {
-		Ok(matches_unwrap!(self, Self::Func(v), v))
-	}
-	pub fn try_cast_bool(self, context: &'static str) -> Result<bool> {
-		self.assert_type(context, ValType::Bool)?;
-		Ok(matches_unwrap!(self, Self::Bool(v), v))
-	}
-	pub fn try_cast_str(self, context: &'static str) -> Result<IStr> {
-		self.assert_type(context, ValType::Str)?;
-		Ok(matches_unwrap!(self, Self::Str(v), v))
-	}
-	pub fn try_cast_num(self, context: &'static str) -> Result<f64> {
-		self.assert_type(context, ValType::Num)?;
-		self.unwrap_num()
-	}
 	pub fn try_cast_nullable_num(self, context: &'static str) -> Result<Option<f64>> {
 		Ok(match self {
 			Val::Null => None,
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(())
 	}