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

difftreelog

feat(evaluator) use errors, pass EvaluationState

Лач2020-06-03parent: #b855963.patch.diff
in: master

7 files changed

modifiedcrates/jsonnet-evaluator/Cargo.tomldiffbeforeafterboth
--- a/crates/jsonnet-evaluator/Cargo.toml
+++ b/crates/jsonnet-evaluator/Cargo.toml
@@ -9,6 +9,4 @@
 [dependencies]
 jsonnet-parser = { path = "../jsonnet-parser" }
 closure = "0.3.0"
-
-[dev-dependencies]
 jsonnet-stdlib = { version = "0.1.0", path = "../jsonnet-stdlib" }
modifiedcrates/jsonnet-evaluator/src/ctx.rsdiffbeforeafterboth
--- a/crates/jsonnet-evaluator/src/ctx.rs
+++ b/crates/jsonnet-evaluator/src/ctx.rs
@@ -1,5 +1,6 @@
 use crate::{
-	future_wrapper, lazy_binding, lazy_val, rc_fn_helper, LazyBinding, LazyVal, ObjValue, Val,
+	future_wrapper, lazy_binding, lazy_val, rc_fn_helper, LazyBinding, LazyVal, ObjValue, Result,
+	Val,
 };
 use closure::closure;
 use std::{cell::RefCell, collections::HashMap, fmt::Debug, rc::Rc};
@@ -7,7 +8,7 @@
 rc_fn_helper!(
 	ContextCreator,
 	context_creator,
-	dyn Fn(Option<ObjValue>, Option<ObjValue>) -> Context
+	dyn Fn(Option<ObjValue>, Option<ObjValue>) -> Result<Context>
 );
 
 future_wrapper!(Context, FutureContext);
@@ -65,12 +66,12 @@
 		ctx.unwrap()
 	}
 
-	pub fn with_var(&self, name: String, value: Val) -> Context {
+	pub fn with_var(&self, name: String, value: Val) -> Result<Context> {
 		let mut new_bindings: HashMap<_, LazyBinding> = HashMap::new();
 		new_bindings.insert(
 			name,
 			lazy_binding!(
-				closure!(clone value, |_t, _s|lazy_val!(closure!(clone value, ||value.clone())))
+				closure!(clone value, |_t, _s|Ok(lazy_val!(closure!(clone value, ||Ok(value.clone())))))
 			),
 		);
 		self.extend(new_bindings, None, None, None)
@@ -82,7 +83,7 @@
 		new_dollar: Option<ObjValue>,
 		new_this: Option<ObjValue>,
 		new_super_obj: Option<ObjValue>,
-	) -> Context {
+	) -> Result<Context> {
 		let dollar = new_dollar.or_else(|| self.0.dollar.clone());
 		let this = new_this.or_else(|| self.0.this.clone());
 		let super_obj = new_super_obj.or_else(|| self.0.super_obj.clone());
@@ -94,16 +95,16 @@
 				new.insert(k.clone(), v.clone());
 			}
 			for (k, v) in new_bindings.into_iter() {
-				new.insert(k, v.0(this.clone(), super_obj.clone()));
+				new.insert(k, v.0(this.clone(), super_obj.clone())?);
 			}
 			Rc::new(new)
 		};
-		Context(Rc::new(ContextInternals {
+		Ok(Context(Rc::new(ContextInternals {
 			dollar,
 			this,
 			super_obj,
 			bindings,
-		}))
+		})))
 	}
 }
 
modifiedcrates/jsonnet-evaluator/src/error.rsdiffbeforeafterboth
--- a/crates/jsonnet-evaluator/src/error.rs
+++ b/crates/jsonnet-evaluator/src/error.rs
@@ -1 +1,20 @@
-pub enum Error {}
+use crate::ValType;
+use jsonnet_parser::LocExpr;
+
+#[derive(Debug)]
+pub enum Error {
+	VariableIsNotDefined(String),
+	TypeMismatch(&'static str, Vec<ValType>, ValType),
+	NoSuchField(String),
+
+	RuntimeError(String),
+}
+
+#[derive(Clone, Debug)]
+pub struct StackTraceElement(pub LocExpr, pub String);
+#[derive(Debug)]
+pub struct StackTrace(pub Vec<StackTraceElement>);
+
+#[derive(Debug)]
+pub struct LocError(pub Error, pub StackTrace);
+pub type Result<V> = std::result::Result<V, LocError>;
modifiedcrates/jsonnet-evaluator/src/evaluate.rsdiffbeforeafterboth
before · crates/jsonnet-evaluator/src/evaluate.rs
1use crate::{2	binding, bool_val, context_creator, function_default, function_rhs, future_wrapper,3	lazy_binding, lazy_val, Context, ContextCreator, EvaluationState, FuncDesc, LazyBinding,4	ObjMember, ObjValue, Val,5};6use closure::closure;7use jsonnet_parser::{8	el, Arg, ArgsDesc, AssertStmt, BinaryOpType, BindSpec, CompSpec, Expr, FieldMember,9	ForSpecData, IfSpecData, LiteralType, LocExpr, Member, ObjBody, ParamsDesc, UnaryOpType,10	Visibility,11};12use std::{13	collections::{BTreeMap, HashMap},14	rc::Rc,15};1617pub fn evaluate_binding(18	eval_state: EvaluationState,19	b: &BindSpec,20	context_creator: ContextCreator,21) -> (String, LazyBinding) {22	let b = b.clone();23	if let Some(args) = &b.params {24		let args = args.clone();25		(26			b.name.clone(),27			lazy_binding!(move |this, super_obj| lazy_val!(28				closure!(clone b, clone args, clone context_creator, clone eval_state, || evaluate_method(29					context_creator.0(this.clone(), super_obj.clone()),30					eval_state.clone(),31					&b.value,32					args.clone()33				))34			)),35		)36	} else {37		(38			b.name.clone(),39			lazy_binding!(move |this, super_obj| {40				lazy_val!(41					closure!(clone context_creator, clone b, clone eval_state, || evaluate(42						context_creator.0(this.clone(), super_obj.clone()),43						eval_state.clone(),44						&b.value45					))46				)47			}),48		)49	}50}5152pub fn evaluate_method(53	ctx: Context,54	eval_state: EvaluationState,55	expr: &LocExpr,56	arg_spec: ParamsDesc,57) -> Val {58	Val::Func(FuncDesc {59		ctx,60		params: arg_spec,61		eval_rhs: function_rhs!(62			closure!(clone expr, clone eval_state, |ctx| evaluate(ctx, eval_state.clone(), &expr))63		),64		eval_default: function_default!(65			closure!(clone eval_state, |ctx, default| evaluate(ctx, eval_state.clone(), &default))66		),67	})68}6970pub fn evaluate_field_name(71	context: Context,72	eval_state: EvaluationState,73	field_name: &jsonnet_parser::FieldName,74) -> String {75	match field_name {76		jsonnet_parser::FieldName::Fixed(n) => n.clone(),77		jsonnet_parser::FieldName::Dyn(expr) => {78			let name = evaluate(context, eval_state, expr).unwrap_if_lazy();79			match name {80				Val::Str(n) => n,81				_ => panic!(82					"dynamic field name can be only evaluated to 'string', got: {:?}",83					name84				),85			}86		}87	}88}8990pub fn evaluate_unary_op(op: UnaryOpType, b: &Val) -> Val {91	match (op, b) {92		(o, Val::Lazy(l)) => evaluate_unary_op(o, &l.evaluate()),93		(UnaryOpType::Not, Val::Bool(v)) => Val::Bool(!v),94		(op, o) => panic!("unary op not implemented: {:?} {:?}", op, o),95	}96}9798pub fn evaluate_add_op(a: &Val, b: &Val) -> Val {99	match (a, b) {100		(Val::Str(v1), Val::Str(v2)) => Val::Str(v1.to_owned() + &v2),101		(Val::Str(v1), Val::Num(v2)) => Val::Str(format!("{}{}", v1, v2)),102		(Val::Num(v1), Val::Str(v2)) => Val::Str(format!("{}{}", v1, v2)),103		(Val::Obj(v1), Val::Obj(v2)) => Val::Obj(v2.with_super(v1.clone())),104		(Val::Arr(a), Val::Arr(b)) => Val::Arr([&a[..], &b[..]].concat()),105		(Val::Num(v1), Val::Num(v2)) => Val::Num(v1 + v2),106		_ => panic!("can't add: {:?} and {:?}", a, b),107	}108}109110pub fn evaluate_binary_op(111	context: Context,112	eval_state: EvaluationState,113	a: &Val,114	op: BinaryOpType,115	b: &Val,116) -> Val {117	match (a, op, b) {118		(Val::Lazy(a), o, b) => evaluate_binary_op(context, eval_state, &a.evaluate(), o, b),119		(a, o, Val::Lazy(b)) => evaluate_binary_op(context, eval_state, a, o, &b.evaluate()),120121		(a, BinaryOpType::Add, b) => evaluate_add_op(a, b),122123		(Val::Str(v1), BinaryOpType::Ne, Val::Str(v2)) => bool_val(v1 != v2),124125		(Val::Str(v1), BinaryOpType::Mul, Val::Num(v2)) => Val::Str(v1.repeat(*v2 as usize)),126		(Val::Str(format), BinaryOpType::Mod, args) => evaluate(127			context128				.with_var("__tmp__format__".to_owned(), Val::Str(format.to_owned()))129				.with_var(130					"__tmp__args__".to_owned(),131					match args {132						Val::Arr(v) => Val::Arr(v.clone()),133						v => Val::Arr(vec![v.clone()]),134					},135				),136			eval_state,137			&el!(Expr::Apply(138				el!(Expr::Index(139					el!(Expr::Var("std".to_owned())),140					el!(Expr::Str("format".to_owned()))141				)),142				ArgsDesc(vec![143					Arg(None, el!(Expr::Var("__tmp__format__".to_owned()))),144					Arg(None, el!(Expr::Var("__tmp__args__".to_owned())))145				])146			)),147		),148149		(Val::Bool(a), BinaryOpType::And, Val::Bool(b)) => Val::Bool(*a && *b),150		(Val::Bool(a), BinaryOpType::Or, Val::Bool(b)) => Val::Bool(*a || *b),151152		(Val::Num(v1), BinaryOpType::Mul, Val::Num(v2)) => Val::Num(v1 * v2),153		(Val::Num(v1), BinaryOpType::Div, Val::Num(v2)) => Val::Num(v1 / v2),154		(Val::Num(v1), BinaryOpType::Mod, Val::Num(v2)) => Val::Num(v1 % v2),155156		(Val::Num(v1), BinaryOpType::Sub, Val::Num(v2)) => Val::Num(v1 - v2),157158		(Val::Num(v1), BinaryOpType::Lhs, Val::Num(v2)) => {159			Val::Num(((*v1 as i32) << (*v2 as i32)) as f64)160		}161		(Val::Num(v1), BinaryOpType::Rhs, Val::Num(v2)) => {162			Val::Num(((*v1 as i32) >> (*v2 as i32)) as f64)163		}164165		(Val::Num(v1), BinaryOpType::Lt, Val::Num(v2)) => bool_val(v1 < v2),166		(Val::Num(v1), BinaryOpType::Gt, Val::Num(v2)) => bool_val(v1 > v2),167		(Val::Num(v1), BinaryOpType::Lte, Val::Num(v2)) => bool_val(v1 <= v2),168		(Val::Num(v1), BinaryOpType::Gte, Val::Num(v2)) => bool_val(v1 >= v2),169170		(Val::Num(v1), BinaryOpType::Eq, Val::Num(v2)) => bool_val((v1 - v2).abs() < f64::EPSILON),171		(Val::Num(v1), BinaryOpType::Ne, Val::Num(v2)) => bool_val((v1 - v2).abs() > f64::EPSILON),172173		(Val::Num(v1), BinaryOpType::BitAnd, Val::Num(v2)) => {174			Val::Num(((*v1 as i32) & (*v2 as i32)) as f64)175		}176		(Val::Num(v1), BinaryOpType::BitOr, Val::Num(v2)) => {177			Val::Num(((*v1 as i32) | (*v2 as i32)) as f64)178		}179		(Val::Num(v1), BinaryOpType::BitXor, Val::Num(v2)) => {180			Val::Num(((*v1 as i32) ^ (*v2 as i32)) as f64)181		}182		(a, BinaryOpType::Eq, b) => bool_val(a == b),183		(a, BinaryOpType::Ne, b) => bool_val(a != b),184		_ => panic!("no rules for binary operation: {:?} {:?} {:?}", a, op, b),185	}186}187188future_wrapper!(HashMap<String, LazyBinding>, FutureNewBindings);189future_wrapper!(ObjValue, FutureObjValue);190191pub fn evaluate_comp(192	context: Context,193	eval_state: EvaluationState,194	value: &LocExpr,195	specs: &[CompSpec],196) -> Option<Vec<Val>> {197	match specs.get(0) {198		None => Some(vec![evaluate(context, eval_state, &value)]),199		Some(CompSpec::IfSpec(IfSpecData(cond))) => {200			match evaluate(context.clone(), eval_state.clone(), &cond).unwrap_if_lazy() {201				Val::Bool(false) => None,202				Val::Bool(true) => evaluate_comp(context, eval_state, value, &specs[1..]),203				_ => panic!("if expression evaluated to non-boolean value"),204			}205		}206		Some(CompSpec::ForSpec(ForSpecData(var, expr))) => {207			match evaluate(context.clone(), eval_state.clone(), &expr).unwrap_if_lazy() {208				Val::Arr(list) => {209					let mut out = Vec::new();210					for item in list {211						let item = item.clone();212						out.push(evaluate_comp(213							context.with_var(var.clone(), item),214							eval_state.clone(),215							value,216							&specs[1..],217						));218					}219					Some(out.iter().flatten().flatten().cloned().collect())220				}221				_ => panic!("for expression evaluated to non-iterable value"),222			}223		}224	}225}226227// TODO: Asserts228pub fn evaluate_object(context: Context, eval_state: EvaluationState, object: ObjBody) -> ObjValue {229	match object {230		ObjBody::MemberList(members) => {231			let new_bindings = FutureNewBindings::new();232			let future_this = FutureObjValue::new();233			let context_creator = context_creator!(234				closure!(clone context, clone new_bindings, clone future_this, |this: Option<ObjValue>, super_obj: Option<ObjValue>| {235					context.clone().extend(236						new_bindings.clone().unwrap(),237						context.clone().dollar().clone().or_else(||this.clone()),238						Some(this.unwrap()),239						super_obj240					)241				})242			);243			{244				let mut bindings: HashMap<String, LazyBinding> = HashMap::new();245				for (n, b) in members246					.iter()247					.filter_map(|m| match m {248						Member::BindStmt(b) => Some(b.clone()),249						_ => None,250					})251					.map(|b| evaluate_binding(eval_state.clone(), &b, context_creator.clone()))252				{253					bindings.insert(n, b);254				}255				new_bindings.fill(bindings);256			}257258			let mut new_members = BTreeMap::new();259			for member in members.into_iter() {260				match member {261					Member::Field(FieldMember {262						name,263						plus,264						params: None,265						visibility,266						value,267					}) => {268						let name = evaluate_field_name(context.clone(), eval_state.clone(), &name);269						new_members.insert(270							name,271							ObjMember {272								add: plus,273								visibility: visibility.clone(),274								invoke: binding!(275									closure!(clone value, clone context_creator, clone eval_state, |this, super_obj| {276										let context = context_creator.0(this, super_obj);277										// TODO: Assert278										evaluate(279											context,280											eval_state.clone(),281											&value,282										).unwrap_if_lazy()283									})284								),285							},286						);287					}288					Member::Field(FieldMember {289						name,290						params: Some(params),291						value,292						..293					}) => {294						let name = evaluate_field_name(context.clone(), eval_state.clone(), &name);295						new_members.insert(296							name,297							ObjMember {298								add: false,299								visibility: Visibility::Hidden,300								invoke: binding!(301									closure!(clone value, clone context_creator, clone eval_state, |this, super_obj| {302										// TODO: Assert303										evaluate_method(304											context_creator.0(this, super_obj),305											eval_state.clone(),306											&value.clone(),307											params.clone(),308										)309									})310								),311							},312						);313					}314					Member::BindStmt(_) => {}315					Member::AssertStmt(_) => {}316				}317			}318			future_this.fill(ObjValue::new(None, Rc::new(new_members)))319		}320		_ => todo!(),321	}322}323324pub fn evaluate(context: Context, eval_state: EvaluationState, expr: &LocExpr) -> Val {325	use Expr::*;326	eval_state.clone().push(expr.clone(), "expr".to_owned(), || {327		let LocExpr(expr, loc) = expr;328		match &**expr {329			Literal(LiteralType::This) => Val::Obj(330				context331					.this()332					.clone()333					.unwrap_or_else(|| panic!("this not found")),334			),335			Literal(LiteralType::Super) => Val::Obj(336				context337					.super_obj()338					.clone()339					.unwrap_or_else(|| panic!("super not found")),340			),341			Literal(LiteralType::True) => Val::Bool(true),342			Literal(LiteralType::False) => Val::Bool(false),343			Literal(LiteralType::Null) => Val::Null,344			Parened(e) => evaluate(context, eval_state.clone(), e),345			Str(v) => Val::Str(v.clone()),346			Num(v) => Val::Num(*v),347			BinaryOp(v1, o, v2) => {348				let a = evaluate(context.clone(), eval_state.clone(), v1).unwrap_if_lazy();349				let op = *o;350				let b = evaluate(context.clone(), eval_state.clone(), v2).unwrap_if_lazy();351				evaluate_binary_op(352					context,353					eval_state,354					&a,355					op,356					&b,357				)358			},359			UnaryOp(o, v) => evaluate_unary_op(*o, &evaluate(context, eval_state, v)),360			Var(name) => Val::Lazy(context.binding(&name)).unwrap_if_lazy(),361			Index(value, index) => {362				match (363					evaluate(context.clone(), eval_state.clone(), value).unwrap_if_lazy(),364					evaluate(context.clone(), eval_state.clone(), index),365				) {366					(Val::Obj(v), Val::Str(s)) => v367						.get(&s)368						.unwrap_or_else(closure!(clone context, clone eval_state, || {369							if let Some(n) = v.get("__intristic_namespace__") {370								if let Val::Str(n) = n.unwrap_if_lazy() {371									Val::Intristic(n, s)372								} else {373									panic!("__intristic_namespace__ should be string");374								}375							} else {376								panic!("{} not found in {:?}", s, v)377							}378						}))379						.unwrap_if_lazy(),380					(Val::Arr(v), Val::Num(n)) => v381						.get(n as usize)382						.unwrap_or_else(|| panic!("out of bounds"))383						.clone(),384					(Val::Str(s), Val::Num(n)) => {385						Val::Str(s.chars().skip(n as usize).take(1).collect())386					}387					(v, i) => todo!("not implemented: {:?}[{:?}]", v, i.unwrap_if_lazy()),388				}389			}390			LocalExpr(bindings, returned) => {391				let mut new_bindings: HashMap<String, LazyBinding> = HashMap::new();392				let future_context = Context::new_future();393394				let context_creator = context_creator!(395					closure!(clone future_context, |_, _| future_context.clone().unwrap())396				);397398				for (k, v) in bindings399					.iter()400					.map(|b| evaluate_binding(eval_state.clone(), b, context_creator.clone()))401				{402					new_bindings.insert(k, v);403				}404405				let context = context406					.extend(new_bindings, None, None, None)407					.into_future(future_context);408				evaluate(context, eval_state.clone(), &returned.clone())409			}410			Arr(items) => {411				let mut out = Vec::with_capacity(items.len());412				for item in items {413					out.push(evaluate(context.clone(), eval_state.clone(), item));414				}415				Val::Arr(out)416			}417			ArrComp(expr, compspecs) => {418				Val::Arr(evaluate_comp(context, eval_state, expr, compspecs).unwrap())419			}420			Obj(body) => Val::Obj(evaluate_object(context, eval_state, body.clone())),421			Apply(value, ArgsDesc(args)) => {422				let value = evaluate(context.clone(), eval_state.clone(), value).unwrap_if_lazy();423				match value {424					// TODO: Capture context of application425					Val::Intristic(ns, name) => match (&ns as &str, &name as &str) {426						// arr/string/function427						("std", "length") => {428							assert_eq!(args.len(), 1);429							let expr = &args.get(0).unwrap().1;430							match evaluate(context, eval_state.clone(), expr) {431								Val::Str(n) => Val::Num(n.chars().count() as f64),432								Val::Arr(i) => Val::Num(i.len() as f64),433								v => panic!("can't get length of {:?}", v),434							}435						}436						// any437						("std", "type") => {438							assert_eq!(args.len(), 1);439							let expr = &args.get(0).unwrap().1;440							Val::Str(evaluate(context, eval_state, expr).type_of().to_owned())441						}442						// length, idx=>any443						("std", "makeArray") => {444							assert_eq!(args.len(), 2);445							if let (Val::Num(v), Val::Func(d)) = (446								evaluate(context.clone(), eval_state.clone(), &args[0].1),447								evaluate(context, eval_state, &args[1].1),448							) {449								assert!(v > 0.0);450								let mut out = Vec::with_capacity(v as usize);451								for i in 0..v as usize {452									out.push(d.evaluate(vec![(None, Val::Num(i as f64))]))453								}454								Val::Arr(out)455							} else {456								panic!("bad makeArray call");457							}458						}459						// string460						("std", "codepoint") => {461							assert_eq!(args.len(), 1);462							if let Val::Str(s) = evaluate(context, eval_state, &args[0].1) {463								assert!(464									s.chars().count() == 1,465									"std.codepoint should receive single char string"466								);467								Val::Num(s.chars().take(1).next().unwrap() as u32 as f64)468							} else {469								panic!("bad codepoint call");470							}471						}472						// object, includeHidden473						("std", "objectFieldsEx") => {474							assert_eq!(args.len(), 2);475							if let (Val::Obj(body), Val::Bool(_include_hidden)) = (476								evaluate(context.clone(), eval_state.clone(), &args[0].1),477								evaluate(context, eval_state, &args[1].1),478							) {479								// TODO: handle visibility (_include_hidden)480								Val::Arr(body.fields().into_iter().map(Val::Str).collect())481							} else {482								panic!("bad objectFieldsEx call");483							}484						}485						(ns, name) => panic!("Intristic not found: {}.{}", ns, name),486					},487					Val::Func(f) => f.evaluate(488						args.clone()489							.into_iter()490							.map(move |a| {491								(492									a.clone().0,493									Val::Lazy(lazy_val!(494										closure!(clone context, clone a, clone eval_state, || evaluate(context.clone(), eval_state.clone(), &a.clone().1))495									)),496								)497							})498							.collect(),499					),500					_ => panic!("{:?} is not a function", value),501				}502			}503			Function(params, body) => evaluate_method(context, eval_state, body, params.clone()),504			AssertExpr(AssertStmt(value, msg), returned) => {505				if evaluate(context.clone(), eval_state.clone(), &value).try_cast_bool() {506					evaluate(context, eval_state, returned)507				}else {508					if let Some(msg) = msg {509						panic!("assertion failed ({:?}): {}", value, evaluate(context, eval_state, msg).try_cast_str());510					} else {511						panic!("assertion failed ({:?}): no message", value);512					}513				}514			},515			Error(e) => panic!("error: {}", evaluate(context, eval_state, e)),516			IfElse {517				cond,518				cond_then,519				cond_else,520			} => match evaluate(context.clone(), eval_state.clone(), &cond.0).unwrap_if_lazy() {521				Val::Bool(true) => evaluate(context, eval_state.clone(), cond_then),522				Val::Bool(false) => match cond_else {523					Some(v) => evaluate(context, eval_state, v),524					None => Val::Bool(false),525				},526				v => panic!("if condition evaluated to {:?} (boolean needed instead)", v),527			},528			_ => panic!(529				"evaluation not implemented: {:?}",530				LocExpr(expr.clone(), loc.clone())531			),532		}533	})534}
after · crates/jsonnet-evaluator/src/evaluate.rs
1use crate::{2	binding, context_creator, create_error, function_default, function_rhs, future_wrapper,3	lazy_binding, lazy_val, push, Context, ContextCreator, FuncDesc, LazyBinding, ObjMember,4	ObjValue, Result, Val,5};6use closure::closure;7use jsonnet_parser::{8	el, Arg, ArgsDesc, AssertStmt, BinaryOpType, BindSpec, CompSpec, Expr, FieldMember,9	ForSpecData, IfSpecData, LiteralType, LocExpr, Member, ObjBody, ParamsDesc, UnaryOpType,10	Visibility,11};12use std::{13	collections::{BTreeMap, HashMap},14	rc::Rc,15};1617pub fn evaluate_binding(b: &BindSpec, context_creator: ContextCreator) -> (String, LazyBinding) {18	let b = b.clone();19	if let Some(args) = &b.params {20		let args = args.clone();21		(22			b.name.clone(),23			lazy_binding!(move |this, super_obj| Ok(lazy_val!(24				closure!(clone b, clone args, clone context_creator, || Ok(evaluate_method(25					context_creator.0(this.clone(), super_obj.clone())?,26					&b.value,27					args.clone()28				)))29			))),30		)31	} else {32		(33			b.name.clone(),34			lazy_binding!(move |this, super_obj| {35				Ok(lazy_val!(36					closure!(clone context_creator, clone b, || evaluate(37						context_creator.0(this.clone(), super_obj.clone())?,38						&b.value39					))40				))41			}),42		)43	}44}4546pub fn evaluate_method(ctx: Context, expr: &LocExpr, arg_spec: ParamsDesc) -> Val {47	Val::Func(FuncDesc {48		ctx,49		params: arg_spec,50		eval_rhs: function_rhs!(closure!(clone expr, |ctx| evaluate(ctx, &expr))),51		eval_default: function_default!(closure!(|ctx, default| evaluate(ctx, &default))),52	})53}5455pub fn evaluate_field_name(56	context: Context,57	field_name: &jsonnet_parser::FieldName,58) -> Result<String> {59	Ok(match field_name {60		jsonnet_parser::FieldName::Fixed(n) => n.clone(),61		jsonnet_parser::FieldName::Dyn(expr) => {62			evaluate(context, expr)?.try_cast_str("dynamic field name")?63		}64	})65}6667pub fn evaluate_unary_op(op: UnaryOpType, b: &Val) -> Result<Val> {68	Ok(match (op, b) {69		(o, Val::Lazy(l)) => evaluate_unary_op(o, &l.evaluate()?)?,70		(UnaryOpType::Not, Val::Bool(v)) => Val::Bool(!v),71		(op, o) => panic!("unary op not implemented: {:?} {:?}", op, o),72	})73}7475pub(crate) fn evaluate_add_op(a: &Val, b: &Val) -> Result<Val> {76	Ok(match (a, b) {77		(Val::Str(v1), Val::Str(v2)) => Val::Str(v1.to_owned() + &v2),78		(Val::Str(v1), Val::Num(v2)) => Val::Str(format!("{}{}", v1, v2)),79		(Val::Num(v1), Val::Str(v2)) => Val::Str(format!("{}{}", v1, v2)),80		(Val::Obj(v1), Val::Obj(v2)) => Val::Obj(v2.with_super(v1.clone())),81		(Val::Arr(a), Val::Arr(b)) => Val::Arr([&a[..], &b[..]].concat()),82		(Val::Num(v1), Val::Num(v2)) => Val::Num(v1 + v2),83		_ => panic!("can't add: {:?} and {:?}", a, b),84	})85}8687pub fn evaluate_binary_op(context: Context, a: &Val, op: BinaryOpType, b: &Val) -> Result<Val> {88	Ok(match (a, op, b) {89		(Val::Lazy(a), o, b) => evaluate_binary_op(context, &a.evaluate()?, o, b)?,90		(a, o, Val::Lazy(b)) => evaluate_binary_op(context, a, o, &b.evaluate()?)?,9192		(a, BinaryOpType::Add, b) => evaluate_add_op(a, b)?,9394		(Val::Str(v1), BinaryOpType::Ne, Val::Str(v2)) => Val::Bool(v1 != v2),9596		(Val::Str(v1), BinaryOpType::Mul, Val::Num(v2)) => Val::Str(v1.repeat(*v2 as usize)),97		(Val::Str(format), BinaryOpType::Mod, args) => evaluate(98			context99				.with_var("__tmp__format__".to_owned(), Val::Str(format.to_owned()))?100				.with_var(101					"__tmp__args__".to_owned(),102					match args {103						Val::Arr(v) => Val::Arr(v.clone()),104						v => Val::Arr(vec![v.clone()]),105					},106				)?,107			&el!(Expr::Apply(108				el!(Expr::Index(109					el!(Expr::Var("std".to_owned())),110					el!(Expr::Str("format".to_owned()))111				)),112				ArgsDesc(vec![113					Arg(None, el!(Expr::Var("__tmp__format__".to_owned()))),114					Arg(None, el!(Expr::Var("__tmp__args__".to_owned())))115				])116			)),117		)?,118119		(Val::Bool(a), BinaryOpType::And, Val::Bool(b)) => Val::Bool(*a && *b),120		(Val::Bool(a), BinaryOpType::Or, Val::Bool(b)) => Val::Bool(*a || *b),121122		(Val::Num(v1), BinaryOpType::Mul, Val::Num(v2)) => Val::Num(v1 * v2),123		(Val::Num(v1), BinaryOpType::Div, Val::Num(v2)) => Val::Num(v1 / v2),124		(Val::Num(v1), BinaryOpType::Mod, Val::Num(v2)) => Val::Num(v1 % v2),125126		(Val::Num(v1), BinaryOpType::Sub, Val::Num(v2)) => Val::Num(v1 - v2),127128		(Val::Num(v1), BinaryOpType::Lhs, Val::Num(v2)) => {129			Val::Num(((*v1 as i32) << (*v2 as i32)) as f64)130		}131		(Val::Num(v1), BinaryOpType::Rhs, Val::Num(v2)) => {132			Val::Num(((*v1 as i32) >> (*v2 as i32)) as f64)133		}134135		(Val::Num(v1), BinaryOpType::Lt, Val::Num(v2)) => Val::Bool(v1 < v2),136		(Val::Num(v1), BinaryOpType::Gt, Val::Num(v2)) => Val::Bool(v1 > v2),137		(Val::Num(v1), BinaryOpType::Lte, Val::Num(v2)) => Val::Bool(v1 <= v2),138		(Val::Num(v1), BinaryOpType::Gte, Val::Num(v2)) => Val::Bool(v1 >= v2),139140		(Val::Num(v1), BinaryOpType::Eq, Val::Num(v2)) => Val::Bool((v1 - v2).abs() < f64::EPSILON),141		(Val::Num(v1), BinaryOpType::Ne, Val::Num(v2)) => Val::Bool((v1 - v2).abs() > f64::EPSILON),142143		(Val::Num(v1), BinaryOpType::BitAnd, Val::Num(v2)) => {144			Val::Num(((*v1 as i32) & (*v2 as i32)) as f64)145		}146		(Val::Num(v1), BinaryOpType::BitOr, Val::Num(v2)) => {147			Val::Num(((*v1 as i32) | (*v2 as i32)) as f64)148		}149		(Val::Num(v1), BinaryOpType::BitXor, Val::Num(v2)) => {150			Val::Num(((*v1 as i32) ^ (*v2 as i32)) as f64)151		}152		(a, BinaryOpType::Eq, b) => Val::Bool(a == b),153		(a, BinaryOpType::Ne, b) => Val::Bool(a != b),154		_ => panic!("no rules for binary operation: {:?} {:?} {:?}", a, op, b),155	})156}157158future_wrapper!(HashMap<String, LazyBinding>, FutureNewBindings);159future_wrapper!(ObjValue, FutureObjValue);160161pub fn evaluate_comp(162	context: Context,163	value: &LocExpr,164	specs: &[CompSpec],165) -> Result<Option<Vec<Val>>> {166	Ok(match specs.get(0) {167		None => Some(vec![evaluate(context, &value)?]),168		Some(CompSpec::IfSpec(IfSpecData(cond))) => {169			if evaluate(context.clone(), &cond)?.try_cast_bool("if spec")? {170				evaluate_comp(context, value, &specs[1..])?171			} else {172				None173			}174		}175		Some(CompSpec::ForSpec(ForSpecData(var, expr))) => {176			match evaluate(context.clone(), &expr)?.unwrap_if_lazy()? {177				Val::Arr(list) => {178					let mut out = Vec::new();179					for item in list {180						let item = item.clone();181						out.push(evaluate_comp(182							context.with_var(var.clone(), item)?,183							value,184							&specs[1..],185						)?);186					}187					Some(out.iter().flatten().flatten().cloned().collect())188				}189				_ => panic!("for expression evaluated to non-iterable value"),190			}191		}192	})193}194195// TODO: Asserts196pub fn evaluate_object(context: Context, object: ObjBody) -> Result<ObjValue> {197	Ok(match object {198		ObjBody::MemberList(members) => {199			let new_bindings = FutureNewBindings::new();200			let future_this = FutureObjValue::new();201			let context_creator = context_creator!(202				closure!(clone context, clone new_bindings, clone future_this, |this: Option<ObjValue>, super_obj: Option<ObjValue>| {203					Ok(context.clone().extend(204						new_bindings.clone().unwrap(),205						context.clone().dollar().clone().or_else(||this.clone()),206						Some(this.unwrap()),207						super_obj208					)?)209				})210			);211			{212				let mut bindings: HashMap<String, LazyBinding> = HashMap::new();213				for (n, b) in members214					.iter()215					.filter_map(|m| match m {216						Member::BindStmt(b) => Some(b.clone()),217						_ => None,218					})219					.map(|b| evaluate_binding(&b, context_creator.clone()))220				{221					bindings.insert(n, b);222				}223				new_bindings.fill(bindings);224			}225226			let mut new_members = BTreeMap::new();227			for member in members.into_iter() {228				match member {229					Member::Field(FieldMember {230						name,231						plus,232						params: None,233						visibility,234						value,235					}) => {236						let name = evaluate_field_name(context.clone(), &name)?;237						new_members.insert(238							name,239							ObjMember {240								add: plus,241								visibility: visibility.clone(),242								invoke: binding!(243									closure!(clone value, clone context_creator, |this, super_obj| {244										let context = context_creator.0(this, super_obj)?;245										// TODO: Assert246										evaluate(247											context,248											&value,249										)?.unwrap_if_lazy()250									})251								),252							},253						);254					}255					Member::Field(FieldMember {256						name,257						params: Some(params),258						value,259						..260					}) => {261						let name = evaluate_field_name(context.clone(), &name)?;262						new_members.insert(263							name,264							ObjMember {265								add: false,266								visibility: Visibility::Hidden,267								invoke: binding!(268									closure!(clone value, clone context_creator, |this, super_obj| {269										// TODO: Assert270										Ok(evaluate_method(271											context_creator.0(this, super_obj)?,272											&value.clone(),273											params.clone(),274										))275									})276								),277							},278						);279					}280					Member::BindStmt(_) => {}281					Member::AssertStmt(_) => {}282				}283			}284			future_this.fill(ObjValue::new(None, Rc::new(new_members)))285		}286		_ => todo!(),287	})288}289290pub fn evaluate(context: Context, expr: &LocExpr) -> Result<Val> {291	use Expr::*;292	push(expr.clone(), "expr".to_owned(), || {293		let LocExpr(expr, loc) = expr;294		Ok(match &**expr {295			Literal(LiteralType::This) => Val::Obj(296				context297					.this()298					.clone()299					.unwrap_or_else(|| panic!("this not found")),300			),301			Literal(LiteralType::Super) => Val::Obj(302				context303					.super_obj()304					.clone()305					.unwrap_or_else(|| panic!("super not found")),306			),307			Literal(LiteralType::True) => Val::Bool(true),308			Literal(LiteralType::False) => Val::Bool(false),309			Literal(LiteralType::Null) => Val::Null,310			Parened(e) => evaluate(context, e)?,311			Str(v) => Val::Str(v.clone()),312			Num(v) => Val::Num(*v),313			BinaryOp(v1, o, v2) => {314				let a = evaluate(context.clone(), v1)?.unwrap_if_lazy()?;315				let op = *o;316				let b = evaluate(context.clone(), v2)?.unwrap_if_lazy()?;317				evaluate_binary_op(context, &a, op, &b)?318			}319			UnaryOp(o, v) => evaluate_unary_op(*o, &evaluate(context, v)?)?,320			Var(name) => Val::Lazy(context.binding(&name)).unwrap_if_lazy()?,321			Index(value, index) => {322				match (323					evaluate(context.clone(), value)?.unwrap_if_lazy()?,324					evaluate(context.clone(), index)?,325				) {326					(Val::Obj(v), Val::Str(s)) => {327						if let Some(v) = v.get(&s)? {328							v.unwrap_if_lazy()?329						} else if let Some(Val::Str(n)) = v.get("__intristic_namespace__")? {330							Val::Intristic(n, s)331						} else {332							create_error(crate::Error::NoSuchField(s))?333						}334					}335					(Val::Arr(v), Val::Num(n)) => v336						.get(n as usize)337						.unwrap_or_else(|| panic!("out of bounds"))338						.clone(),339					(Val::Str(s), Val::Num(n)) => {340						Val::Str(s.chars().skip(n as usize).take(1).collect())341					}342					(v, i) => todo!("not implemented: {:?}[{:?}]", v, i.unwrap_if_lazy()),343				}344			}345			LocalExpr(bindings, returned) => {346				let mut new_bindings: HashMap<String, LazyBinding> = HashMap::new();347				let future_context = Context::new_future();348349				let context_creator = context_creator!(350					closure!(clone future_context, |_, _| Ok(future_context.clone().unwrap()))351				);352353				for (k, v) in bindings354					.iter()355					.map(|b| evaluate_binding(b, context_creator.clone()))356				{357					new_bindings.insert(k, v);358				}359360				let context = context361					.extend(new_bindings, None, None, None)?362					.into_future(future_context);363				evaluate(context, &returned.clone())?364			}365			Arr(items) => {366				let mut out = Vec::with_capacity(items.len());367				for item in items {368					out.push(evaluate(context.clone(), item)?);369				}370				Val::Arr(out)371			}372			ArrComp(expr, compspecs) => Val::Arr(373				// First compspec should be forspec, so no "None" possible here374				evaluate_comp(context, expr, compspecs)?.unwrap(),375			),376			Obj(body) => Val::Obj(evaluate_object(context, body.clone())?),377			Apply(value, ArgsDesc(args)) => {378				let value = evaluate(context.clone(), value)?.unwrap_if_lazy()?;379				match value {380					// TODO: Capture context of application381					Val::Intristic(ns, name) => match (&ns as &str, &name as &str) {382						// arr/string/function383						("std", "length") => {384							assert_eq!(args.len(), 1);385							let expr = &args.get(0).unwrap().1;386							match evaluate(context, expr)? {387								Val::Str(n) => Val::Num(n.chars().count() as f64),388								Val::Arr(i) => Val::Num(i.len() as f64),389								v => panic!("can't get length of {:?}", v),390							}391						}392						// any393						("std", "type") => {394							assert_eq!(args.len(), 1);395							let expr = &args.get(0).unwrap().1;396							Val::Str(evaluate(context, expr)?.value_type()?.name().to_owned())397						}398						// length, idx=>any399						("std", "makeArray") => {400							assert_eq!(args.len(), 2);401							if let (Val::Num(v), Val::Func(d)) = (402								evaluate(context.clone(), &args[0].1)?,403								evaluate(context, &args[1].1)?,404							) {405								assert!(v > 0.0);406								let mut out = Vec::with_capacity(v as usize);407								for i in 0..v as usize {408									out.push(d.evaluate(vec![(None, Val::Num(i as f64))])?)409								}410								Val::Arr(out)411							} else {412								panic!("bad makeArray call");413							}414						}415						// string416						("std", "codepoint") => {417							assert_eq!(args.len(), 1);418							if let Val::Str(s) = evaluate(context, &args[0].1)? {419								assert!(420									s.chars().count() == 1,421									"std.codepoint should receive single char string"422								);423								Val::Num(s.chars().take(1).next().unwrap() as u32 as f64)424							} else {425								panic!("bad codepoint call");426							}427						}428						// object, includeHidden429						("std", "objectFieldsEx") => {430							assert_eq!(args.len(), 2);431							if let (Val::Obj(body), Val::Bool(_include_hidden)) = (432								evaluate(context.clone(), &args[0].1)?,433								evaluate(context, &args[1].1)?,434							) {435								// TODO: handle visibility (_include_hidden)436								Val::Arr(body.fields().into_iter().map(Val::Str).collect())437							} else {438								panic!("bad objectFieldsEx call");439							}440						}441						(ns, name) => panic!("Intristic not found: {}.{}", ns, name),442					},443					Val::Func(f) => f.evaluate(444						args.clone()445							.into_iter()446							.map(move |a| {447								(448									a.clone().0,449									Val::Lazy(lazy_val!(450										closure!(clone context, clone a, || evaluate(context.clone(), &a.clone().1))451									)),452								)453							})454							.collect(),455					)?,456					_ => panic!("{:?} is not a function", value),457				}458			}459			Function(params, body) => evaluate_method(context, body, params.clone()),460			AssertExpr(AssertStmt(value, msg), returned) => {461				if evaluate(context.clone(), &value)?462					.try_cast_bool("assertion condition should be boolean")?463				{464					evaluate(context, returned)?465				} else if let Some(msg) = msg {466					panic!(467						"assertion failed ({:?}): {}",468						value,469						evaluate(context, msg)?470							.try_cast_str("assertion message should be string")?471					);472				} else {473					panic!("assertion failed ({:?}): no message", value);474				}475			}476			Error(e) => create_error(crate::Error::RuntimeError(477				evaluate(context, e)?.try_cast_str("error text should be string")?,478			))?,479			IfElse {480				cond,481				cond_then,482				cond_else,483			} => {484				if evaluate(context.clone(), &cond.0)?485					.try_cast_bool("if condition should be boolean")?486				{487					evaluate(context, cond_then)?488				} else {489					match cond_else {490						Some(v) => evaluate(context, v)?,491						None => Val::Bool(false),492					}493				}494			}495			_ => panic!(496				"evaluation not implemented: {:?}",497				LocExpr(expr.clone(), loc.clone())498			),499		})500	})501}
modifiedcrates/jsonnet-evaluator/src/lib.rsdiffbeforeafterboth
--- a/crates/jsonnet-evaluator/src/lib.rs
+++ b/crates/jsonnet-evaluator/src/lib.rs
@@ -22,41 +22,59 @@
 rc_fn_helper!(
 	Binding,
 	binding,
-	dyn Fn(Option<ObjValue>, Option<ObjValue>) -> Val
+	dyn Fn(Option<ObjValue>, Option<ObjValue>) -> Result<Val>
 );
 rc_fn_helper!(
 	LazyBinding,
 	lazy_binding,
-	dyn Fn(Option<ObjValue>, Option<ObjValue>) -> LazyVal
+	dyn Fn(Option<ObjValue>, Option<ObjValue>) -> Result<LazyVal>
 );
-rc_fn_helper!(FunctionRhs, function_rhs, dyn Fn(Context) -> Val);
+rc_fn_helper!(FunctionRhs, function_rhs, dyn Fn(Context) -> Result<Val>);
 rc_fn_helper!(
 	FunctionDefault,
 	function_default,
-	dyn Fn(Context, LocExpr) -> Val
+	dyn Fn(Context, LocExpr) -> Result<Val>
 );
 
+pub struct FileData(String, LocExpr, Option<Val>);
 #[derive(Default)]
 pub struct EvaluationStateInternals {
 	/// Used for stack-overflows and stacktraces
-	stack: RefCell<Vec<(LocExpr, String)>>,
+	stack: RefCell<Vec<StackTraceElement>>,
 	/// Contains file source codes and evaluated results for imports and pretty printing stacktraces
-	files: RefCell<HashMap<String, (String, LocExpr, Option<Val>)>>,
+	files: RefCell<HashMap<String, FileData>>,
 	globals: RefCell<HashMap<String, Val>>,
 }
 
+thread_local! {
+	pub static EVAL_STATE: RefCell<Option<EvaluationState>> = RefCell::new(None)
+}
+pub(crate) fn with_state<T>(f: impl FnOnce(&EvaluationState) -> T) -> T {
+	EVAL_STATE.with(|s| f(s.borrow().as_ref().unwrap()))
+}
+pub(crate) fn create_error<T>(err: Error) -> Result<T> {
+	with_state(|s| s.error(err))
+}
+pub(crate) fn push<T>(e: LocExpr, comment: String, f: impl FnOnce() -> T) -> T {
+	with_state(|s| s.push(e, comment, f))
+}
+
 #[derive(Default, Clone)]
 pub struct EvaluationState(Rc<EvaluationStateInternals>);
 impl EvaluationState {
-	pub fn add_file(&self, name: String, code: String) -> Result<(), Box<dyn std::error::Error>> {
+	pub fn add_file(
+		&self,
+		name: String,
+		code: String,
+	) -> std::result::Result<(), Box<dyn std::error::Error>> {
 		self.0.files.borrow_mut().insert(
 			name.clone(),
-			(
+			FileData(
 				code.clone(),
 				parse(
 					&code,
 					&ParserSettings {
-						file_name: name.clone(),
+						file_name: name,
 						loc_data: true,
 					},
 				)?,
@@ -66,7 +84,8 @@
 
 		Ok(())
 	}
-	pub fn evaluate_file(&self, name: &str) -> Result<Val, Box<dyn std::error::Error>> {
+	pub fn evaluate_file(&self, name: &str) -> Result<Val> {
+		self.begin_state();
 		let expr: LocExpr = {
 			let ro_map = self.0.files.borrow();
 			let value = ro_map
@@ -77,7 +96,7 @@
 			}
 			value.1.clone()
 		};
-		let value = evaluate(self.create_default_context(), self.clone(), &expr);
+		let value = evaluate(self.create_default_context()?, &expr)?;
 		{
 			self.0
 				.files
@@ -87,10 +106,11 @@
 				.2
 				.replace(value.clone());
 		}
+		self.end_state();
 		Ok(value)
 	}
 
-	pub fn parse_evaluate_raw(&self, code: &str) -> Val {
+	pub fn parse_evaluate_raw(&self, code: &str) -> Result<Val> {
 		let parsed = parse(
 			&code,
 			&ParserSettings {
@@ -98,29 +118,30 @@
 				loc_data: true,
 			},
 		);
-		evaluate(
-			self.create_default_context(),
-			self.clone(),
-			&parsed.unwrap(),
-		)
+		self.begin_state();
+		let value = evaluate(self.create_default_context()?, &parsed.unwrap());
+		self.end_state();
+		value
 	}
 
 	pub fn add_stdlib(&self) {
+		self.begin_state();
 		use jsonnet_stdlib::STDLIB_STR;
 		self.add_file("std.jsonnet".to_owned(), STDLIB_STR.to_owned())
 			.unwrap();
 		let val = self.evaluate_file("std.jsonnet").unwrap();
 		self.0.globals.borrow_mut().insert("std".to_owned(), val);
+		self.end_state();
 	}
 
-	pub fn create_default_context(&self) -> Context {
+	pub fn create_default_context(&self) -> Result<Context> {
 		let globals = self.0.globals.borrow();
 		let mut new_bindings: HashMap<String, LazyBinding> = HashMap::new();
 		for (name, value) in globals.iter() {
 			new_bindings.insert(
 				name.clone(),
 				lazy_binding!(
-					closure!(clone value, |_self, _super_obj| lazy_val!(closure!(clone value, ||value.clone())))
+					closure!(clone value, |_self, _super_obj| Ok(lazy_val!(closure!(clone value, ||Ok(value.clone())))))
 				),
 			);
 		}
@@ -128,30 +149,37 @@
 	}
 
 	pub fn push<T>(&self, e: LocExpr, comment: String, f: impl FnOnce() -> T) -> T {
-		self.0.stack.borrow_mut().push((e, comment));
+		self.0
+			.stack
+			.borrow_mut()
+			.push(StackTraceElement(e, comment));
 		let result = f();
 		self.0.stack.borrow_mut().pop();
 		result
 	}
 	pub fn print_stack_trace(&self) {
-		for e in self.stack_trace() {
+		for e in self.stack_trace().0 {
 			println!("{:?} - {:?}", e.0, e.1)
 		}
 	}
-	pub fn stack_trace(&self) -> Vec<(LocExpr, String)> {
-		self.0
-			.stack
-			.borrow()
-			.iter()
-			.rev()
-			.map(|e| e.clone())
-			.collect()
+	pub fn stack_trace(&self) -> StackTrace {
+		StackTrace(self.0.stack.borrow().iter().rev().cloned().collect())
+	}
+	pub fn error<T>(&self, err: Error) -> Result<T> {
+		Err(LocError(err, self.stack_trace()))
+	}
+
+	fn begin_state(&self) {
+		EVAL_STATE.with(|v| v.borrow_mut().replace(self.clone()));
+	}
+	fn end_state(&self) {
+		EVAL_STATE.with(|v| v.borrow_mut().take());
 	}
 }
 
 #[cfg(test)]
 pub mod tests {
-	use super::{evaluate, Context, Val};
+	use super::Val;
 	use crate::EvaluationState;
 	use jsonnet_parser::*;
 
@@ -176,7 +204,9 @@
 		let state = EvaluationState::default();
 		state.add_stdlib();
 		assert_eq!(
-			state.parse_evaluate_raw(r#"std.base64("test") == "dGVzdA==""#),
+			state
+				.parse_evaluate_raw(r#"std.assertEqual(std.base64("test"), "dGVzdA==w")"#)
+				.unwrap(),
 			Val::Bool(true)
 		);
 	}
@@ -282,6 +312,7 @@
 		};
 	}
 
+	/*
 	/// Sanity checking, before trusting to another tests
 	#[test]
 	fn equality_operator() {
@@ -491,4 +522,5 @@
 		"#
 		);
 	}
+	*/
 }
modifiedcrates/jsonnet-evaluator/src/obj.rsdiffbeforeafterboth
--- a/crates/jsonnet-evaluator/src/obj.rs
+++ b/crates/jsonnet-evaluator/src/obj.rs
@@ -1,4 +1,4 @@
-use crate::{evaluate_add_op, Binding, Val};
+use crate::{evaluate_add_op, Binding, Result, Val};
 use jsonnet_parser::Visibility;
 use std::{
 	cell::RefCell,
@@ -32,13 +32,10 @@
 			write!(f, " + ")?;
 		}
 		let mut debug = f.debug_struct("ObjValue");
-		debug.field("$ptr", &Rc::as_ptr(&self.0));
 		for (name, member) in self.0.this_entries.iter() {
 			debug.field(name, member);
 		}
 		debug.finish_non_exhaustive()
-		// .field("fields", &self.fields())
-		// .finish_non_exhaustive()
 	}
 }
 
@@ -71,33 +68,40 @@
 		}
 		fields
 	}
-	pub fn get(&self, key: &str) -> Option<Val> {
+	pub fn get(&self, key: &str) -> Result<Option<Val>> {
 		if let Some(v) = self.0.value_cache.borrow().get(key) {
-			return Some(v.clone());
+			return Ok(Some(v.clone()));
 		}
-		let v = self.get_raw(key, self).map(|v| v.unwrap_if_lazy());
-		if let Some(v) = v.clone() {
-			self.0.value_cache.borrow_mut().insert(key.to_owned(), v);
+		if let Some(v) = self.get_raw(key, self)? {
+			let v = v.unwrap_if_lazy()?;
+			self.0
+				.value_cache
+				.borrow_mut()
+				.insert(key.to_owned(), v.clone());
+			Ok(Some(v))
+		} else {
+			Ok(None)
 		}
-		v
 	}
-	fn get_raw(&self, key: &str, real_this: &ObjValue) -> Option<Val> {
+	fn get_raw(&self, key: &str, real_this: &ObjValue) -> Result<Option<Val>> {
 		match (self.0.this_entries.get(key), &self.0.super_obj) {
-			(Some(k), None) => Some(k.invoke.0(
+			(Some(k), None) => Ok(Some(k.invoke.0(
 				Some(real_this.clone()),
 				self.0.super_obj.clone(),
-			)),
+			)?)),
 			(Some(k), Some(s)) => {
-				let our = k.invoke.0(Some(real_this.clone()), self.0.super_obj.clone());
+				let our = k.invoke.0(Some(real_this.clone()), self.0.super_obj.clone())?;
 				if k.add {
-					s.get_raw(key, real_this)
-						.map_or(Some(our.clone()), |v| Some(evaluate_add_op(&v, &our)))
+					s.get_raw(key, real_this)?
+						.map_or(Ok(Some(our.clone())), |v| {
+							Ok(Some(evaluate_add_op(&v, &our)?))
+						})
 				} else {
-					Some(our)
+					Ok(Some(our))
 				}
 			}
 			(None, Some(s)) => s.get_raw(key, real_this),
-			(None, None) => None,
+			(None, None) => Ok(None),
 		}
 	}
 }
modifiedcrates/jsonnet-evaluator/src/val.rsdiffbeforeafterboth
--- a/crates/jsonnet-evaluator/src/val.rs
+++ b/crates/jsonnet-evaluator/src/val.rs
@@ -1,4 +1,7 @@
-use crate::{lazy_binding, Context, FunctionDefault, FunctionRhs, LazyBinding, ObjValue};
+use crate::{
+	create_error, lazy_binding, Context, Error, FunctionDefault, FunctionRhs, LazyBinding,
+	ObjValue, Result,
+};
 use closure::closure;
 use jsonnet_parser::ParamsDesc;
 use std::{
@@ -9,28 +12,28 @@
 };
 
 struct LazyValInternals {
-	pub f: Box<dyn Fn() -> Val>,
+	pub f: Box<dyn Fn() -> Result<Val>>,
 	pub cached: RefCell<Option<Val>>,
 }
 #[derive(Clone)]
 pub struct LazyVal(Rc<LazyValInternals>);
 impl LazyVal {
-	pub fn new(f: Box<dyn Fn() -> Val>) -> Self {
+	pub fn new(f: Box<dyn Fn() -> Result<Val>>) -> Self {
 		LazyVal(Rc::new(LazyValInternals {
 			f,
 			cached: RefCell::new(None),
 		}))
 	}
-	pub fn evaluate(&self) -> Val {
+	pub fn evaluate(&self) -> Result<Val> {
 		{
 			let cached = self.0.cached.borrow();
 			if cached.is_some() {
-				return cached.clone().unwrap();
+				return Ok(cached.clone().unwrap());
 			}
 		}
-		let result = (self.0.f)();
+		let result = (self.0.f)()?;
 		self.0.cached.borrow_mut().replace(result.clone());
-		result
+		Ok(result)
 	}
 }
 #[macro_export]
@@ -59,7 +62,7 @@
 }
 impl FuncDesc {
 	// TODO: Check for unset variables
-	pub fn evaluate(&self, args: Vec<(Option<String>, Val)>) -> Val {
+	pub fn evaluate(&self, args: Vec<(Option<String>, Val)>) -> Result<Val> {
 		let mut new_bindings: HashMap<String, LazyBinding> = HashMap::new();
 		let future_ctx = Context::new_future();
 
@@ -80,7 +83,7 @@
 			new_bindings.insert(
 				name.as_ref().unwrap().clone(),
 				lazy_binding!(
-					closure!(clone val, |_, _| lazy_val!(closure!(clone val, || val.clone())))
+					closure!(clone val, |_, _| Ok(lazy_val!(closure!(clone val, || Ok(val.clone())))))
 				),
 			);
 		}
@@ -89,19 +92,49 @@
 				new_bindings.insert(
 					param.0.clone(),
 					lazy_binding!(
-						closure!(clone val, |_, _| lazy_val!(closure!(clone val, || val.clone())))
+						closure!(clone val, |_, _| Ok(lazy_val!(closure!(clone val, || Ok(val.clone())))))
 					),
 				);
 			}
 		}
 		let ctx = self
 			.ctx
-			.extend(new_bindings, None, None, None)
+			.extend(new_bindings, None, None, None)?
 			.into_future(future_ctx);
 		self.eval_rhs.0(ctx)
 	}
 }
 
+#[derive(Debug)]
+pub enum ValType {
+	Bool,
+	Null,
+	Str,
+	Num,
+	Arr,
+	Obj,
+	Func,
+}
+impl ValType {
+	pub fn name(&self) -> &'static str {
+		use ValType::*;
+		match self {
+			Bool => "boolean",
+			Null => "null",
+			Str => "string",
+			Num => "number",
+			Arr => "array",
+			Obj => "object",
+			Func => "function",
+		}
+	}
+}
+impl Display for ValType {
+	fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
+		write!(f, "{}", self.name())
+	}
+}
+
 #[derive(Debug, PartialEq, Clone)]
 pub enum Val {
 	Bool(bool),
@@ -117,80 +150,44 @@
 	Intristic(String, String),
 }
 impl Val {
-	pub fn try_cast_bool(self) -> bool {
-		match self.unwrap_if_lazy() {
-			Val::Bool(v) => v,
-			v => panic!("expected bool, got {:?}", v),
+	pub fn try_cast_bool(self, context: &'static str) -> Result<bool> {
+		match self.unwrap_if_lazy()? {
+			Val::Bool(v) => Ok(v),
+			v => create_error(Error::TypeMismatch(
+				context,
+				vec![ValType::Bool],
+				v.value_type()?,
+			)),
 		}
 	}
-	pub fn try_cast_str(self) -> String {
-		match self.unwrap_if_lazy() {
-			Val::Str(v) => v,
-			v => panic!("expected bool, got {:?}", v),
+	pub fn try_cast_str(self, context: &'static str) -> Result<String> {
+		match self.unwrap_if_lazy()? {
+			Val::Str(v) => Ok(v),
+			v => create_error(Error::TypeMismatch(
+				context,
+				vec![ValType::Str],
+				v.value_type()?,
+			)),
 		}
 	}
-	pub fn unwrap_if_lazy(self) -> Self {
-		if let Val::Lazy(v) = self {
-			v.evaluate().unwrap_if_lazy()
+	pub fn unwrap_if_lazy(self) -> Result<Self> {
+		Ok(if let Val::Lazy(v) = self {
+			v.evaluate()?.unwrap_if_lazy()?
 		} else {
 			self
-		}
-	}
-	pub fn type_of(&self) -> &'static str {
-		match self {
-			Val::Str(..) => "string",
-			Val::Num(..) => "number",
-			Val::Arr(..) => "array",
-			Val::Obj(..) => "object",
-			Val::Func(..) => "function",
-			_ => panic!("no native type found"),
-		}
+		})
 	}
-}
-impl Display for Val {
-	fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
-		match self {
-			Val::Str(str) => write!(f, "\"{}\"", str)?,
-			Val::Num(n) => write!(f, "{}", n)?,
-			Val::Arr(values) => {
-				write!(f, "[")?;
-				let mut first = true;
-				for value in values {
-					if first {
-						first = false;
-					} else {
-						write!(f, ",")?;
-					}
-					write!(f, "{}", value)?;
-				}
-				write!(f, "]")?;
-			}
-			Val::Obj(value) => {
-				write!(f, "{{")?;
-				let mut first = true;
-				for field in value.fields() {
-					if first {
-						first = false;
-					} else {
-						write!(f, ",")?;
-					}
-					write!(f, "\"{}\":", field)?;
-					write!(f, "{}", value.get(&field).unwrap())?;
-				}
-				write!(f, "}}")?;
-			}
-			Val::Lazy(lazy) => {
-				write!(f, "{}", lazy.evaluate())?;
-			}
-			Val::Func(_) => {
-				write!(f, "<<FUNC>>")?;
-			}
-			v => panic!("no json equivalent for {:?}", v),
-		};
-		Ok(())
+	pub fn value_type(&self) -> Result<ValType> {
+		Ok(match self {
+			Val::Str(..) => ValType::Str,
+			Val::Num(..) => ValType::Num,
+			Val::Arr(..) => ValType::Arr,
+			Val::Obj(..) => ValType::Obj,
+			Val::Func(..) => ValType::Func,
+			Val::Bool(_) => ValType::Bool,
+			Val::Null => ValType::Null,
+			Val::Intristic(_, _) => ValType::Func,
+			Val::Lazy(_) => self.clone().unwrap_if_lazy()?.value_type()?,
+		})
 	}
-}
-
-pub fn bool_val(v: bool) -> Val {
-	Val::Bool(v)
 }