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
after · 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	ValType,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(params) = &b.params {20		let params = params.clone();21		(22			b.name.clone(),23			LazyBinding::Bindable(Rc::new(move |this, super_obj| {24				Ok(lazy_val!(25					closure!(clone b, clone params, clone context_creator, || Ok(evaluate_method(26						context_creator.0(this.clone(), super_obj.clone())?,27						params.clone(),28						b.value.clone(),29					)))30				))31			})),32		)33	} else {34		(35			b.name.clone(),36			LazyBinding::Bindable(Rc::new(move |this, super_obj| {37				Ok(lazy_val!(closure!(clone context_creator, clone b, ||38					push(b.value.clone(), "thunk".to_owned(), ||{39						evaluate(40							context_creator.0(this.clone(), super_obj.clone())?,41							&b.value42						)43					})44				)))45			})),46		)47	}48}4950pub fn evaluate_method(ctx: Context, params: ParamsDesc, body: LocExpr) -> Val {51	Val::Func(FuncDesc { ctx, params, body })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(s), o) => Val::Str(format!("{}{}", s, o.clone().into_json(0)?)),86		(o, Val::Str(s)) => Val::Str(format!("{}{}", o.clone().into_json(0)?, s)),8788		(Val::Obj(v1), Val::Obj(v2)) => Val::Obj(v2.with_super(v1.clone())),89		(Val::Arr(a), Val::Arr(b)) => Val::Arr([&a[..], &b[..]].concat()),90		(Val::Num(v1), Val::Num(v2)) => Val::Num(v1 + v2),91		_ => panic!("can't add: {:?} and {:?}", a, b),92	})93}9495pub fn evaluate_binary_op_special(96	context: Context,97	a: &LocExpr,98	op: BinaryOpType,99	b: &LocExpr,100) -> Result<Val> {101	Ok(102		match (evaluate(context.clone(), &a)?.unwrap_if_lazy()?, op, b) {103			(Val::Bool(true), BinaryOpType::Or, _o) => Val::Bool(true),104			(Val::Bool(false), BinaryOpType::And, _o) => Val::Bool(false),105			(a, op, eb) => {106				evaluate_binary_op_normal(&a, op, &evaluate(context, eb)?.unwrap_if_lazy()?)?107			}108		},109	)110}111112pub fn evaluate_binary_op_normal(a: &Val, op: BinaryOpType, b: &Val) -> Result<Val> {113	Ok(match (a, op, b) {114		(a, BinaryOpType::Add, b) => evaluate_add_op(a, b)?,115116		(Val::Str(v1), BinaryOpType::Mul, Val::Num(v2)) => Val::Str(v1.repeat(*v2 as usize)),117118		// Bool X Bool119		(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		// Str X Str123		(Val::Str(v1), BinaryOpType::Lt, Val::Str(v2)) => Val::Bool(v1 < v2),124		(Val::Str(v1), BinaryOpType::Gt, Val::Str(v2)) => Val::Bool(v1 > v2),125		(Val::Str(v1), BinaryOpType::Lte, Val::Str(v2)) => Val::Bool(v1 <= v2),126		(Val::Str(v1), BinaryOpType::Gte, Val::Str(v2)) => Val::Bool(v1 >= v2),127128		// Num X Num129		(Val::Num(v1), BinaryOpType::Mul, Val::Num(v2)) => Val::Num(v1 * v2),130		(Val::Num(v1), BinaryOpType::Div, Val::Num(v2)) => {131			if *v2 <= f64::EPSILON {132				create_error(crate::Error::DivisionByZero)?133			}134			Val::Num(v1 / v2)135		}136137		(Val::Num(v1), BinaryOpType::Sub, Val::Num(v2)) => Val::Num(v1 - v2),138139		(Val::Num(v1), BinaryOpType::Lt, Val::Num(v2)) => Val::Bool(v1 < v2),140		(Val::Num(v1), BinaryOpType::Gt, Val::Num(v2)) => Val::Bool(v1 > v2),141		(Val::Num(v1), BinaryOpType::Lte, Val::Num(v2)) => Val::Bool(v1 <= v2),142		(Val::Num(v1), BinaryOpType::Gte, Val::Num(v2)) => Val::Bool(v1 >= v2),143144		(Val::Num(v1), BinaryOpType::BitAnd, Val::Num(v2)) => {145			Val::Num(((*v1 as i32) & (*v2 as i32)) as f64)146		}147		(Val::Num(v1), BinaryOpType::BitOr, Val::Num(v2)) => {148			Val::Num(((*v1 as i32) | (*v2 as i32)) as f64)149		}150		(Val::Num(v1), BinaryOpType::BitXor, Val::Num(v2)) => {151			Val::Num(((*v1 as i32) ^ (*v2 as i32)) as f64)152		}153		(Val::Num(v1), BinaryOpType::Lhs, Val::Num(v2)) => {154			Val::Num(((*v1 as i32) << (*v2 as i32)) as f64)155		}156		(Val::Num(v1), BinaryOpType::Rhs, Val::Num(v2)) => {157			Val::Num(((*v1 as i32) >> (*v2 as i32)) as f64)158		}159160		_ => panic!("no rules for binary operation: {:?} {:?} {:?}", a, op, b),161	})162}163164future_wrapper!(HashMap<String, LazyBinding>, FutureNewBindings);165future_wrapper!(ObjValue, FutureObjValue);166167#[inline(always)]168pub fn evaluate_comp<T>(169	context: Context,170	value: &impl Fn(Context) -> Result<T>,171	specs: &[CompSpec],172) -> Result<Option<Vec<T>>> {173	Ok(match specs.get(0) {174		None => Some(vec![value(context)?]),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.into_iter().flatten().flatten().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, |this: Option<ObjValue>, super_obj: Option<ObjValue>| {210					Ok(context.clone().extend_unbound(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: LazyBinding::Bindable(Rc::new(254									closure!(clone name, clone value, clone context_creator, |this, super_obj| {255										Ok(LazyVal::new_resolved(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: LazyBinding::Bindable(Rc::new(284									closure!(clone value, clone context_creator, |this, super_obj| {285										// TODO: Assert286										Ok(LazyVal::new_resolved(evaluate_method(287											context_creator.0(this, super_obj)?,288											params.clone(),289											value.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		ObjBody::ObjComp {303			pre_locals,304			key,305			value,306			post_locals,307			compspecs,308		} => {309			let future_this = FutureObjValue::new();310			let mut new_members = BTreeMap::new();311			for (k, v) in evaluate_comp(312				context.clone(),313				&|ctx| {314					let new_bindings = FutureNewBindings::new();315					let context_creator = context_creator!(316						closure!(clone context, clone new_bindings, |this: Option<ObjValue>, super_obj: Option<ObjValue>| {317							Ok(context.clone().extend_unbound(318								new_bindings.clone().unwrap(),319								context.clone().dollar().clone().or_else(||this.clone()),320								None,321								super_obj322							)?)323						})324					);325					let mut bindings: HashMap<String, LazyBinding> = HashMap::new();326					for (n, b) in pre_locals327						.iter()328						.chain(post_locals.iter())329						.map(|b| evaluate_binding(b, context_creator.clone()))330					{331						bindings.insert(n, b);332					}333					let bindings = new_bindings.fill(bindings);334					let ctx = ctx.extend_unbound(bindings, None, None, None)?;335					let key = evaluate(ctx.clone(), &key)?;336					let value = LazyBinding::Bindable(Rc::new(337						closure!(clone ctx, clone value, |this, _super_obj| {338							Ok(LazyVal::new_resolved(evaluate(ctx.extend(HashMap::new(), None, this, None)?, &value)?))339						}),340					));341342					Ok((key, value))343				},344				&compspecs,345			)?346			.unwrap()347			{348				match k {349					Val::Null => {}350					Val::Str(n) => {351						new_members.insert(352							n,353							ObjMember {354								add: false,355								visibility: Visibility::Normal,356								invoke: v,357							},358						);359					}360					v => create_error(Error::FieldMustBeStringGot(v.value_type()?))?,361				}362			}363364			future_this.fill(ObjValue::new(None, Rc::new(new_members)))365		}366	})367}368369#[inline(always)]370pub fn evaluate(context: Context, expr: &LocExpr) -> Result<Val> {371	use Expr::*;372	let locexpr = expr.clone();373	let LocExpr(expr, loc) = expr;374	Ok(match &**expr {375		Literal(LiteralType::This) => Val::Obj(376			context377				.this()378				.clone()379				.unwrap_or_else(|| panic!("this not found")),380		),381		Literal(LiteralType::Dollar) => Val::Obj(382			context383				.dollar()384				.clone()385				.unwrap_or_else(|| panic!("dollar not found")),386		),387		Literal(LiteralType::True) => Val::Bool(true),388		Literal(LiteralType::False) => Val::Bool(false),389		Literal(LiteralType::Null) => Val::Null,390		Parened(e) => evaluate(context, e)?,391		Str(v) => Val::Str(v.clone()),392		Num(v) => Val::Num(*v),393		BinaryOp(v1, o, v2) => evaluate_binary_op_special(context, &v1, *o, &v2)?,394		UnaryOp(o, v) => evaluate_unary_op(*o, &evaluate(context, v)?)?,395		Var(name) => push(locexpr, "var".to_owned(), || {396			Val::Lazy(context.binding(&name)).unwrap_if_lazy()397		})?,398		Index(LocExpr(v, _), index) if matches!(&**v, Expr::Literal(LiteralType::Super)) => {399			let name = evaluate(context.clone(), index)?.try_cast_str("object index")?;400			context401				.super_obj()402				.clone()403				.expect("no super found")404				.get_raw(&name, &context.this().clone().expect("no this found"))?405				.expect("value not found")406		}407		Index(value, index) => {408			match (409				evaluate(context.clone(), value)?.unwrap_if_lazy()?,410				evaluate(context, index)?,411			) {412				(Val::Obj(v), Val::Str(s)) => {413					if let Some(v) = v.get(&s)? {414						v.unwrap_if_lazy()?415					} else if let Some(Val::Str(n)) = v.get("__intristic_namespace__")? {416						Val::Intristic(n, s)417					} else {418						create_error(crate::Error::NoSuchField(s))?419					}420				}421				(Val::Obj(_), n) => create_error(crate::Error::ValueIndexMustBeTypeGot(422					ValType::Obj,423					ValType::Str,424					n.value_type()?,425				))?,426427				(Val::Arr(v), Val::Num(n)) => {428					if n.fract() > f64::EPSILON {429						create_error(crate::Error::FractionalIndex)?430					}431					v.get(n as usize)432						.unwrap_or_else(|| panic!("out of bounds"))433						.clone()434						.unwrap_if_lazy()?435				}436				(Val::Arr(_), Val::Str(n)) => {437					create_error(crate::Error::AttemptedIndexAnArrayWithString(n))?438				}439				(Val::Arr(_), n) => create_error(crate::Error::ValueIndexMustBeTypeGot(440					ValType::Arr,441					ValType::Num,442					n.value_type()?,443				))?,444445				(Val::Str(s), Val::Num(n)) => {446					Val::Str(s.chars().skip(n as usize).take(1).collect())447				}448				(Val::Str(_), n) => create_error(crate::Error::ValueIndexMustBeTypeGot(449					ValType::Str,450					ValType::Num,451					n.value_type()?,452				))?,453454				(v, _) => create_error(crate::Error::CantIndexInto(v.value_type()?))?,455			}456		}457		LocalExpr(bindings, returned) => {458			let mut new_bindings: HashMap<String, LazyBinding> = HashMap::new();459			let future_context = Context::new_future();460461			let context_creator = context_creator!(462				closure!(clone future_context, |_, _| Ok(future_context.clone().unwrap()))463			);464465			for (k, v) in bindings466				.iter()467				.map(|b| evaluate_binding(b, context_creator.clone()))468			{469				new_bindings.insert(k, v);470			}471472			let context = context473				.extend_unbound(new_bindings, None, None, None)?474				.into_future(future_context);475			evaluate(context, &returned.clone())?476		}477		Arr(items) => {478			let mut out = Vec::with_capacity(items.len());479			for item in items {480				out.push(Val::Lazy(lazy_val!(481					closure!(clone context, clone item, || {482						evaluate(context.clone(), &item)483					})484				)));485			}486			Val::Arr(out)487		}488		ArrComp(expr, compspecs) => Val::Arr(489			// First compspec should be forspec, so no "None" possible here490			evaluate_comp(context, &|ctx| evaluate(ctx, expr), compspecs)?.unwrap(),491		),492		Obj(body) => Val::Obj(evaluate_object(context, body.clone())?),493		ObjExtend(s, t) => evaluate_add_op(494			&evaluate(context.clone(), s)?,495			&Val::Obj(evaluate_object(context, t.clone())?),496		)?,497		Apply(value, args, tailstrict) => {498			let value = evaluate(context.clone(), value)?.unwrap_if_lazy()?;499			match value {500				Val::Intristic(ns, name) => match (&ns as &str, &name as &str) {501					// arr/string/function502					("std", "length") => {503						assert_eq!(args.len(), 1);504						let expr = &args.get(0).unwrap().1;505						match evaluate(context, expr)? {506							Val::Str(n) => Val::Num(n.chars().count() as f64),507							Val::Arr(i) => Val::Num(i.len() as f64),508							Val::Obj(o) => Val::Num(509								o.fields_visibility()510									.into_iter()511									.filter(|(_k, v)| *v)512									.count() as f64,513							),514							v => panic!("can't get length of {:?}", v),515						}516					}517					// any518					("std", "type") => {519						assert_eq!(args.len(), 1);520						let expr = &args.get(0).unwrap().1;521						Val::Str(evaluate(context, expr)?.value_type()?.name().to_owned())522					}523					// length, idx=>any524					("std", "makeArray") => {525						assert_eq!(args.len(), 2);526						if let (Val::Num(v), Val::Func(d)) = (527							evaluate(context.clone(), &args[0].1)?,528							evaluate(context, &args[1].1)?,529						) {530							assert!(v >= 0.0);531							let mut out = Vec::with_capacity(v as usize);532							for i in 0..v as usize {533								let call_ctx =534									Context::new().with_var("v".to_owned(), Val::Num(i as f64))?;535								out.push(d.evaluate(536									call_ctx,537									&ArgsDesc(vec![Arg(None, el!(Expr::Var("v".to_owned())))]),538									true,539								)?)540							}541							Val::Arr(out)542						} else {543							panic!("bad makeArray call");544						}545					}546					// string547					("std", "codepoint") => {548						assert_eq!(args.len(), 1);549						if let Val::Str(s) = evaluate(context, &args[0].1)? {550							assert!(551								s.chars().count() == 1,552								"std.codepoint should receive single char string"553							);554							Val::Num(s.chars().take(1).next().unwrap() as u32 as f64)555						} else {556							panic!("bad codepoint call");557						}558					}559					// object, includeHidden560					("std", "objectFieldsEx") => {561						assert_eq!(args.len(), 2);562						if let (Val::Obj(body), Val::Bool(include_hidden)) = (563							evaluate(context.clone(), &args[0].1)?,564							evaluate(context, &args[1].1)?,565						) {566							Val::Arr(567								body.fields_visibility()568									.into_iter()569									.filter(|(_k, v)| *v || include_hidden)570									.map(|(k, _v)| Val::Str(k))571									.collect(),572							)573						} else {574							panic!("bad objectFieldsEx call");575						}576					}577					// object, field, includeHidden578					("std", "objectHasEx") => {579						assert_eq!(args.len(), 3);580						if let (Val::Obj(body), Val::Str(name), Val::Bool(include_hidden)) = (581							evaluate(context.clone(), &args[0].1)?,582							evaluate(context.clone(), &args[1].1)?,583							evaluate(context, &args[2].1)?,584						) {585							Val::Bool(586								body.fields_visibility()587									.into_iter()588									.filter(|(_k, v)| *v || include_hidden)589									.any(|(k, _v)| k == name),590							)591						} else {592							panic!("bad objectHasEx call");593						}594					}595					("std", "primitiveEquals") => {596						assert_eq!(args.len(), 2);597						let (a, b) = (598							evaluate(context.clone(), &args[0].1)?,599							evaluate(context, &args[1].1)?,600						);601						Val::Bool(a == b)602					}603					("std", "modulo") => {604						assert_eq!(args.len(), 2);605						if let (Val::Num(a), Val::Num(b)) = (606							evaluate(context.clone(), &args[0].1)?,607							evaluate(context, &args[1].1)?,608						) {609							Val::Num(a % b)610						} else {611							panic!("bad modulo call");612						}613					}614					("std", "floor") => {615						assert_eq!(args.len(), 1);616						if let Val::Num(a) = evaluate(context, &args[0].1)? {617							Val::Num(a.floor())618						} else {619							panic!("bad floor call");620						}621					}622					("std", "trace") => {623						assert_eq!(args.len(), 2);624						if let (Val::Str(a), b) = (625							evaluate(context.clone(), &args[0].1)?,626							evaluate(context, &args[1].1)?,627						) {628							// TODO: Line numbers as in original jsonnet629							println!("TRACE: {}", a);630							b631						} else {632							panic!("bad trace call");633						}634					}635					("std", "pow") => {636						assert_eq!(args.len(), 2);637						if let (Val::Num(a), Val::Num(b)) = (638							evaluate(context.clone(), &args[0].1)?,639							evaluate(context, &args[1].1)?,640						) {641							Val::Num(a.powf(b))642						} else {643							panic!("bad pow call");644						}645					}646					("std", "extVar") => {647						assert_eq!(args.len(), 1);648						if let Val::Str(a) = evaluate(context, &args[0].1)? {649							with_state(|s| s.0.ext_vars.borrow().get(&a).cloned()).ok_or_else(650								|| {651									create_error::<()>(crate::Error::UndefinedExternalVariable(a))652										.err()653										.unwrap()654								},655							)?656						} else {657							panic!("bad extVar call");658						}659					}660					(ns, name) => panic!("Intristic not found: {}.{}", ns, name),661				},662				Val::Func(f) => {663					let body = #[inline(always)]664					|| f.evaluate(context, args, *tailstrict);665					if *tailstrict {666						body()?667					} else {668						push(locexpr, "function call".to_owned(), body)?669					}670				}671				_ => panic!("{:?} is not a function", value),672			}673		}674		Function(params, body) => evaluate_method(context, params.clone(), body.clone()),675		AssertExpr(AssertStmt(value, msg), returned) => {676			let assertion_result = push(value.clone(), "assertion condition".to_owned(), || {677				evaluate(context.clone(), &value)?678					.try_cast_bool("assertion condition should be boolean")679			})?;680			if assertion_result {681				push(682					returned.clone(),683					"assert 'return' branch".to_owned(),684					|| evaluate(context, returned),685				)?686			} else if let Some(msg) = msg {687				panic!(688					"assertion failed ({:?}): {}",689					value,690					evaluate(context, msg)?.try_cast_str("assertion message should be string")?691				);692			} else {693				panic!("assertion failed ({:?}): no message", value);694			}695		}696		Error(e) => create_error(crate::Error::RuntimeError(697			evaluate(context, e)?.try_cast_str("error text should be string")?,698		))?,699		IfElse {700			cond,701			cond_then,702			cond_else,703		} => {704			let condition_result = push(cond.0.clone(), "if condition".to_owned(), || {705				evaluate(context.clone(), &cond.0)?.try_cast_bool("if condition should be boolean")706			})?;707			if condition_result {708				push(709					cond_then.clone(),710					"if condition 'then' branch".to_owned(),711					|| evaluate(context, cond_then),712				)?713			} else {714				match cond_else {715					Some(v) => evaluate(context, v)?,716					None => Val::Null,717				}718			}719		}720		Import(path) => {721			let mut lib_path = loc722				.clone()723				.expect("imports can't be used without loc_data")724				.0725				.clone();726			lib_path.pop();727			lib_path.push(path);728			with_state(|s| s.import_file(&lib_path))?729		}730		ImportStr(path) => {731			let mut file_path = loc732				.clone()733				.expect("imports can't be used without loc_data")734				.0735				.clone();736			file_path.pop();737			file_path.push(path);738			Val::Str(with_state(|s| s.import_file_str(&file_path))?)739		}740	})741}
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(