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

difftreelog

refactor(evaluator) use PathBuf for file paths

Лач2020-06-06parent: #30ce98e.patch.diff
in: master

4 files changed

modifiedcrates/jsonnet-evaluator/build.rsdiffbeforeafterboth
--- a/crates/jsonnet-evaluator/build.rs
+++ b/crates/jsonnet-evaluator/build.rs
@@ -1,13 +1,18 @@
 use bincode::serialize;
 use jsonnet_parser::{parse, ParserSettings};
 use jsonnet_stdlib::STDLIB_STR;
-use std::{env, fs::File, io::Write, path::Path};
+use std::{
+	env,
+	fs::File,
+	io::Write,
+	path::{Path, PathBuf},
+};
 
 fn main() {
 	let parsed = parse(
 		STDLIB_STR,
 		&ParserSettings {
-			file_name: "std.jsonnet".to_owned(),
+			file_name: PathBuf::from("std.jsonnet"),
 			loc_data: true,
 		},
 	)
modifiedcrates/jsonnet-evaluator/src/error.rsdiffbeforeafterboth
--- a/crates/jsonnet-evaluator/src/error.rs
+++ b/crates/jsonnet-evaluator/src/error.rs
@@ -8,6 +8,7 @@
 	NoSuchField(String),
 
 	RuntimeError(String),
+	StackOverflow,
 }
 
 #[derive(Clone, Debug)]
modifiedcrates/jsonnet-evaluator/src/evaluate.rsdiffbeforeafterboth
before · 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	ArgsDesc, AssertStmt, BinaryOpType, BindSpec, CompSpec, Expr, FieldMember, ForSpecData,9	IfSpecData, LiteralType, LocExpr, Member, ObjBody, ParamsDesc, UnaryOpType, Visibility,10};11use std::{12	collections::{BTreeMap, HashMap},13	rc::Rc,14};1516pub fn evaluate_binding(b: &BindSpec, context_creator: ContextCreator) -> (String, LazyBinding) {17	let b = b.clone();18	if let Some(args) = &b.params {19		let args = args.clone();20		(21			b.name.clone(),22			lazy_binding!(move |this, super_obj| Ok(lazy_val!(23				closure!(clone b, clone args, clone context_creator, || Ok(evaluate_method(24					context_creator.0(this.clone(), super_obj.clone())?,25					&b.value,26					args.clone()27				)))28			))),29		)30	} else {31		(32			b.name.clone(),33			lazy_binding!(move |this, super_obj| {34				Ok(lazy_val!(35					closure!(clone context_creator, clone b, || evaluate(36						context_creator.0(this.clone(), super_obj.clone())?,37						&b.value38					))39				))40			}),41		)42	}43}4445pub fn evaluate_method(ctx: Context, expr: &LocExpr, arg_spec: ParamsDesc) -> Val {46	Val::Func(FuncDesc {47		ctx,48		params: arg_spec,49		eval_rhs: function_rhs!(closure!(clone expr, |ctx| evaluate(ctx, &expr))),50		eval_default: function_default!(closure!(|ctx, default| evaluate(ctx, &default))),51	})52}5354pub fn evaluate_field_name(55	context: Context,56	field_name: &jsonnet_parser::FieldName,57) -> Result<Option<String>> {58	Ok(match field_name {59		jsonnet_parser::FieldName::Fixed(n) => Some(n.clone()),60		jsonnet_parser::FieldName::Dyn(expr) => {61			let value = evaluate(context, expr)?.unwrap_if_lazy()?;62			if matches!(value, Val::Null) {63				None64			} else {65				Some(value.try_cast_str("dynamic field name")?)66			}67		}68	})69}7071pub fn evaluate_unary_op(op: UnaryOpType, b: &Val) -> Result<Val> {72	Ok(match (op, b) {73		(o, Val::Lazy(l)) => evaluate_unary_op(o, &l.evaluate()?)?,74		(UnaryOpType::Not, Val::Bool(v)) => Val::Bool(!v),75		(UnaryOpType::Minus, Val::Num(n)) => Val::Num(-*n),76		(UnaryOpType::BitNot, Val::Num(n)) => Val::Num(!(*n as i32) as f64),77		(op, o) => panic!("unary op not implemented: {:?} {:?}", op, o),78	})79}8081pub(crate) fn evaluate_add_op(a: &Val, b: &Val) -> Result<Val> {82	Ok(match (a, b) {83		(Val::Str(v1), Val::Str(v2)) => Val::Str(v1.to_owned() + &v2),8485		(Val::Str(v1), Val::Num(v2)) => Val::Str(format!("{}{}", v1, v2)),86		(Val::Num(v1), Val::Str(v2)) => Val::Str(format!("{}{}", v1, v2)),87		(Val::Str(v1), Val::Bool(v2)) => Val::Str(format!("{}{}", v1, v2)),88		(Val::Bool(v1), Val::Str(v2)) => Val::Str(format!("{}{}", v1, v2)),89		(Val::Str(v1), Val::Null) => Val::Str(format!("{}null", v1)),90		(Val::Null, Val::Str(v2)) => Val::Str(format!("null{}", v2)),9192		(Val::Obj(v1), Val::Obj(v2)) => Val::Obj(v2.with_super(v1.clone())),93		(Val::Arr(a), Val::Arr(b)) => Val::Arr([&a[..], &b[..]].concat()),94		(Val::Num(v1), Val::Num(v2)) => Val::Num(v1 + v2),95		_ => panic!("can't add: {:?} and {:?}", a, b),96	})97}9899pub fn evaluate_binary_op_special(100	context: Context,101	a: &LocExpr,102	op: BinaryOpType,103	b: &LocExpr,104) -> Result<Val> {105	Ok(106		match (evaluate(context.clone(), &a)?.unwrap_if_lazy()?, op, b) {107			(Val::Bool(true), BinaryOpType::Or, _o) => Val::Bool(true),108			(Val::Bool(false), BinaryOpType::And, _o) => Val::Bool(false),109			(a, op, eb) => {110				evaluate_binary_op_normal(&a, op, &evaluate(context, eb)?.unwrap_if_lazy()?)?111			}112		},113	)114}115116pub fn evaluate_binary_op_normal(a: &Val, op: BinaryOpType, b: &Val) -> Result<Val> {117	Ok(match (a, op, b) {118		(a, BinaryOpType::Add, b) => evaluate_add_op(a, b)?,119120		(Val::Str(v1), BinaryOpType::Mul, Val::Num(v2)) => Val::Str(v1.repeat(*v2 as usize)),121122		// Bool X Bool123		(Val::Bool(a), BinaryOpType::And, Val::Bool(b)) => Val::Bool(*a && *b),124		(Val::Bool(a), BinaryOpType::Or, Val::Bool(b)) => Val::Bool(*a || *b),125126		// Str X Str127		(Val::Str(v1), BinaryOpType::Lt, Val::Str(v2)) => Val::Bool(v1 < v2),128		(Val::Str(v1), BinaryOpType::Gt, Val::Str(v2)) => Val::Bool(v1 > v2),129		(Val::Str(v1), BinaryOpType::Lte, Val::Str(v2)) => Val::Bool(v1 <= v2),130		(Val::Str(v1), BinaryOpType::Gte, Val::Str(v2)) => Val::Bool(v1 >= v2),131132		// Num X Num133		(Val::Num(v1), BinaryOpType::Mul, Val::Num(v2)) => Val::Num(v1 * v2),134		(Val::Num(v1), BinaryOpType::Div, Val::Num(v2)) => Val::Num(v1 / v2),135136		(Val::Num(v1), BinaryOpType::Sub, Val::Num(v2)) => Val::Num(v1 - v2),137138		(Val::Num(v1), BinaryOpType::Lt, Val::Num(v2)) => Val::Bool(v1 < v2),139		(Val::Num(v1), BinaryOpType::Gt, Val::Num(v2)) => Val::Bool(v1 > v2),140		(Val::Num(v1), BinaryOpType::Lte, Val::Num(v2)) => Val::Bool(v1 <= v2),141		(Val::Num(v1), BinaryOpType::Gte, Val::Num(v2)) => Val::Bool(v1 >= v2),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		(Val::Num(v1), BinaryOpType::Lhs, Val::Num(v2)) => {153			Val::Num(((*v1 as i32) << (*v2 as i32)) as f64)154		}155		(Val::Num(v1), BinaryOpType::Rhs, Val::Num(v2)) => {156			Val::Num(((*v1 as i32) >> (*v2 as i32)) as f64)157		}158159		_ => panic!("no rules for binary operation: {:?} {:?} {:?}", a, op, b),160	})161}162163future_wrapper!(HashMap<String, LazyBinding>, FutureNewBindings);164future_wrapper!(ObjValue, FutureObjValue);165166pub fn evaluate_comp(167	context: Context,168	value: &LocExpr,169	specs: &[CompSpec],170) -> Result<Option<Vec<Val>>> {171	Ok(match specs.get(0) {172		None => Some(vec![evaluate(context, &value)?]),173		Some(CompSpec::IfSpec(IfSpecData(cond))) => {174			if evaluate(context.clone(), &cond)?.try_cast_bool("if spec")? {175				evaluate_comp(context, value, &specs[1..])?176			} else {177				None178			}179		}180		Some(CompSpec::ForSpec(ForSpecData(var, expr))) => {181			match evaluate(context.clone(), &expr)?.unwrap_if_lazy()? {182				Val::Arr(list) => {183					let mut out = Vec::new();184					for item in list {185						let item = item.clone().unwrap_if_lazy()?;186						out.push(evaluate_comp(187							context.with_var(var.clone(), item)?,188							value,189							&specs[1..],190						)?);191					}192					Some(out.iter().flatten().flatten().cloned().collect())193				}194				_ => panic!("for expression evaluated to non-iterable value"),195			}196		}197	})198}199200// TODO: Asserts201pub fn evaluate_object(context: Context, object: ObjBody) -> Result<ObjValue> {202	Ok(match object {203		ObjBody::MemberList(members) => {204			let new_bindings = FutureNewBindings::new();205			let future_this = FutureObjValue::new();206			let context_creator = context_creator!(207				closure!(clone context, clone new_bindings, clone future_this, |this: Option<ObjValue>, super_obj: Option<ObjValue>| {208					Ok(context.clone().extend(209						new_bindings.clone().unwrap(),210						context.clone().dollar().clone().or_else(||this.clone()),211						Some(this.unwrap()),212						super_obj213					)?)214				})215			);216			{217				let mut bindings: HashMap<String, LazyBinding> = HashMap::new();218				for (n, b) in members219					.iter()220					.filter_map(|m| match m {221						Member::BindStmt(b) => Some(b.clone()),222						_ => None,223					})224					.map(|b| evaluate_binding(&b, context_creator.clone()))225				{226					bindings.insert(n, b);227				}228				new_bindings.fill(bindings);229			}230231			let mut new_members = BTreeMap::new();232			for member in members.into_iter() {233				match member {234					Member::Field(FieldMember {235						name,236						plus,237						params: None,238						visibility,239						value,240					}) => {241						let name = evaluate_field_name(context.clone(), &name)?;242						if name.is_none() {243							continue;244						}245						let name = name.unwrap();246						new_members.insert(247							name.clone(),248							ObjMember {249								add: plus,250								visibility: visibility.clone(),251								invoke: binding!(252									closure!(clone name, clone value, clone context_creator, |this, super_obj| {253										push(value.clone(), "object ".to_owned()+&name+" field", ||{254											let context = context_creator.0(this, super_obj)?;255											evaluate(256												context,257												&value,258											)?.unwrap_if_lazy()259										})260									})261								),262							},263						);264					}265					Member::Field(FieldMember {266						name,267						params: Some(params),268						value,269						..270					}) => {271						let name = evaluate_field_name(context.clone(), &name)?;272						if name.is_none() {273							continue;274						}275						let name = name.unwrap();276						new_members.insert(277							name,278							ObjMember {279								add: false,280								visibility: Visibility::Hidden,281								invoke: binding!(282									closure!(clone value, clone context_creator, |this, super_obj| {283										// TODO: Assert284										Ok(evaluate_method(285											context_creator.0(this, super_obj)?,286											&value.clone(),287											params.clone(),288										))289									})290								),291							},292						);293					}294					Member::BindStmt(_) => {}295					Member::AssertStmt(_) => {}296				}297			}298			future_this.fill(ObjValue::new(None, Rc::new(new_members)))299		}300		_ => todo!(),301	})302}303304pub fn evaluate(context: Context, expr: &LocExpr) -> Result<Val> {305	use Expr::*;306	let locexpr = expr.clone();307	let LocExpr(expr, loc) = expr;308	Ok(match &**expr {309		Literal(LiteralType::This) => Val::Obj(310			context311				.this()312				.clone()313				.unwrap_or_else(|| panic!("this not found")),314		),315		Literal(LiteralType::Dollar) => Val::Obj(316			context317				.dollar()318				.clone()319				.unwrap_or_else(|| panic!("dollar not found")),320		),321		Literal(LiteralType::True) => Val::Bool(true),322		Literal(LiteralType::False) => Val::Bool(false),323		Literal(LiteralType::Null) => Val::Null,324		Parened(e) => evaluate(context, e)?,325		Str(v) => Val::Str(v.clone()),326		Num(v) => Val::Num(*v),327		BinaryOp(v1, o, v2) => evaluate_binary_op_special(context, &v1, *o, &v2)?,328		UnaryOp(o, v) => evaluate_unary_op(*o, &evaluate(context, v)?)?,329		Var(name) => Val::Lazy(context.binding(&name)).unwrap_if_lazy()?,330		Index(LocExpr(v, _), index) if matches!(&**v, Expr::Literal(LiteralType::Super)) => {331			let name = evaluate(context.clone(), index)?.try_cast_str("object index")?;332			context333				.super_obj()334				.clone()335				.expect("no super found")336				.get_raw(&name, &context.this().clone().expect("no this found"))?337				.expect("value not found")338		}339		Index(value, index) => {340			match (341				evaluate(context.clone(), value)?.unwrap_if_lazy()?,342				evaluate(context, index)?,343			) {344				(Val::Obj(v), Val::Str(s)) => {345					if let Some(v) = v.get(&s)? {346						v.unwrap_if_lazy()?347					} else if let Some(Val::Str(n)) = v.get("__intristic_namespace__")? {348						Val::Intristic(n, s)349					} else {350						create_error(crate::Error::NoSuchField(s))?351					}352				}353				(Val::Arr(v), Val::Num(n)) => v354					.get(n as usize)355					.unwrap_or_else(|| panic!("out of bounds"))356					.clone()357					.unwrap_if_lazy()?,358				(Val::Str(s), Val::Num(n)) => {359					Val::Str(s.chars().skip(n as usize).take(1).collect())360				}361				(v, i) => todo!("not implemented: {:?}[{:?}]", v, i.unwrap_if_lazy()),362			}363		}364		LocalExpr(bindings, returned) => {365			let mut new_bindings: HashMap<String, LazyBinding> = HashMap::new();366			let future_context = Context::new_future();367368			let context_creator = context_creator!(369				closure!(clone future_context, |_, _| Ok(future_context.clone().unwrap()))370			);371372			for (k, v) in bindings373				.iter()374				.map(|b| evaluate_binding(b, context_creator.clone()))375			{376				new_bindings.insert(k, v);377			}378379			let context = context380				.extend(new_bindings, None, None, None)?381				.into_future(future_context);382			evaluate(context, &returned.clone())?383		}384		Arr(items) => {385			let mut out = Vec::with_capacity(items.len());386			for item in items {387				out.push(Val::Lazy(lazy_val!(388					closure!(clone context, clone item, || {389						evaluate(context.clone(), &item)390					})391				)));392			}393			Val::Arr(out)394		}395		ArrComp(expr, compspecs) => Val::Arr(396			// First compspec should be forspec, so no "None" possible here397			evaluate_comp(context, expr, compspecs)?.unwrap(),398		),399		Obj(body) => Val::Obj(evaluate_object(context, body.clone())?),400		ObjExtend(s, t) => evaluate_add_op(401			&evaluate(context.clone(), s)?,402			&Val::Obj(evaluate_object(context, t.clone())?),403		)?,404		Apply(value, ArgsDesc(args)) => {405			let value = evaluate(context.clone(), value)?.unwrap_if_lazy()?;406			match value {407				Val::Intristic(ns, name) => match (&ns as &str, &name as &str) {408					// arr/string/function409					("std", "length") => {410						assert_eq!(args.len(), 1);411						let expr = &args.get(0).unwrap().1;412						match evaluate(context, expr)? {413							Val::Str(n) => Val::Num(n.chars().count() as f64),414							Val::Arr(i) => Val::Num(i.len() as f64),415							v => panic!("can't get length of {:?}", v),416						}417					}418					// any419					("std", "type") => {420						assert_eq!(args.len(), 1);421						let expr = &args.get(0).unwrap().1;422						Val::Str(evaluate(context, expr)?.value_type()?.name().to_owned())423					}424					// length, idx=>any425					("std", "makeArray") => {426						assert_eq!(args.len(), 2);427						if let (Val::Num(v), Val::Func(d)) = (428							evaluate(context.clone(), &args[0].1)?,429							evaluate(context, &args[1].1)?,430						) {431							assert!(v >= 0.0);432							let mut out = Vec::with_capacity(v as usize);433							for i in 0..v as usize {434								out.push(d.evaluate(vec![(None, Val::Num(i as f64))])?)435							}436							Val::Arr(out)437						} else {438							panic!("bad makeArray call");439						}440					}441					// string442					("std", "codepoint") => {443						assert_eq!(args.len(), 1);444						if let Val::Str(s) = evaluate(context, &args[0].1)? {445							assert!(446								s.chars().count() == 1,447								"std.codepoint should receive single char string"448							);449							Val::Num(s.chars().take(1).next().unwrap() as u32 as f64)450						} else {451							panic!("bad codepoint call");452						}453					}454					// object, includeHidden455					("std", "objectFieldsEx") => {456						assert_eq!(args.len(), 2);457						if let (Val::Obj(body), Val::Bool(_include_hidden)) = (458							evaluate(context.clone(), &args[0].1)?,459							evaluate(context, &args[1].1)?,460						) {461							// TODO: handle visibility (_include_hidden)462							Val::Arr(body.fields().into_iter().map(Val::Str).collect())463						} else {464							panic!("bad objectFieldsEx call");465						}466					}467					("std", "primitiveEquals") => {468						assert_eq!(args.len(), 2);469						let (a, b) = (470							evaluate(context.clone(), &args[0].1)?,471							evaluate(context, &args[1].1)?,472						);473						Val::Bool(a == b)474					}475					("std", "modulo") => {476						assert_eq!(args.len(), 2);477						if let (Val::Num(a), Val::Num(b)) = (478							evaluate(context.clone(), &args[0].1)?,479							evaluate(context, &args[1].1)?,480						) {481							Val::Num(a % b)482						} else {483							panic!("bad modulo call");484						}485					}486					("std", "floor") => {487						assert_eq!(args.len(), 1);488						if let Val::Num(a) = evaluate(context, &args[0].1)? {489							Val::Num(a.floor())490						} else {491							panic!("bad floor call");492						}493					}494					(ns, name) => panic!("Intristic not found: {}.{}", ns, name),495				},496				Val::Func(f) => push(locexpr, "function call".to_owned(), || {497					f.evaluate(498						args.clone()499							.into_iter()500							.map(move |a| {501								(502									a.clone().0,503									Val::Lazy(lazy_val!(504										closure!(clone context, clone a, || evaluate(context.clone(), &a.clone().1))505									)),506								)507							})508							.collect(),509					)510				})?,511				_ => panic!("{:?} is not a function", value),512			}513		}514		Function(params, body) => evaluate_method(context, body, params.clone()),515		AssertExpr(AssertStmt(value, msg), returned) => {516			let assertion_result = push(value.clone(), "assertion condition".to_owned(), || {517				evaluate(context.clone(), &value)?518					.try_cast_bool("assertion condition should be boolean")519			})?;520			if assertion_result {521				push(522					returned.clone(),523					"assert 'return' branch".to_owned(),524					|| evaluate(context, returned),525				)?526			} else if let Some(msg) = msg {527				panic!(528					"assertion failed ({:?}): {}",529					value,530					evaluate(context, msg)?.try_cast_str("assertion message should be string")?531				);532			} else {533				panic!("assertion failed ({:?}): no message", value);534			}535		}536		Error(e) => create_error(crate::Error::RuntimeError(537			evaluate(context, e)?.try_cast_str("error text should be string")?,538		))?,539		IfElse {540			cond,541			cond_then,542			cond_else,543		} => {544			let condition_result = push(cond.0.clone(), "if condition".to_owned(), || {545				evaluate(context.clone(), &cond.0)?.try_cast_bool("if condition should be boolean")546			})?;547			if condition_result {548				push(549					cond_then.clone(),550					"if condition 'then' branch".to_owned(),551					|| evaluate(context, cond_then),552				)?553			} else {554				match cond_else {555					Some(v) => push(v.clone(), "if condition 'else' branch".to_owned(), || {556						evaluate(context, v)557					})?,558					None => Val::Null,559				}560			}561		}562		_ => panic!(563			"evaluation not implemented: {:?}",564			LocExpr(expr.clone(), loc.clone())565		),566	})567}
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	ArgsDesc, AssertStmt, BinaryOpType, BindSpec, CompSpec, Expr, FieldMember, ForSpecData,9	IfSpecData, LiteralType, LocExpr, Member, ObjBody, ParamsDesc, UnaryOpType, Visibility,10};11use std::{12	collections::{BTreeMap, HashMap},13	rc::Rc,14};1516pub fn evaluate_binding(b: &BindSpec, context_creator: ContextCreator) -> (String, LazyBinding) {17	let b = b.clone();18	if let Some(args) = &b.params {19		let args = args.clone();20		(21			b.name.clone(),22			lazy_binding!(move |this, super_obj| Ok(lazy_val!(23				closure!(clone b, clone args, clone context_creator, || Ok(evaluate_method(24					context_creator.0(this.clone(), super_obj.clone())?,25					&b.value,26					args.clone()27				)))28			))),29		)30	} else {31		(32			b.name.clone(),33			lazy_binding!(move |this, super_obj| {34				Ok(lazy_val!(closure!(clone context_creator, clone b, ||35					push(b.value.clone(), "thunk".to_owned(), ||{36						evaluate(37							context_creator.0(this.clone(), super_obj.clone())?,38							&b.value39						)40					})41				)))42			}),43		)44	}45}4647pub fn evaluate_method(ctx: Context, expr: &LocExpr, arg_spec: ParamsDesc) -> Val {48	Val::Func(FuncDesc {49		ctx,50		params: arg_spec,51		eval_rhs: function_rhs!(closure!(clone expr, |ctx| evaluate(ctx, &expr))),52		eval_default: function_default!(closure!(|ctx, default| evaluate(ctx, &default))),53	})54}5556pub fn evaluate_field_name(57	context: Context,58	field_name: &jsonnet_parser::FieldName,59) -> Result<Option<String>> {60	Ok(match field_name {61		jsonnet_parser::FieldName::Fixed(n) => Some(n.clone()),62		jsonnet_parser::FieldName::Dyn(expr) => {63			let value = evaluate(context, expr)?.unwrap_if_lazy()?;64			if matches!(value, Val::Null) {65				None66			} else {67				Some(value.try_cast_str("dynamic field name")?)68			}69		}70	})71}7273pub fn evaluate_unary_op(op: UnaryOpType, b: &Val) -> Result<Val> {74	Ok(match (op, b) {75		(o, Val::Lazy(l)) => evaluate_unary_op(o, &l.evaluate()?)?,76		(UnaryOpType::Not, Val::Bool(v)) => Val::Bool(!v),77		(UnaryOpType::Minus, Val::Num(n)) => Val::Num(-*n),78		(UnaryOpType::BitNot, Val::Num(n)) => Val::Num(!(*n as i32) as f64),79		(op, o) => panic!("unary op not implemented: {:?} {:?}", op, o),80	})81}8283pub(crate) fn evaluate_add_op(a: &Val, b: &Val) -> Result<Val> {84	Ok(match (a, b) {85		(Val::Str(v1), Val::Str(v2)) => Val::Str(v1.to_owned() + &v2),8687		(Val::Str(v1), Val::Num(v2)) => Val::Str(format!("{}{}", v1, v2)),88		(Val::Num(v1), Val::Str(v2)) => Val::Str(format!("{}{}", v1, v2)),89		(Val::Str(v1), Val::Bool(v2)) => Val::Str(format!("{}{}", v1, v2)),90		(Val::Bool(v1), Val::Str(v2)) => Val::Str(format!("{}{}", v1, v2)),91		(Val::Str(v1), Val::Null) => Val::Str(format!("{}null", v1)),92		(Val::Null, Val::Str(v2)) => Val::Str(format!("null{}", v2)),9394		(Val::Obj(v1), Val::Obj(v2)) => Val::Obj(v2.with_super(v1.clone())),95		(Val::Arr(a), Val::Arr(b)) => Val::Arr([&a[..], &b[..]].concat()),96		(Val::Num(v1), Val::Num(v2)) => Val::Num(v1 + v2),97		_ => panic!("can't add: {:?} and {:?}", a, b),98	})99}100101pub fn evaluate_binary_op_special(102	context: Context,103	a: &LocExpr,104	op: BinaryOpType,105	b: &LocExpr,106) -> Result<Val> {107	Ok(108		match (evaluate(context.clone(), &a)?.unwrap_if_lazy()?, op, b) {109			(Val::Bool(true), BinaryOpType::Or, _o) => Val::Bool(true),110			(Val::Bool(false), BinaryOpType::And, _o) => Val::Bool(false),111			(a, op, eb) => {112				evaluate_binary_op_normal(&a, op, &evaluate(context, eb)?.unwrap_if_lazy()?)?113			}114		},115	)116}117118pub fn evaluate_binary_op_normal(a: &Val, op: BinaryOpType, b: &Val) -> Result<Val> {119	Ok(match (a, op, b) {120		(a, BinaryOpType::Add, b) => evaluate_add_op(a, b)?,121122		(Val::Str(v1), BinaryOpType::Mul, Val::Num(v2)) => Val::Str(v1.repeat(*v2 as usize)),123124		// Bool X Bool125		(Val::Bool(a), BinaryOpType::And, Val::Bool(b)) => Val::Bool(*a && *b),126		(Val::Bool(a), BinaryOpType::Or, Val::Bool(b)) => Val::Bool(*a || *b),127128		// Str X Str129		(Val::Str(v1), BinaryOpType::Lt, Val::Str(v2)) => Val::Bool(v1 < v2),130		(Val::Str(v1), BinaryOpType::Gt, Val::Str(v2)) => Val::Bool(v1 > v2),131		(Val::Str(v1), BinaryOpType::Lte, Val::Str(v2)) => Val::Bool(v1 <= v2),132		(Val::Str(v1), BinaryOpType::Gte, Val::Str(v2)) => Val::Bool(v1 >= v2),133134		// Num X Num135		(Val::Num(v1), BinaryOpType::Mul, Val::Num(v2)) => Val::Num(v1 * v2),136		(Val::Num(v1), BinaryOpType::Div, Val::Num(v2)) => Val::Num(v1 / v2),137138		(Val::Num(v1), BinaryOpType::Sub, Val::Num(v2)) => Val::Num(v1 - v2),139140		(Val::Num(v1), BinaryOpType::Lt, Val::Num(v2)) => Val::Bool(v1 < v2),141		(Val::Num(v1), BinaryOpType::Gt, Val::Num(v2)) => Val::Bool(v1 > v2),142		(Val::Num(v1), BinaryOpType::Lte, Val::Num(v2)) => Val::Bool(v1 <= v2),143		(Val::Num(v1), BinaryOpType::Gte, Val::Num(v2)) => Val::Bool(v1 >= v2),144145		(Val::Num(v1), BinaryOpType::BitAnd, Val::Num(v2)) => {146			Val::Num(((*v1 as i32) & (*v2 as i32)) as f64)147		}148		(Val::Num(v1), BinaryOpType::BitOr, Val::Num(v2)) => {149			Val::Num(((*v1 as i32) | (*v2 as i32)) as f64)150		}151		(Val::Num(v1), BinaryOpType::BitXor, Val::Num(v2)) => {152			Val::Num(((*v1 as i32) ^ (*v2 as i32)) as f64)153		}154		(Val::Num(v1), BinaryOpType::Lhs, Val::Num(v2)) => {155			Val::Num(((*v1 as i32) << (*v2 as i32)) as f64)156		}157		(Val::Num(v1), BinaryOpType::Rhs, Val::Num(v2)) => {158			Val::Num(((*v1 as i32) >> (*v2 as i32)) as f64)159		}160161		_ => panic!("no rules for binary operation: {:?} {:?} {:?}", a, op, b),162	})163}164165future_wrapper!(HashMap<String, LazyBinding>, FutureNewBindings);166future_wrapper!(ObjValue, FutureObjValue);167168pub fn evaluate_comp(169	context: Context,170	value: &LocExpr,171	specs: &[CompSpec],172) -> Result<Option<Vec<Val>>> {173	Ok(match specs.get(0) {174		None => Some(vec![evaluate(context, &value)?]),175		Some(CompSpec::IfSpec(IfSpecData(cond))) => {176			if evaluate(context.clone(), &cond)?.try_cast_bool("if spec")? {177				evaluate_comp(context, value, &specs[1..])?178			} else {179				None180			}181		}182		Some(CompSpec::ForSpec(ForSpecData(var, expr))) => {183			match evaluate(context.clone(), &expr)?.unwrap_if_lazy()? {184				Val::Arr(list) => {185					let mut out = Vec::new();186					for item in list {187						let item = item.clone().unwrap_if_lazy()?;188						out.push(evaluate_comp(189							context.with_var(var.clone(), item)?,190							value,191							&specs[1..],192						)?);193					}194					Some(out.iter().flatten().flatten().cloned().collect())195				}196				_ => panic!("for expression evaluated to non-iterable value"),197			}198		}199	})200}201202// TODO: Asserts203pub fn evaluate_object(context: Context, object: ObjBody) -> Result<ObjValue> {204	Ok(match object {205		ObjBody::MemberList(members) => {206			let new_bindings = FutureNewBindings::new();207			let future_this = FutureObjValue::new();208			let context_creator = context_creator!(209				closure!(clone context, clone new_bindings, clone future_this, |this: Option<ObjValue>, super_obj: Option<ObjValue>| {210					Ok(context.clone().extend(211						new_bindings.clone().unwrap(),212						context.clone().dollar().clone().or_else(||this.clone()),213						Some(this.unwrap()),214						super_obj215					)?)216				})217			);218			{219				let mut bindings: HashMap<String, LazyBinding> = HashMap::new();220				for (n, b) in members221					.iter()222					.filter_map(|m| match m {223						Member::BindStmt(b) => Some(b.clone()),224						_ => None,225					})226					.map(|b| evaluate_binding(&b, context_creator.clone()))227				{228					bindings.insert(n, b);229				}230				new_bindings.fill(bindings);231			}232233			let mut new_members = BTreeMap::new();234			for member in members.into_iter() {235				match member {236					Member::Field(FieldMember {237						name,238						plus,239						params: None,240						visibility,241						value,242					}) => {243						let name = evaluate_field_name(context.clone(), &name)?;244						if name.is_none() {245							continue;246						}247						let name = name.unwrap();248						new_members.insert(249							name.clone(),250							ObjMember {251								add: plus,252								visibility: visibility.clone(),253								invoke: binding!(254									closure!(clone name, clone value, clone context_creator, |this, super_obj| {255										push(value.clone(), "object ".to_owned()+&name+" field", ||{256											let context = context_creator.0(this, super_obj)?;257											evaluate(258												context,259												&value,260											)?.unwrap_if_lazy()261										})262									})263								),264							},265						);266					}267					Member::Field(FieldMember {268						name,269						params: Some(params),270						value,271						..272					}) => {273						let name = evaluate_field_name(context.clone(), &name)?;274						if name.is_none() {275							continue;276						}277						let name = name.unwrap();278						new_members.insert(279							name,280							ObjMember {281								add: false,282								visibility: Visibility::Hidden,283								invoke: binding!(284									closure!(clone value, clone context_creator, |this, super_obj| {285										// TODO: Assert286										Ok(evaluate_method(287											context_creator.0(this, super_obj)?,288											&value.clone(),289											params.clone(),290										))291									})292								),293							},294						);295					}296					Member::BindStmt(_) => {}297					Member::AssertStmt(_) => {}298				}299			}300			future_this.fill(ObjValue::new(None, Rc::new(new_members)))301		}302		_ => todo!(),303	})304}305306pub fn evaluate(context: Context, expr: &LocExpr) -> Result<Val> {307	use Expr::*;308	let locexpr = expr.clone();309	let LocExpr(expr, loc) = expr;310	Ok(match &**expr {311		Literal(LiteralType::This) => Val::Obj(312			context313				.this()314				.clone()315				.unwrap_or_else(|| panic!("this not found")),316		),317		Literal(LiteralType::Dollar) => Val::Obj(318			context319				.dollar()320				.clone()321				.unwrap_or_else(|| panic!("dollar not found")),322		),323		Literal(LiteralType::True) => Val::Bool(true),324		Literal(LiteralType::False) => Val::Bool(false),325		Literal(LiteralType::Null) => Val::Null,326		Parened(e) => evaluate(context, e)?,327		Str(v) => Val::Str(v.clone()),328		Num(v) => Val::Num(*v),329		BinaryOp(v1, o, v2) => evaluate_binary_op_special(context, &v1, *o, &v2)?,330		UnaryOp(o, v) => evaluate_unary_op(*o, &evaluate(context, v)?)?,331		Var(name) => push(locexpr, "var".to_owned(), || {332			Val::Lazy(context.binding(&name)).unwrap_if_lazy()333		})?,334		Index(LocExpr(v, _), index) if matches!(&**v, Expr::Literal(LiteralType::Super)) => {335			let name = evaluate(context.clone(), index)?.try_cast_str("object index")?;336			context337				.super_obj()338				.clone()339				.expect("no super found")340				.get_raw(&name, &context.this().clone().expect("no this found"))?341				.expect("value not found")342		}343		Index(value, index) => {344			match (345				evaluate(context.clone(), value)?.unwrap_if_lazy()?,346				evaluate(context, index)?,347			) {348				(Val::Obj(v), Val::Str(s)) => {349					if let Some(v) = v.get(&s)? {350						v.unwrap_if_lazy()?351					} else if let Some(Val::Str(n)) = v.get("__intristic_namespace__")? {352						Val::Intristic(n, s)353					} else {354						create_error(crate::Error::NoSuchField(s))?355					}356				}357				(Val::Arr(v), Val::Num(n)) => v358					.get(n as usize)359					.unwrap_or_else(|| panic!("out of bounds"))360					.clone()361					.unwrap_if_lazy()?,362				(Val::Str(s), Val::Num(n)) => {363					Val::Str(s.chars().skip(n as usize).take(1).collect())364				}365				(v, i) => todo!("not implemented: {:?}[{:?}]", v, i.unwrap_if_lazy()),366			}367		}368		LocalExpr(bindings, returned) => {369			let mut new_bindings: HashMap<String, LazyBinding> = HashMap::new();370			let future_context = Context::new_future();371372			let context_creator = context_creator!(373				closure!(clone future_context, |_, _| Ok(future_context.clone().unwrap()))374			);375376			for (k, v) in bindings377				.iter()378				.map(|b| evaluate_binding(b, context_creator.clone()))379			{380				new_bindings.insert(k, v);381			}382383			let context = context384				.extend(new_bindings, None, None, None)?385				.into_future(future_context);386			evaluate(context, &returned.clone())?387		}388		Arr(items) => {389			let mut out = Vec::with_capacity(items.len());390			for item in items {391				out.push(Val::Lazy(lazy_val!(392					closure!(clone context, clone item, || {393						evaluate(context.clone(), &item)394					})395				)));396			}397			Val::Arr(out)398		}399		ArrComp(expr, compspecs) => Val::Arr(400			// First compspec should be forspec, so no "None" possible here401			evaluate_comp(context, expr, compspecs)?.unwrap(),402		),403		Obj(body) => Val::Obj(evaluate_object(context, body.clone())?),404		ObjExtend(s, t) => evaluate_add_op(405			&evaluate(context.clone(), s)?,406			&Val::Obj(evaluate_object(context, t.clone())?),407		)?,408		Apply(value, ArgsDesc(args)) => {409			let value = evaluate(context.clone(), value)?.unwrap_if_lazy()?;410			match value {411				Val::Intristic(ns, name) => match (&ns as &str, &name as &str) {412					// arr/string/function413					("std", "length") => {414						assert_eq!(args.len(), 1);415						let expr = &args.get(0).unwrap().1;416						match evaluate(context, expr)? {417							Val::Str(n) => Val::Num(n.chars().count() as f64),418							Val::Arr(i) => Val::Num(i.len() as f64),419							Val::Obj(o) => Val::Num(o.fields().len() as f64),420							v => panic!("can't get length of {:?}", v),421						}422					}423					// any424					("std", "type") => {425						assert_eq!(args.len(), 1);426						let expr = &args.get(0).unwrap().1;427						Val::Str(evaluate(context, expr)?.value_type()?.name().to_owned())428					}429					// length, idx=>any430					("std", "makeArray") => {431						assert_eq!(args.len(), 2);432						if let (Val::Num(v), Val::Func(d)) = (433							evaluate(context.clone(), &args[0].1)?,434							evaluate(context, &args[1].1)?,435						) {436							assert!(v >= 0.0);437							let mut out = Vec::with_capacity(v as usize);438							for i in 0..v as usize {439								out.push(d.evaluate(vec![(None, Val::Num(i as f64))])?)440							}441							Val::Arr(out)442						} else {443							panic!("bad makeArray call");444						}445					}446					// string447					("std", "codepoint") => {448						assert_eq!(args.len(), 1);449						if let Val::Str(s) = evaluate(context, &args[0].1)? {450							assert!(451								s.chars().count() == 1,452								"std.codepoint should receive single char string"453							);454							Val::Num(s.chars().take(1).next().unwrap() as u32 as f64)455						} else {456							panic!("bad codepoint call");457						}458					}459					// object, includeHidden460					("std", "objectFieldsEx") => {461						assert_eq!(args.len(), 2);462						if let (Val::Obj(body), Val::Bool(_include_hidden)) = (463							evaluate(context.clone(), &args[0].1)?,464							evaluate(context, &args[1].1)?,465						) {466							// TODO: handle visibility (_include_hidden)467							Val::Arr(body.fields().into_iter().map(Val::Str).collect())468						} else {469							panic!("bad objectFieldsEx call");470						}471					}472					("std", "primitiveEquals") => {473						assert_eq!(args.len(), 2);474						let (a, b) = (475							evaluate(context.clone(), &args[0].1)?,476							evaluate(context, &args[1].1)?,477						);478						Val::Bool(a == b)479					}480					("std", "modulo") => {481						assert_eq!(args.len(), 2);482						if let (Val::Num(a), Val::Num(b)) = (483							evaluate(context.clone(), &args[0].1)?,484							evaluate(context, &args[1].1)?,485						) {486							Val::Num(a % b)487						} else {488							panic!("bad modulo call");489						}490					}491					("std", "floor") => {492						assert_eq!(args.len(), 1);493						if let Val::Num(a) = evaluate(context, &args[0].1)? {494							Val::Num(a.floor())495						} else {496							panic!("bad floor call");497						}498					}499					(ns, name) => panic!("Intristic not found: {}.{}", ns, name),500				},501				Val::Func(f) => push(locexpr, "function call".to_owned(), || {502					f.evaluate(503						args.clone()504							.into_iter()505							.map(move |a| {506								(507									a.clone().0,508									Val::Lazy(lazy_val!(509										closure!(clone context, clone a, || evaluate(context.clone(), &a.clone().1))510									)),511								)512							})513							.collect(),514					)515				})?,516				_ => panic!("{:?} is not a function", value),517			}518		}519		Function(params, body) => evaluate_method(context, body, params.clone()),520		AssertExpr(AssertStmt(value, msg), returned) => {521			let assertion_result = push(value.clone(), "assertion condition".to_owned(), || {522				evaluate(context.clone(), &value)?523					.try_cast_bool("assertion condition should be boolean")524			})?;525			if assertion_result {526				push(527					returned.clone(),528					"assert 'return' branch".to_owned(),529					|| evaluate(context, returned),530				)?531			} else if let Some(msg) = msg {532				panic!(533					"assertion failed ({:?}): {}",534					value,535					evaluate(context, msg)?.try_cast_str("assertion message should be string")?536				);537			} else {538				panic!("assertion failed ({:?}): no message", value);539			}540		}541		Error(e) => create_error(crate::Error::RuntimeError(542			evaluate(context, e)?.try_cast_str("error text should be string")?,543		))?,544		IfElse {545			cond,546			cond_then,547			cond_else,548		} => {549			let condition_result = push(cond.0.clone(), "if condition".to_owned(), || {550				evaluate(context.clone(), &cond.0)?.try_cast_bool("if condition should be boolean")551			})?;552			if condition_result {553				push(554					cond_then.clone(),555					"if condition 'then' branch".to_owned(),556					|| evaluate(context, cond_then),557				)?558			} else {559				match cond_else {560					Some(v) => push(v.clone(), "if condition 'else' branch".to_owned(), || {561						evaluate(context, v)562					})?,563					None => Val::Null,564				}565			}566		}567		_ => panic!(568			"evaluation not implemented: {:?}",569			LocExpr(expr.clone(), loc.clone())570		),571	})572}
modifiedcrates/jsonnet-evaluator/src/lib.rsdiffbeforeafterboth
--- a/crates/jsonnet-evaluator/src/lib.rs
+++ b/crates/jsonnet-evaluator/src/lib.rs
@@ -16,7 +16,7 @@
 pub use evaluate::*;
 use jsonnet_parser::*;
 pub use obj::*;
-use std::{cell::RefCell, collections::HashMap, rc::Rc};
+use std::{cell::RefCell, collections::HashMap, path::PathBuf, rc::Rc};
 pub use val::*;
 
 rc_fn_helper!(
@@ -43,7 +43,7 @@
 	stack: RefCell<Vec<StackTraceElement>>,
 	/// Contains file source codes and evaluated results for imports and pretty
 	/// printing stacktraces
-	files: RefCell<HashMap<String, FileData>>,
+	files: RefCell<HashMap<PathBuf, FileData>>,
 	globals: RefCell<HashMap<String, Val>>,
 }
 
@@ -56,7 +56,7 @@
 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 {
+pub(crate) fn push<T>(e: LocExpr, comment: String, f: impl FnOnce() -> Result<T>) -> Result<T> {
 	with_state(|s| s.push(e, comment, f))
 }
 
@@ -65,7 +65,7 @@
 impl EvaluationState {
 	pub fn add_file(
 		&self,
-		name: String,
+		name: PathBuf,
 		code: String,
 	) -> std::result::Result<(), Box<dyn std::error::Error>> {
 		self.0.files.borrow_mut().insert(
@@ -87,7 +87,7 @@
 	}
 	pub fn add_parsed_file(
 		&self,
-		name: String,
+		name: PathBuf,
 		code: String,
 		parsed: LocExpr,
 	) -> std::result::Result<(), Box<dyn std::error::Error>> {
@@ -98,14 +98,13 @@
 
 		Ok(())
 	}
-	pub fn get_source(&self, name: &str) -> String {
+	pub fn get_source(&self, name: &PathBuf) -> Option<String> {
 		let ro_map = self.0.files.borrow();
-		let value = ro_map
+		ro_map
 			.get(name)
-			.unwrap_or_else(|| panic!("file not added: {:?}", name));
-		value.0.clone()
+			.map(|value|value.0.clone())
 	}
-	pub fn evaluate_file(&self, name: &str) -> Result<Val> {
+	pub fn evaluate_file(&self, name: &PathBuf) -> Result<Val> {
 		self.begin_state();
 		let expr: LocExpr = {
 			let ro_map = self.0.files.borrow();
@@ -135,7 +134,7 @@
 		let parsed = parse(
 			&code,
 			&ParserSettings {
-				file_name: "raw.jsonnet".to_owned(),
+				file_name: PathBuf::from("raw.jsonnet"),
 				loc_data: true,
 			},
 		);
@@ -154,17 +153,17 @@
 		use jsonnet_stdlib::STDLIB_STR;
 		if cfg!(feature = "serialized-stdlib") {
 			self.add_parsed_file(
-				"std.jsonnet".to_owned(),
+				PathBuf::from("std.jsonnet"),
 				STDLIB_STR.to_owned(),
 				bincode::deserialize(include_bytes!(concat!(env!("OUT_DIR"), "/stdlib.bincode")))
 					.expect("deserialize stdlib"),
 			)
 			.unwrap();
 		} else {
-			self.add_file("std.jsonnet".to_owned(), STDLIB_STR.to_owned())
+			self.add_file(PathBuf::from("std.jsonnet"), STDLIB_STR.to_owned())
 				.unwrap();
 		}
-		let val = self.evaluate_file("std.jsonnet").unwrap();
+		let val = self.evaluate_file(&PathBuf::from("std.jsonnet")).unwrap();
 		self.add_global("std".to_owned(), val);
 		self.end_state();
 	}
@@ -183,11 +182,16 @@
 		Context::new().extend(new_bindings, None, None, None)
 	}
 
-	pub fn push<T>(&self, e: LocExpr, comment: String, f: impl FnOnce() -> T) -> T {
-		self.0
-			.stack
-			.borrow_mut()
-			.push(StackTraceElement(e, comment));
+	pub fn push<T>(&self, e: LocExpr, comment: String, f: impl FnOnce() -> Result<T>) -> Result<T> {
+		{
+			let mut stack = self.0.stack.borrow_mut();
+			if stack.len() > 5000 {
+				drop(stack);
+				return self.error(Error::StackOverflow);
+			} else {
+				stack.push(StackTraceElement(e, comment));
+			}
+		}
 		let result = f();
 		self.0.stack.borrow_mut().pop();
 		result
@@ -217,21 +221,36 @@
 	use super::Val;
 	use crate::EvaluationState;
 	use jsonnet_parser::*;
+	use std::path::PathBuf;
 
 	#[test]
 	fn eval_state_stacktrace() {
 		let state = EvaluationState::default();
-		state.push(
-			loc_expr!(Expr::Num(0.0), true, ("test1.jsonnet".to_owned(), 10, 20)),
-			"outer".to_owned(),
-			|| {
-				state.push(
-					loc_expr!(Expr::Num(0.0), true, ("test2.jsonnet".to_owned(), 30, 40)),
-					"inner".to_owned(),
-					|| state.print_stack_trace(),
-				);
-			},
-		);
+		state
+			.push(
+				loc_expr!(
+					Expr::Num(0.0),
+					true,
+					(PathBuf::from("test1.jsonnet"), 10, 20)
+				),
+				"outer".to_owned(),
+				|| {
+					state.push(
+						loc_expr!(
+							Expr::Num(0.0),
+							true,
+							(PathBuf::from("test2.jsonnet"), 30, 40)
+						),
+						"inner".to_owned(),
+						|| {
+							state.print_stack_trace();
+							Ok(())
+						},
+					)?;
+					Ok(())
+				},
+			)
+			.unwrap();
 	}
 
 	#[test]
@@ -240,7 +259,7 @@
 		state.add_stdlib();
 		assert_eq!(
 			state
-				.parse_evaluate_raw(r#"std.assertEqual(std.base64("test"), "dGVzdA==w")"#)
+				.parse_evaluate_raw(r#"std.assertEqual(std.base64("test"), "dGVzdA==")"#)
 				.unwrap(),
 			Val::Bool(true)
 		);