git.delta.rocks / jrsonnet / refs/commits / 2edd59dfdd9f

difftreelog

source

crates/jsonnet-evaluator/src/evaluate.rs21.3 KiBsourcehistory
1use crate::{2	context_creator, create_error, future_wrapper, lazy_val, push, with_state, Context,3	ContextCreator, Error, FuncDesc, LazyBinding, LazyVal, ObjMember, ObjValue, Result, Val,4};5use closure::closure;6use jsonnet_parser::{7	el, Arg, ArgsDesc, AssertStmt, BinaryOpType, BindSpec, CompSpec, Expr, FieldMember,8	ForSpecData, IfSpecData, LiteralType, LocExpr, Member, ObjBody, ParamsDesc, UnaryOpType,9	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(params) = &b.params {19		let params = params.clone();20		(21			b.name.clone(),22			LazyBinding::Bindable(Rc::new(move |this, super_obj| {23				Ok(lazy_val!(24					closure!(clone b, clone params, clone context_creator, || Ok(evaluate_method(25						context_creator.0(this.clone(), super_obj.clone())?,26						params.clone(),27						b.value.clone(),28					)))29				))30			})),31		)32	} else {33		(34			b.name.clone(),35			LazyBinding::Bindable(Rc::new(move |this, super_obj| {36				Ok(lazy_val!(closure!(clone context_creator, clone b, ||37					push(b.value.clone(), "thunk".to_owned(), ||{38						evaluate(39							context_creator.0(this.clone(), super_obj.clone())?,40							&b.value41						)42					})43				)))44			})),45		)46	}47}4849pub fn evaluate_method(ctx: Context, params: ParamsDesc, body: LocExpr) -> Val {50	Val::Func(FuncDesc { ctx, params, body })51}5253pub fn evaluate_field_name(54	context: Context,55	field_name: &jsonnet_parser::FieldName,56) -> Result<Option<String>> {57	Ok(match field_name {58		jsonnet_parser::FieldName::Fixed(n) => Some(n.clone()),59		jsonnet_parser::FieldName::Dyn(expr) => {60			let value = evaluate(context, expr)?.unwrap_if_lazy()?;61			if matches!(value, Val::Null) {62				None63			} else {64				Some(value.try_cast_str("dynamic field name")?)65			}66		}67	})68}6970pub fn evaluate_unary_op(op: UnaryOpType, b: &Val) -> Result<Val> {71	Ok(match (op, b) {72		(o, Val::Lazy(l)) => evaluate_unary_op(o, &l.evaluate()?)?,73		(UnaryOpType::Not, Val::Bool(v)) => Val::Bool(!v),74		(UnaryOpType::Minus, Val::Num(n)) => Val::Num(-*n),75		(UnaryOpType::BitNot, Val::Num(n)) => Val::Num(!(*n as i32) as f64),76		(op, o) => panic!("unary op not implemented: {:?} {:?}", op, o),77	})78}7980pub(crate) fn evaluate_add_op(a: &Val, b: &Val) -> Result<Val> {81	Ok(match (a, b) {82		(Val::Str(v1), Val::Str(v2)) => Val::Str(v1.to_owned() + &v2),8384		(Val::Str(v1), Val::Num(v2)) => Val::Str(format!("{}{}", v1, v2)),85		(Val::Num(v1), Val::Str(v2)) => Val::Str(format!("{}{}", v1, v2)),86		(Val::Str(v1), Val::Bool(v2)) => Val::Str(format!("{}{}", v1, v2)),87		(Val::Bool(v1), Val::Str(v2)) => Val::Str(format!("{}{}", v1, v2)),88		(Val::Str(v1), Val::Null) => Val::Str(format!("{}null", v1)),89		(Val::Null, Val::Str(v2)) => Val::Str(format!("null{}", v2)),9091		(Val::Obj(v1), Val::Obj(v2)) => Val::Obj(v2.with_super(v1.clone())),92		(Val::Arr(a), Val::Arr(b)) => Val::Arr([&a[..], &b[..]].concat()),93		(Val::Num(v1), Val::Num(v2)) => Val::Num(v1 + v2),94		_ => panic!("can't add: {:?} and {:?}", a, b),95	})96}9798pub fn evaluate_binary_op_special(99	context: Context,100	a: &LocExpr,101	op: BinaryOpType,102	b: &LocExpr,103) -> Result<Val> {104	Ok(105		match (evaluate(context.clone(), &a)?.unwrap_if_lazy()?, op, b) {106			(Val::Bool(true), BinaryOpType::Or, _o) => Val::Bool(true),107			(Val::Bool(false), BinaryOpType::And, _o) => Val::Bool(false),108			(a, op, eb) => {109				evaluate_binary_op_normal(&a, op, &evaluate(context, eb)?.unwrap_if_lazy()?)?110			}111		},112	)113}114115pub fn evaluate_binary_op_normal(a: &Val, op: BinaryOpType, b: &Val) -> Result<Val> {116	Ok(match (a, op, b) {117		(a, BinaryOpType::Add, b) => evaluate_add_op(a, b)?,118119		(Val::Str(v1), BinaryOpType::Mul, Val::Num(v2)) => Val::Str(v1.repeat(*v2 as usize)),120121		// Bool X Bool122		(Val::Bool(a), BinaryOpType::And, Val::Bool(b)) => Val::Bool(*a && *b),123		(Val::Bool(a), BinaryOpType::Or, Val::Bool(b)) => Val::Bool(*a || *b),124125		// Str X Str126		(Val::Str(v1), BinaryOpType::Lt, Val::Str(v2)) => Val::Bool(v1 < v2),127		(Val::Str(v1), BinaryOpType::Gt, Val::Str(v2)) => Val::Bool(v1 > v2),128		(Val::Str(v1), BinaryOpType::Lte, Val::Str(v2)) => Val::Bool(v1 <= v2),129		(Val::Str(v1), BinaryOpType::Gte, Val::Str(v2)) => Val::Bool(v1 >= v2),130131		// Num X Num132		(Val::Num(v1), BinaryOpType::Mul, Val::Num(v2)) => Val::Num(v1 * v2),133		(Val::Num(v1), BinaryOpType::Div, Val::Num(v2)) => {134			if *v2 <= f64::EPSILON {135				create_error(crate::Error::DivisionByZero)?136			}137			Val::Num(v1 / v2)138		}139140		(Val::Num(v1), BinaryOpType::Sub, Val::Num(v2)) => Val::Num(v1 - v2),141142		(Val::Num(v1), BinaryOpType::Lt, Val::Num(v2)) => Val::Bool(v1 < v2),143		(Val::Num(v1), BinaryOpType::Gt, Val::Num(v2)) => Val::Bool(v1 > v2),144		(Val::Num(v1), BinaryOpType::Lte, Val::Num(v2)) => Val::Bool(v1 <= v2),145		(Val::Num(v1), BinaryOpType::Gte, Val::Num(v2)) => Val::Bool(v1 >= v2),146147		(Val::Num(v1), BinaryOpType::BitAnd, Val::Num(v2)) => {148			Val::Num(((*v1 as i32) & (*v2 as i32)) as f64)149		}150		(Val::Num(v1), BinaryOpType::BitOr, Val::Num(v2)) => {151			Val::Num(((*v1 as i32) | (*v2 as i32)) as f64)152		}153		(Val::Num(v1), BinaryOpType::BitXor, Val::Num(v2)) => {154			Val::Num(((*v1 as i32) ^ (*v2 as i32)) as f64)155		}156		(Val::Num(v1), BinaryOpType::Lhs, Val::Num(v2)) => {157			Val::Num(((*v1 as i32) << (*v2 as i32)) as f64)158		}159		(Val::Num(v1), BinaryOpType::Rhs, Val::Num(v2)) => {160			Val::Num(((*v1 as i32) >> (*v2 as i32)) as f64)161		}162163		_ => panic!("no rules for binary operation: {:?} {:?} {:?}", a, op, b),164	})165}166167future_wrapper!(HashMap<String, LazyBinding>, FutureNewBindings);168future_wrapper!(ObjValue, FutureObjValue);169170#[inline(always)]171pub fn evaluate_comp<T>(172	context: Context,173	value: &impl Fn(Context) -> Result<T>,174	specs: &[CompSpec],175) -> Result<Option<Vec<T>>> {176	Ok(match specs.get(0) {177		None => Some(vec![value(context)?]),178		Some(CompSpec::IfSpec(IfSpecData(cond))) => {179			if evaluate(context.clone(), &cond)?.try_cast_bool("if spec")? {180				evaluate_comp(context, value, &specs[1..])?181			} else {182				None183			}184		}185		Some(CompSpec::ForSpec(ForSpecData(var, expr))) => {186			match evaluate(context.clone(), &expr)?.unwrap_if_lazy()? {187				Val::Arr(list) => {188					let mut out = Vec::new();189					for item in list {190						let item = item.clone().unwrap_if_lazy()?;191						out.push(evaluate_comp(192							context.with_var(var.clone(), item)?,193							value,194							&specs[1..],195						)?);196					}197					Some(out.into_iter().flatten().flatten().collect())198				}199				_ => panic!("for expression evaluated to non-iterable value"),200			}201		}202	})203}204205// TODO: Asserts206pub fn evaluate_object(context: Context, object: ObjBody) -> Result<ObjValue> {207	Ok(match object {208		ObjBody::MemberList(members) => {209			let new_bindings = FutureNewBindings::new();210			let future_this = FutureObjValue::new();211			let context_creator = context_creator!(212				closure!(clone context, clone new_bindings, |this: Option<ObjValue>, super_obj: Option<ObjValue>| {213					Ok(context.clone().extend_unbound(214						new_bindings.clone().unwrap(),215						context.clone().dollar().clone().or_else(||this.clone()),216						Some(this.unwrap()),217						super_obj218					)?)219				})220			);221			{222				let mut bindings: HashMap<String, LazyBinding> = HashMap::new();223				for (n, b) in members224					.iter()225					.filter_map(|m| match m {226						Member::BindStmt(b) => Some(b.clone()),227						_ => None,228					})229					.map(|b| evaluate_binding(&b, context_creator.clone()))230				{231					bindings.insert(n, b);232				}233				new_bindings.fill(bindings);234			}235236			let mut new_members = BTreeMap::new();237			for member in members.into_iter() {238				match member {239					Member::Field(FieldMember {240						name,241						plus,242						params: None,243						visibility,244						value,245					}) => {246						let name = evaluate_field_name(context.clone(), &name)?;247						if name.is_none() {248							continue;249						}250						let name = name.unwrap();251						new_members.insert(252							name.clone(),253							ObjMember {254								add: plus,255								visibility: visibility.clone(),256								invoke: LazyBinding::Bindable(Rc::new(257									closure!(clone name, clone value, clone context_creator, |this, super_obj| {258										Ok(LazyVal::new_resolved(push(value.clone(), "object ".to_owned()+&name+" field", ||{259											let context = context_creator.0(this, super_obj)?;260											evaluate(261												context,262												&value,263											)?.unwrap_if_lazy()264										})?))265									}),266								)),267							},268						);269					}270					Member::Field(FieldMember {271						name,272						params: Some(params),273						value,274						..275					}) => {276						let name = evaluate_field_name(context.clone(), &name)?;277						if name.is_none() {278							continue;279						}280						let name = name.unwrap();281						new_members.insert(282							name,283							ObjMember {284								add: false,285								visibility: Visibility::Hidden,286								invoke: LazyBinding::Bindable(Rc::new(287									closure!(clone value, clone context_creator, |this, super_obj| {288										// TODO: Assert289										Ok(LazyVal::new_resolved(evaluate_method(290											context_creator.0(this, super_obj)?,291											params.clone(),292											value.clone(),293										)))294									}),295								)),296							},297						);298					}299					Member::BindStmt(_) => {}300					Member::AssertStmt(_) => {}301				}302			}303			future_this.fill(ObjValue::new(None, Rc::new(new_members)))304		}305		ObjBody::ObjComp {306			pre_locals,307			key,308			value,309			post_locals,310			compspecs,311		} => {312			let future_this = FutureObjValue::new();313			let mut new_members = BTreeMap::new();314			for (k, v) in evaluate_comp(315				context.clone(),316				&|ctx| {317					let new_bindings = FutureNewBindings::new();318					let context_creator = context_creator!(319						closure!(clone context, clone new_bindings, |this: Option<ObjValue>, super_obj: Option<ObjValue>| {320							Ok(context.clone().extend_unbound(321								new_bindings.clone().unwrap(),322								context.clone().dollar().clone().or_else(||this.clone()),323								None,324								super_obj325							)?)326						})327					);328					let mut bindings: HashMap<String, LazyBinding> = HashMap::new();329					for (n, b) in pre_locals330						.iter()331						.chain(post_locals.iter())332						.map(|b| evaluate_binding(b, context_creator.clone()))333					{334						bindings.insert(n, b);335					}336					let bindings = new_bindings.fill(bindings);337					let ctx = ctx.extend_unbound(bindings, None, None, None)?;338					let key = evaluate(ctx.clone(), &key)?;339					let value = LazyBinding::Bindable(Rc::new(340						closure!(clone ctx, clone value, |this, _super_obj| {341							Ok(LazyVal::new_resolved(evaluate(ctx.extend(HashMap::new(), None, this, None)?, &value)?))342						}),343					));344345					Ok((key, value))346				},347				&compspecs,348			)?349			.unwrap()350			{351				match k {352					Val::Null => {}353					Val::Str(n) => {354						new_members.insert(355							n,356							ObjMember {357								add: false,358								visibility: Visibility::Normal,359								invoke: v,360							},361						);362					}363					v => create_error(Error::FieldMustBeStringGot(v.value_type()?))?,364				}365			}366367			future_this.fill(ObjValue::new(None, Rc::new(new_members)))368		}369	})370}371372#[inline(always)]373pub fn evaluate(context: Context, expr: &LocExpr) -> Result<Val> {374	use Expr::*;375	let locexpr = expr.clone();376	let LocExpr(expr, loc) = expr;377	Ok(match &**expr {378		Literal(LiteralType::This) => Val::Obj(379			context380				.this()381				.clone()382				.unwrap_or_else(|| panic!("this not found")),383		),384		Literal(LiteralType::Dollar) => Val::Obj(385			context386				.dollar()387				.clone()388				.unwrap_or_else(|| panic!("dollar not found")),389		),390		Literal(LiteralType::True) => Val::Bool(true),391		Literal(LiteralType::False) => Val::Bool(false),392		Literal(LiteralType::Null) => Val::Null,393		Parened(e) => evaluate(context, e)?,394		Str(v) => Val::Str(v.clone()),395		Num(v) => Val::Num(*v),396		BinaryOp(v1, o, v2) => evaluate_binary_op_special(context, &v1, *o, &v2)?,397		UnaryOp(o, v) => evaluate_unary_op(*o, &evaluate(context, v)?)?,398		Var(name) => push(locexpr, "var".to_owned(), || {399			Val::Lazy(context.binding(&name)).unwrap_if_lazy()400		})?,401		Index(LocExpr(v, _), index) if matches!(&**v, Expr::Literal(LiteralType::Super)) => {402			let name = evaluate(context.clone(), index)?.try_cast_str("object index")?;403			context404				.super_obj()405				.clone()406				.expect("no super found")407				.get_raw(&name, &context.this().clone().expect("no this found"))?408				.expect("value not found")409		}410		Index(value, index) => {411			match (412				evaluate(context.clone(), value)?.unwrap_if_lazy()?,413				evaluate(context, index)?,414			) {415				(Val::Obj(v), Val::Str(s)) => {416					if let Some(v) = v.get(&s)? {417						v.unwrap_if_lazy()?418					} else if let Some(Val::Str(n)) = v.get("__intristic_namespace__")? {419						Val::Intristic(n, s)420					} else {421						create_error(crate::Error::NoSuchField(s))?422					}423				}424				(Val::Obj(_), n) => create_error(crate::Error::ValueIndexMustBeTypeGot(425					ValType::Obj,426					ValType::Str,427					n.value_type()?,428				))?,429430				(Val::Arr(v), Val::Num(n)) => {431					if n.fract() > f64::EPSILON {432						create_error(crate::Error::FractionalIndex)?433					}434					v.get(n as usize)435						.unwrap_or_else(|| panic!("out of bounds"))436						.clone()437						.unwrap_if_lazy()?438				}439				(Val::Arr(_), Val::Str(n)) => {440					create_error(crate::Error::AttemptedIndexAnArrayWithString(n))?441				}442				(Val::Arr(_), n) => create_error(crate::Error::ValueIndexMustBeTypeGot(443					ValType::Arr,444					ValType::Num,445					n.value_type()?,446				))?,447448				(Val::Str(s), Val::Num(n)) => {449					Val::Str(s.chars().skip(n as usize).take(1).collect())450				}451				(Val::Str(_), n) => create_error(crate::Error::ValueIndexMustBeTypeGot(452					ValType::Str,453					ValType::Num,454					n.value_type()?,455				))?,456457				(v, _) => create_error(crate::Error::CantIndexInto(v.value_type()?))?,458			}459		}460		LocalExpr(bindings, returned) => {461			let mut new_bindings: HashMap<String, LazyBinding> = HashMap::new();462			let future_context = Context::new_future();463464			let context_creator = context_creator!(465				closure!(clone future_context, |_, _| Ok(future_context.clone().unwrap()))466			);467468			for (k, v) in bindings469				.iter()470				.map(|b| evaluate_binding(b, context_creator.clone()))471			{472				new_bindings.insert(k, v);473			}474475			let context = context476				.extend_unbound(new_bindings, None, None, None)?477				.into_future(future_context);478			evaluate(context, &returned.clone())?479		}480		Arr(items) => {481			let mut out = Vec::with_capacity(items.len());482			for item in items {483				out.push(Val::Lazy(lazy_val!(484					closure!(clone context, clone item, || {485						evaluate(context.clone(), &item)486					})487				)));488			}489			Val::Arr(out)490		}491		ArrComp(expr, compspecs) => Val::Arr(492			// First compspec should be forspec, so no "None" possible here493			evaluate_comp(context, &|ctx| evaluate(ctx, expr), compspecs)?.unwrap(),494		),495		Obj(body) => Val::Obj(evaluate_object(context, body.clone())?),496		ObjExtend(s, t) => evaluate_add_op(497			&evaluate(context.clone(), s)?,498			&Val::Obj(evaluate_object(context, t.clone())?),499		)?,500		Apply(value, args, tailstrict) => {501			let value = evaluate(context.clone(), value)?.unwrap_if_lazy()?;502			match value {503				Val::Intristic(ns, name) => match (&ns as &str, &name as &str) {504					// arr/string/function505					("std", "length") => {506						assert_eq!(args.len(), 1);507						let expr = &args.get(0).unwrap().1;508						match evaluate(context, expr)? {509							Val::Str(n) => Val::Num(n.chars().count() as f64),510							Val::Arr(i) => Val::Num(i.len() as f64),511							Val::Obj(o) => Val::Num(512								o.fields_visibility()513									.into_iter()514									.filter(|(_k, v)| *v)515									.count() as f64,516							),517							v => panic!("can't get length of {:?}", v),518						}519					}520					// any521					("std", "type") => {522						assert_eq!(args.len(), 1);523						let expr = &args.get(0).unwrap().1;524						Val::Str(evaluate(context, expr)?.value_type()?.name().to_owned())525					}526					// length, idx=>any527					("std", "makeArray") => {528						assert_eq!(args.len(), 2);529						if let (Val::Num(v), Val::Func(d)) = (530							evaluate(context.clone(), &args[0].1)?,531							evaluate(context, &args[1].1)?,532						) {533							assert!(v >= 0.0);534							let mut out = Vec::with_capacity(v as usize);535							for i in 0..v as usize {536								let call_ctx =537									Context::new().with_var("v".to_owned(), Val::Num(i as f64))?;538								out.push(d.evaluate(539									call_ctx,540									&ArgsDesc(vec![Arg(None, el!(Expr::Var("v".to_owned())))]),541									true,542								)?)543							}544							Val::Arr(out)545						} else {546							panic!("bad makeArray call");547						}548					}549					// string550					("std", "codepoint") => {551						assert_eq!(args.len(), 1);552						if let Val::Str(s) = evaluate(context, &args[0].1)? {553							assert!(554								s.chars().count() == 1,555								"std.codepoint should receive single char string"556							);557							Val::Num(s.chars().take(1).next().unwrap() as u32 as f64)558						} else {559							panic!("bad codepoint call");560						}561					}562					// object, includeHidden563					("std", "objectFieldsEx") => {564						assert_eq!(args.len(), 2);565						if let (Val::Obj(body), Val::Bool(include_hidden)) = (566							evaluate(context.clone(), &args[0].1)?,567							evaluate(context, &args[1].1)?,568						) {569							Val::Arr(570								body.fields_visibility()571									.into_iter()572									.filter(|(_k, v)| *v || include_hidden)573									.map(|(k, _v)| Val::Str(k))574									.collect(),575							)576						} else {577							panic!("bad objectFieldsEx call");578						}579					}580					// object, field, includeHidden581					("std", "objectHasEx") => {582						assert_eq!(args.len(), 3);583						if let (Val::Obj(body), Val::Str(name), Val::Bool(include_hidden)) = (584							evaluate(context.clone(), &args[0].1)?,585							evaluate(context.clone(), &args[1].1)?,586							evaluate(context, &args[2].1)?,587						) {588							Val::Bool(589								body.fields_visibility()590									.into_iter()591									.filter(|(_k, v)| *v || include_hidden)592									.any(|(k, _v)| k == name),593							)594						} else {595							panic!("bad objectHasEx call");596						}597					}598					("std", "primitiveEquals") => {599						assert_eq!(args.len(), 2);600						let (a, b) = (601							evaluate(context.clone(), &args[0].1)?,602							evaluate(context, &args[1].1)?,603						);604						Val::Bool(a == b)605					}606					("std", "modulo") => {607						assert_eq!(args.len(), 2);608						if let (Val::Num(a), Val::Num(b)) = (609							evaluate(context.clone(), &args[0].1)?,610							evaluate(context, &args[1].1)?,611						) {612							Val::Num(a % b)613						} else {614							panic!("bad modulo call");615						}616					}617					("std", "floor") => {618						assert_eq!(args.len(), 1);619						if let Val::Num(a) = evaluate(context, &args[0].1)? {620							Val::Num(a.floor())621						} else {622							panic!("bad floor call");623						}624					}625					("std", "trace") => {626						assert_eq!(args.len(), 2);627						if let (Val::Str(a), b) = (628							evaluate(context.clone(), &args[0].1)?,629							evaluate(context, &args[1].1)?,630						) {631							// TODO: Line numbers as in original jsonnet632							println!("TRACE: {}", a);633							b634						} else {635							panic!("bad trace call");636						}637					}638					("std", "pow") => {639						assert_eq!(args.len(), 2);640						if let (Val::Num(a), Val::Num(b)) = (641							evaluate(context.clone(), &args[0].1)?,642							evaluate(context, &args[1].1)?,643						) {644							Val::Num(a.powf(b))645						} else {646							panic!("bad pow call");647						}648					}649					("std", "extVar") => {650						assert_eq!(args.len(), 1);651						if let Val::Str(a) = evaluate(context, &args[0].1)? {652							with_state(|s| s.0.ext_vars.borrow().get(&a).cloned()).ok_or_else(653								|| {654									create_error::<()>(crate::Error::UndefinedExternalVariable(a))655										.err()656										.unwrap()657								},658							)?659						} else {660							panic!("bad extVar call");661						}662					}663					(ns, name) => panic!("Intristic not found: {}.{}", ns, name),664				},665				Val::Func(f) => {666					let body = #[inline(always)]667					|| f.evaluate(context, args, *tailstrict);668					if *tailstrict {669						body()?670					} else {671						push(locexpr, "function call".to_owned(), body)?672					}673				}674				_ => panic!("{:?} is not a function", value),675			}676		}677		Function(params, body) => evaluate_method(context, params.clone(), body.clone()),678		AssertExpr(AssertStmt(value, msg), returned) => {679			let assertion_result = push(value.clone(), "assertion condition".to_owned(), || {680				evaluate(context.clone(), &value)?681					.try_cast_bool("assertion condition should be boolean")682			})?;683			if assertion_result {684				push(685					returned.clone(),686					"assert 'return' branch".to_owned(),687					|| evaluate(context, returned),688				)?689			} else if let Some(msg) = msg {690				panic!(691					"assertion failed ({:?}): {}",692					value,693					evaluate(context, msg)?.try_cast_str("assertion message should be string")?694				);695			} else {696				panic!("assertion failed ({:?}): no message", value);697			}698		}699		Error(e) => create_error(crate::Error::RuntimeError(700			evaluate(context, e)?.try_cast_str("error text should be string")?,701		))?,702		IfElse {703			cond,704			cond_then,705			cond_else,706		} => {707			let condition_result = push(cond.0.clone(), "if condition".to_owned(), || {708				evaluate(context.clone(), &cond.0)?.try_cast_bool("if condition should be boolean")709			})?;710			if condition_result {711				push(712					cond_then.clone(),713					"if condition 'then' branch".to_owned(),714					|| evaluate(context, cond_then),715				)?716			} else {717				match cond_else {718					Some(v) => evaluate(context, v)?,719					None => Val::Null,720				}721			}722		}723		Import(path) => {724			let mut lib_path = loc725				.clone()726				.expect("imports can't be used without loc_data")727				.0728				.clone();729			lib_path.pop();730			lib_path.push(path);731			with_state(|s| s.import_file(&lib_path))?732		}733		_ => panic!(734			"evaluation not implemented: {:?}",735			LocExpr(expr.clone(), loc.clone())736		),737	})738}