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

difftreelog

feat(evaluator) add importStr

Лач2020-06-14parent: #d84b1e9.patch.diff
in: master

2 files changed

modifiedcrates/jsonnet-evaluator/src/evaluate.rsdiffbeforeafterboth
before · crates/jsonnet-evaluator/src/evaluate.rs
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(s), o) => Val::Str(format!("{}{}", s, o.clone().into_json(0)?)),85		(o, Val::Str(s)) => Val::Str(format!("{}{}", o.clone().into_json(0)?, s)),8687		(Val::Obj(v1), Val::Obj(v2)) => Val::Obj(v2.with_super(v1.clone())),88		(Val::Arr(a), Val::Arr(b)) => Val::Arr([&a[..], &b[..]].concat()),89		(Val::Num(v1), Val::Num(v2)) => Val::Num(v1 + v2),90		_ => panic!("can't add: {:?} and {:?}", a, b),91	})92}9394pub fn evaluate_binary_op_special(95	context: Context,96	a: &LocExpr,97	op: BinaryOpType,98	b: &LocExpr,99) -> Result<Val> {100	Ok(101		match (evaluate(context.clone(), &a)?.unwrap_if_lazy()?, op, b) {102			(Val::Bool(true), BinaryOpType::Or, _o) => Val::Bool(true),103			(Val::Bool(false), BinaryOpType::And, _o) => Val::Bool(false),104			(a, op, eb) => {105				evaluate_binary_op_normal(&a, op, &evaluate(context, eb)?.unwrap_if_lazy()?)?106			}107		},108	)109}110111pub fn evaluate_binary_op_normal(a: &Val, op: BinaryOpType, b: &Val) -> Result<Val> {112	Ok(match (a, op, b) {113		(a, BinaryOpType::Add, b) => evaluate_add_op(a, b)?,114115		(Val::Str(v1), BinaryOpType::Mul, Val::Num(v2)) => Val::Str(v1.repeat(*v2 as usize)),116117		// Bool X Bool118		(Val::Bool(a), BinaryOpType::And, Val::Bool(b)) => Val::Bool(*a && *b),119		(Val::Bool(a), BinaryOpType::Or, Val::Bool(b)) => Val::Bool(*a || *b),120121		// Str X Str122		(Val::Str(v1), BinaryOpType::Lt, Val::Str(v2)) => Val::Bool(v1 < v2),123		(Val::Str(v1), BinaryOpType::Gt, Val::Str(v2)) => Val::Bool(v1 > v2),124		(Val::Str(v1), BinaryOpType::Lte, Val::Str(v2)) => Val::Bool(v1 <= v2),125		(Val::Str(v1), BinaryOpType::Gte, Val::Str(v2)) => Val::Bool(v1 >= v2),126127		// Num X Num128		(Val::Num(v1), BinaryOpType::Mul, Val::Num(v2)) => Val::Num(v1 * v2),129		(Val::Num(v1), BinaryOpType::Div, Val::Num(v2)) => {130			if *v2 <= f64::EPSILON {131				create_error(crate::Error::DivisionByZero)?132			}133			Val::Num(v1 / v2)134		}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);165166#[inline(always)]167pub fn evaluate_comp<T>(168	context: Context,169	value: &impl Fn(Context) -> Result<T>,170	specs: &[CompSpec],171) -> Result<Option<Vec<T>>> {172	Ok(match specs.get(0) {173		None => Some(vec![value(context)?]),174		Some(CompSpec::IfSpec(IfSpecData(cond))) => {175			if evaluate(context.clone(), &cond)?.try_cast_bool("if spec")? {176				evaluate_comp(context, value, &specs[1..])?177			} else {178				None179			}180		}181		Some(CompSpec::ForSpec(ForSpecData(var, expr))) => {182			match evaluate(context.clone(), &expr)?.unwrap_if_lazy()? {183				Val::Arr(list) => {184					let mut out = Vec::new();185					for item in list {186						let item = item.clone().unwrap_if_lazy()?;187						out.push(evaluate_comp(188							context.with_var(var.clone(), item)?,189							value,190							&specs[1..],191						)?);192					}193					Some(out.into_iter().flatten().flatten().collect())194				}195				_ => panic!("for expression evaluated to non-iterable value"),196			}197		}198	})199}200201// TODO: Asserts202pub fn evaluate_object(context: Context, object: ObjBody) -> Result<ObjValue> {203	Ok(match object {204		ObjBody::MemberList(members) => {205			let new_bindings = FutureNewBindings::new();206			let future_this = FutureObjValue::new();207			let context_creator = context_creator!(208				closure!(clone context, clone new_bindings, |this: Option<ObjValue>, super_obj: Option<ObjValue>| {209					Ok(context.clone().extend_unbound(210						new_bindings.clone().unwrap(),211						context.clone().dollar().clone().or_else(||this.clone()),212						Some(this.unwrap()),213						super_obj214					)?)215				})216			);217			{218				let mut bindings: HashMap<String, LazyBinding> = HashMap::new();219				for (n, b) in members220					.iter()221					.filter_map(|m| match m {222						Member::BindStmt(b) => Some(b.clone()),223						_ => None,224					})225					.map(|b| evaluate_binding(&b, context_creator.clone()))226				{227					bindings.insert(n, b);228				}229				new_bindings.fill(bindings);230			}231232			let mut new_members = BTreeMap::new();233			for member in members.into_iter() {234				match member {235					Member::Field(FieldMember {236						name,237						plus,238						params: None,239						visibility,240						value,241					}) => {242						let name = evaluate_field_name(context.clone(), &name)?;243						if name.is_none() {244							continue;245						}246						let name = name.unwrap();247						new_members.insert(248							name.clone(),249							ObjMember {250								add: plus,251								visibility: visibility.clone(),252								invoke: LazyBinding::Bindable(Rc::new(253									closure!(clone name, clone value, clone context_creator, |this, super_obj| {254										Ok(LazyVal::new_resolved(push(value.clone(), "object ".to_owned()+&name+" field", ||{255											let context = context_creator.0(this, super_obj)?;256											evaluate(257												context,258												&value,259											)?.unwrap_if_lazy()260										})?))261									}),262								)),263							},264						);265					}266					Member::Field(FieldMember {267						name,268						params: Some(params),269						value,270						..271					}) => {272						let name = evaluate_field_name(context.clone(), &name)?;273						if name.is_none() {274							continue;275						}276						let name = name.unwrap();277						new_members.insert(278							name,279							ObjMember {280								add: false,281								visibility: Visibility::Hidden,282								invoke: LazyBinding::Bindable(Rc::new(283									closure!(clone value, clone context_creator, |this, super_obj| {284										// TODO: Assert285										Ok(LazyVal::new_resolved(evaluate_method(286											context_creator.0(this, super_obj)?,287											params.clone(),288											value.clone(),289										)))290									}),291								)),292							},293						);294					}295					Member::BindStmt(_) => {}296					Member::AssertStmt(_) => {}297				}298			}299			future_this.fill(ObjValue::new(None, Rc::new(new_members)))300		}301		ObjBody::ObjComp {302			pre_locals,303			key,304			value,305			post_locals,306			compspecs,307		} => {308			let future_this = FutureObjValue::new();309			let mut new_members = BTreeMap::new();310			for (k, v) in evaluate_comp(311				context.clone(),312				&|ctx| {313					let new_bindings = FutureNewBindings::new();314					let context_creator = context_creator!(315						closure!(clone context, clone new_bindings, |this: Option<ObjValue>, super_obj: Option<ObjValue>| {316							Ok(context.clone().extend_unbound(317								new_bindings.clone().unwrap(),318								context.clone().dollar().clone().or_else(||this.clone()),319								None,320								super_obj321							)?)322						})323					);324					let mut bindings: HashMap<String, LazyBinding> = HashMap::new();325					for (n, b) in pre_locals326						.iter()327						.chain(post_locals.iter())328						.map(|b| evaluate_binding(b, context_creator.clone()))329					{330						bindings.insert(n, b);331					}332					let bindings = new_bindings.fill(bindings);333					let ctx = ctx.extend_unbound(bindings, None, None, None)?;334					let key = evaluate(ctx.clone(), &key)?;335					let value = LazyBinding::Bindable(Rc::new(336						closure!(clone ctx, clone value, |this, _super_obj| {337							Ok(LazyVal::new_resolved(evaluate(ctx.extend(HashMap::new(), None, this, None)?, &value)?))338						}),339					));340341					Ok((key, value))342				},343				&compspecs,344			)?345			.unwrap()346			{347				match k {348					Val::Null => {}349					Val::Str(n) => {350						new_members.insert(351							n,352							ObjMember {353								add: false,354								visibility: Visibility::Normal,355								invoke: v,356							},357						);358					}359					v => create_error(Error::FieldMustBeStringGot(v.value_type()?))?,360				}361			}362363			future_this.fill(ObjValue::new(None, Rc::new(new_members)))364		}365	})366}367368#[inline(always)]369pub fn evaluate(context: Context, expr: &LocExpr) -> Result<Val> {370	use Expr::*;371	let locexpr = expr.clone();372	let LocExpr(expr, loc) = expr;373	Ok(match &**expr {374		Literal(LiteralType::This) => Val::Obj(375			context376				.this()377				.clone()378				.unwrap_or_else(|| panic!("this not found")),379		),380		Literal(LiteralType::Dollar) => Val::Obj(381			context382				.dollar()383				.clone()384				.unwrap_or_else(|| panic!("dollar not found")),385		),386		Literal(LiteralType::True) => Val::Bool(true),387		Literal(LiteralType::False) => Val::Bool(false),388		Literal(LiteralType::Null) => Val::Null,389		Parened(e) => evaluate(context, e)?,390		Str(v) => Val::Str(v.clone()),391		Num(v) => Val::Num(*v),392		BinaryOp(v1, o, v2) => evaluate_binary_op_special(context, &v1, *o, &v2)?,393		UnaryOp(o, v) => evaluate_unary_op(*o, &evaluate(context, v)?)?,394		Var(name) => push(locexpr, "var".to_owned(), || {395			Val::Lazy(context.binding(&name)).unwrap_if_lazy()396		})?,397		Index(LocExpr(v, _), index) if matches!(&**v, Expr::Literal(LiteralType::Super)) => {398			let name = evaluate(context.clone(), index)?.try_cast_str("object index")?;399			context400				.super_obj()401				.clone()402				.expect("no super found")403				.get_raw(&name, &context.this().clone().expect("no this found"))?404				.expect("value not found")405		}406		Index(value, index) => {407			match (408				evaluate(context.clone(), value)?.unwrap_if_lazy()?,409				evaluate(context, index)?,410			) {411				(Val::Obj(v), Val::Str(s)) => {412					if let Some(v) = v.get(&s)? {413						v.unwrap_if_lazy()?414					} else if let Some(Val::Str(n)) = v.get("__intristic_namespace__")? {415						Val::Intristic(n, s)416					} else {417						create_error(crate::Error::NoSuchField(s))?418					}419				}420				(Val::Obj(_), n) => create_error(crate::Error::ValueIndexMustBeTypeGot(421					ValType::Obj,422					ValType::Str,423					n.value_type()?,424				))?,425426				(Val::Arr(v), Val::Num(n)) => {427					if n.fract() > f64::EPSILON {428						create_error(crate::Error::FractionalIndex)?429					}430					v.get(n as usize)431						.unwrap_or_else(|| panic!("out of bounds"))432						.clone()433						.unwrap_if_lazy()?434				}435				(Val::Arr(_), Val::Str(n)) => {436					create_error(crate::Error::AttemptedIndexAnArrayWithString(n))?437				}438				(Val::Arr(_), n) => create_error(crate::Error::ValueIndexMustBeTypeGot(439					ValType::Arr,440					ValType::Num,441					n.value_type()?,442				))?,443444				(Val::Str(s), Val::Num(n)) => {445					Val::Str(s.chars().skip(n as usize).take(1).collect())446				}447				(Val::Str(_), n) => create_error(crate::Error::ValueIndexMustBeTypeGot(448					ValType::Str,449					ValType::Num,450					n.value_type()?,451				))?,452453				(v, _) => create_error(crate::Error::CantIndexInto(v.value_type()?))?,454			}455		}456		LocalExpr(bindings, returned) => {457			let mut new_bindings: HashMap<String, LazyBinding> = HashMap::new();458			let future_context = Context::new_future();459460			let context_creator = context_creator!(461				closure!(clone future_context, |_, _| Ok(future_context.clone().unwrap()))462			);463464			for (k, v) in bindings465				.iter()466				.map(|b| evaluate_binding(b, context_creator.clone()))467			{468				new_bindings.insert(k, v);469			}470471			let context = context472				.extend_unbound(new_bindings, None, None, None)?473				.into_future(future_context);474			evaluate(context, &returned.clone())?475		}476		Arr(items) => {477			let mut out = Vec::with_capacity(items.len());478			for item in items {479				out.push(Val::Lazy(lazy_val!(480					closure!(clone context, clone item, || {481						evaluate(context.clone(), &item)482					})483				)));484			}485			Val::Arr(out)486		}487		ArrComp(expr, compspecs) => Val::Arr(488			// First compspec should be forspec, so no "None" possible here489			evaluate_comp(context, &|ctx| evaluate(ctx, expr), compspecs)?.unwrap(),490		),491		Obj(body) => Val::Obj(evaluate_object(context, body.clone())?),492		ObjExtend(s, t) => evaluate_add_op(493			&evaluate(context.clone(), s)?,494			&Val::Obj(evaluate_object(context, t.clone())?),495		)?,496		Apply(value, args, tailstrict) => {497			let value = evaluate(context.clone(), value)?.unwrap_if_lazy()?;498			match value {499				Val::Intristic(ns, name) => match (&ns as &str, &name as &str) {500					// arr/string/function501					("std", "length") => {502						assert_eq!(args.len(), 1);503						let expr = &args.get(0).unwrap().1;504						match evaluate(context, expr)? {505							Val::Str(n) => Val::Num(n.chars().count() as f64),506							Val::Arr(i) => Val::Num(i.len() as f64),507							Val::Obj(o) => Val::Num(508								o.fields_visibility()509									.into_iter()510									.filter(|(_k, v)| *v)511									.count() as f64,512							),513							v => panic!("can't get length of {:?}", v),514						}515					}516					// any517					("std", "type") => {518						assert_eq!(args.len(), 1);519						let expr = &args.get(0).unwrap().1;520						Val::Str(evaluate(context, expr)?.value_type()?.name().to_owned())521					}522					// length, idx=>any523					("std", "makeArray") => {524						assert_eq!(args.len(), 2);525						if let (Val::Num(v), Val::Func(d)) = (526							evaluate(context.clone(), &args[0].1)?,527							evaluate(context, &args[1].1)?,528						) {529							assert!(v >= 0.0);530							let mut out = Vec::with_capacity(v as usize);531							for i in 0..v as usize {532								let call_ctx =533									Context::new().with_var("v".to_owned(), Val::Num(i as f64))?;534								out.push(d.evaluate(535									call_ctx,536									&ArgsDesc(vec![Arg(None, el!(Expr::Var("v".to_owned())))]),537									true,538								)?)539							}540							Val::Arr(out)541						} else {542							panic!("bad makeArray call");543						}544					}545					// string546					("std", "codepoint") => {547						assert_eq!(args.len(), 1);548						if let Val::Str(s) = evaluate(context, &args[0].1)? {549							assert!(550								s.chars().count() == 1,551								"std.codepoint should receive single char string"552							);553							Val::Num(s.chars().take(1).next().unwrap() as u32 as f64)554						} else {555							panic!("bad codepoint call");556						}557					}558					// object, includeHidden559					("std", "objectFieldsEx") => {560						assert_eq!(args.len(), 2);561						if let (Val::Obj(body), Val::Bool(include_hidden)) = (562							evaluate(context.clone(), &args[0].1)?,563							evaluate(context, &args[1].1)?,564						) {565							Val::Arr(566								body.fields_visibility()567									.into_iter()568									.filter(|(_k, v)| *v || include_hidden)569									.map(|(k, _v)| Val::Str(k))570									.collect(),571							)572						} else {573							panic!("bad objectFieldsEx call");574						}575					}576					// object, field, includeHidden577					("std", "objectHasEx") => {578						assert_eq!(args.len(), 3);579						if let (Val::Obj(body), Val::Str(name), Val::Bool(include_hidden)) = (580							evaluate(context.clone(), &args[0].1)?,581							evaluate(context.clone(), &args[1].1)?,582							evaluate(context, &args[2].1)?,583						) {584							Val::Bool(585								body.fields_visibility()586									.into_iter()587									.filter(|(_k, v)| *v || include_hidden)588									.any(|(k, _v)| k == name),589							)590						} else {591							panic!("bad objectHasEx call");592						}593					}594					("std", "primitiveEquals") => {595						assert_eq!(args.len(), 2);596						let (a, b) = (597							evaluate(context.clone(), &args[0].1)?,598							evaluate(context, &args[1].1)?,599						);600						Val::Bool(a == b)601					}602					("std", "modulo") => {603						assert_eq!(args.len(), 2);604						if let (Val::Num(a), Val::Num(b)) = (605							evaluate(context.clone(), &args[0].1)?,606							evaluate(context, &args[1].1)?,607						) {608							Val::Num(a % b)609						} else {610							panic!("bad modulo call");611						}612					}613					("std", "floor") => {614						assert_eq!(args.len(), 1);615						if let Val::Num(a) = evaluate(context, &args[0].1)? {616							Val::Num(a.floor())617						} else {618							panic!("bad floor call");619						}620					}621					("std", "trace") => {622						assert_eq!(args.len(), 2);623						if let (Val::Str(a), b) = (624							evaluate(context.clone(), &args[0].1)?,625							evaluate(context, &args[1].1)?,626						) {627							// TODO: Line numbers as in original jsonnet628							println!("TRACE: {}", a);629							b630						} else {631							panic!("bad trace call");632						}633					}634					("std", "pow") => {635						assert_eq!(args.len(), 2);636						if let (Val::Num(a), Val::Num(b)) = (637							evaluate(context.clone(), &args[0].1)?,638							evaluate(context, &args[1].1)?,639						) {640							Val::Num(a.powf(b))641						} else {642							panic!("bad pow call");643						}644					}645					("std", "extVar") => {646						assert_eq!(args.len(), 1);647						if let Val::Str(a) = evaluate(context, &args[0].1)? {648							with_state(|s| s.0.ext_vars.borrow().get(&a).cloned()).ok_or_else(649								|| {650									create_error::<()>(crate::Error::UndefinedExternalVariable(a))651										.err()652										.unwrap()653								},654							)?655						} else {656							panic!("bad extVar call");657						}658					}659					(ns, name) => panic!("Intristic not found: {}.{}", ns, name),660				},661				Val::Func(f) => {662					let body = #[inline(always)]663					|| f.evaluate(context, args, *tailstrict);664					if *tailstrict {665						body()?666					} else {667						push(locexpr, "function call".to_owned(), body)?668					}669				}670				_ => panic!("{:?} is not a function", value),671			}672		}673		Function(params, body) => evaluate_method(context, params.clone(), body.clone()),674		AssertExpr(AssertStmt(value, msg), returned) => {675			let assertion_result = push(value.clone(), "assertion condition".to_owned(), || {676				evaluate(context.clone(), &value)?677					.try_cast_bool("assertion condition should be boolean")678			})?;679			if assertion_result {680				push(681					returned.clone(),682					"assert 'return' branch".to_owned(),683					|| evaluate(context, returned),684				)?685			} else if let Some(msg) = msg {686				panic!(687					"assertion failed ({:?}): {}",688					value,689					evaluate(context, msg)?.try_cast_str("assertion message should be string")?690				);691			} else {692				panic!("assertion failed ({:?}): no message", value);693			}694		}695		Error(e) => create_error(crate::Error::RuntimeError(696			evaluate(context, e)?.try_cast_str("error text should be string")?,697		))?,698		IfElse {699			cond,700			cond_then,701			cond_else,702		} => {703			let condition_result = push(cond.0.clone(), "if condition".to_owned(), || {704				evaluate(context.clone(), &cond.0)?.try_cast_bool("if condition should be boolean")705			})?;706			if condition_result {707				push(708					cond_then.clone(),709					"if condition 'then' branch".to_owned(),710					|| evaluate(context, cond_then),711				)?712			} else {713				match cond_else {714					Some(v) => evaluate(context, v)?,715					None => Val::Null,716				}717			}718		}719		Import(path) => {720			let mut lib_path = loc721				.clone()722				.expect("imports can't be used without loc_data")723				.0724				.clone();725			lib_path.pop();726			lib_path.push(path);727			with_state(|s| s.import_file(&lib_path))?728		}729		_ => panic!(730			"evaluation not implemented: {:?}",731			LocExpr(expr.clone(), loc.clone())732		),733	})734}
modifiedcrates/jsonnet-evaluator/src/lib.rsdiffbeforeafterboth
--- a/crates/jsonnet-evaluator/src/lib.rs
+++ b/crates/jsonnet-evaluator/src/lib.rs
@@ -68,6 +68,7 @@
 	/// Contains file source codes and evaluated results for imports and pretty
 	/// printing stacktraces
 	files: RefCell<HashMap<PathBuf, FileData>>,
+	str_files: RefCell<HashMap<PathBuf, String>>,
 	globals: RefCell<HashMap<String, Val>>,
 
 	/// Values to use with std.extVar
@@ -177,6 +178,13 @@
 		}
 		self.evaluate_file_in_current_state(path)
 	}
+	pub(crate) fn import_file_str(&self, path: &PathBuf) -> Result<String> {
+		if !self.0.str_files.borrow().contains_key(path) {
+			let file_str = (self.0.settings.import_resolver)(path);
+			self.0.str_files.borrow_mut().insert(path.clone(), file_str);
+		}
+		Ok(self.0.str_files.borrow().get(path).cloned().unwrap())
+	}
 
 	pub fn parse_evaluate_raw(&self, code: &str) -> Result<Val> {
 		let parsed = parse(