git.delta.rocks / jrsonnet / refs/commits / 765a4d39e770

difftreelog

source

crates/jrsonnet-evaluator/src/evaluate.rs23.1 KiBsourcehistory
1use crate::{2	equals, error::Error::*, push, throw, with_state, ArrValue, Bindable, Context, ContextCreator,3	FuncDesc, FuncVal, FutureWrapper, LazyBinding, LazyVal, LazyValValue, ObjMember, ObjValue,4	ObjectAssertion, Result, Val,5};6use gc::{custom_trace, Finalize, Gc, Trace};7use jrsonnet_interner::IStr;8use jrsonnet_parser::{9	ArgsDesc, AssertStmt, BinaryOpType, BindSpec, CompSpec, Expr, ExprLocation, FieldMember,10	ForSpecData, IfSpecData, LiteralType, LocExpr, Member, ObjBody, ParamsDesc, UnaryOpType,11	Visibility,12};13use jrsonnet_types::ValType;14use rustc_hash::{FxHashMap, FxHasher};15use std::{collections::HashMap, hash::BuildHasherDefault, rc::Rc};1617pub fn evaluate_binding_in_future(18	b: &BindSpec,19	context_creator: FutureWrapper<Context>,20) -> LazyVal {21	let b = b.clone();22	if let Some(params) = &b.params {23		let params = params.clone();2425		struct LazyMethodBinding {26			context_creator: FutureWrapper<Context>,27			name: IStr,28			params: ParamsDesc,29			value: LocExpr,30		}31		impl Finalize for LazyMethodBinding {}32		unsafe impl Trace for LazyMethodBinding {33			custom_trace!(this, {34				mark(&this.context_creator);35				mark(&this.name);36				mark(&this.params);37				mark(&this.value);38			});39		}40		impl LazyValValue for LazyMethodBinding {41			fn get(self: Box<Self>) -> Result<Val> {42				Ok(evaluate_method(43					self.context_creator.unwrap(),44					self.name,45					self.params,46					self.value,47				))48			}49		}5051		LazyVal::new(Box::new(LazyMethodBinding {52			context_creator,53			name: b.name.clone(),54			params,55			value: b.value.clone(),56		}))57	} else {58		struct LazyNamedBinding {59			context_creator: FutureWrapper<Context>,60			name: IStr,61			value: LocExpr,62		}63		impl Finalize for LazyNamedBinding {}64		unsafe impl Trace for LazyNamedBinding {65			custom_trace!(this, {66				mark(&this.context_creator);67				mark(&this.name);68				mark(&this.value);69			});70		}71		impl LazyValValue for LazyNamedBinding {72			fn get(self: Box<Self>) -> Result<Val> {73				evaluate_named(self.context_creator.unwrap(), &self.value, self.name)74			}75		}76		LazyVal::new(Box::new(LazyNamedBinding {77			context_creator,78			name: b.name.clone(),79			value: b.value,80		}))81	}82}8384pub fn evaluate_binding(b: &BindSpec, context_creator: ContextCreator) -> (IStr, LazyBinding) {85	let b = b.clone();86	if let Some(params) = &b.params {87		let params = params.clone();8889		struct BindableMethodLazyVal {90			this: Option<ObjValue>,91			super_obj: Option<ObjValue>,9293			context_creator: ContextCreator,94			name: IStr,95			params: ParamsDesc,96			value: LocExpr,97		}98		impl Finalize for BindableMethodLazyVal {}99		unsafe impl Trace for BindableMethodLazyVal {100			custom_trace!(this, {101				mark(&this.this);102				mark(&this.super_obj);103				mark(&this.context_creator);104				mark(&this.name);105				mark(&this.params);106				mark(&this.value);107			});108		}109		impl LazyValValue for BindableMethodLazyVal {110			fn get(self: Box<Self>) -> Result<Val> {111				Ok(evaluate_method(112					self.context_creator.create(self.this, self.super_obj)?,113					self.name,114					self.params,115					self.value,116				))117			}118		}119120		#[derive(Trace, Finalize)]121		struct BindableMethod {122			context_creator: ContextCreator,123			name: IStr,124			params: ParamsDesc,125			value: LocExpr,126		}127		impl Bindable for BindableMethod {128			fn bind(&self, this: Option<ObjValue>, super_obj: Option<ObjValue>) -> Result<LazyVal> {129				Ok(LazyVal::new(Box::new(BindableMethodLazyVal {130					this: this.clone(),131					super_obj: super_obj.clone(),132133					context_creator: self.context_creator.clone(),134					name: self.name.clone(),135					params: self.params.clone(),136					value: self.value.clone(),137				})))138			}139		}140141		(142			b.name.clone(),143			LazyBinding::Bindable(Gc::new(Box::new(BindableMethod {144				context_creator,145				name: b.name.clone(),146				params,147				value: b.value.clone(),148			}))),149		)150	} else {151		struct BindableNamedLazyVal {152			this: Option<ObjValue>,153			super_obj: Option<ObjValue>,154155			context_creator: ContextCreator,156			name: IStr,157			value: LocExpr,158		}159		impl Finalize for BindableNamedLazyVal {}160		unsafe impl Trace for BindableNamedLazyVal {161			custom_trace!(this, {162				mark(&this.this);163				mark(&this.super_obj);164				mark(&this.context_creator);165				mark(&this.name);166				mark(&this.value);167			});168		}169		impl LazyValValue for BindableNamedLazyVal {170			fn get(self: Box<Self>) -> Result<Val> {171				evaluate_named(172					self.context_creator.create(self.this, self.super_obj)?,173					&self.value,174					self.name,175				)176			}177		}178179		#[derive(Trace, Finalize)]180		struct BindableNamed {181			context_creator: ContextCreator,182			name: IStr,183			value: LocExpr,184		}185		impl Bindable for BindableNamed {186			fn bind(&self, this: Option<ObjValue>, super_obj: Option<ObjValue>) -> Result<LazyVal> {187				Ok(LazyVal::new(Box::new(BindableNamedLazyVal {188					this,189					super_obj,190191					context_creator: self.context_creator.clone(),192					name: self.name.clone(),193					value: self.value.clone(),194				})))195			}196		}197198		(199			b.name.clone(),200			LazyBinding::Bindable(Gc::new(Box::new(BindableNamed {201				context_creator,202				name: b.name.clone(),203				value: b.value.clone(),204			}))),205		)206	}207}208209pub fn evaluate_method(ctx: Context, name: IStr, params: ParamsDesc, body: LocExpr) -> Val {210	Val::Func(Gc::new(FuncVal::Normal(FuncDesc {211		name,212		ctx,213		params,214		body,215	})))216}217218pub fn evaluate_field_name(219	context: Context,220	field_name: &jrsonnet_parser::FieldName,221) -> Result<Option<IStr>> {222	Ok(match field_name {223		jrsonnet_parser::FieldName::Fixed(n) => Some(n.clone()),224		jrsonnet_parser::FieldName::Dyn(expr) => {225			let value = evaluate(context, expr)?;226			if matches!(value, Val::Null) {227				None228			} else {229				Some(value.try_cast_str("dynamic field name")?)230			}231		}232	})233}234235pub fn evaluate_unary_op(op: UnaryOpType, b: &Val) -> Result<Val> {236	Ok(match (op, b) {237		(UnaryOpType::Not, Val::Bool(v)) => Val::Bool(!v),238		(UnaryOpType::Minus, Val::Num(n)) => Val::Num(-*n),239		(UnaryOpType::BitNot, Val::Num(n)) => Val::Num(!(*n as i32) as f64),240		(op, o) => throw!(UnaryOperatorDoesNotOperateOnType(op, o.value_type())),241	})242}243244pub fn evaluate_add_op(a: &Val, b: &Val) -> Result<Val> {245	Ok(match (a, b) {246		(Val::DebugGcTraceValue(v1), Val::DebugGcTraceValue(v2)) => {247			evaluate_add_op(&v1.value, &v2.value)?248		}249		(Val::Str(v1), Val::Str(v2)) => Val::Str(((**v1).to_owned() + v2).into()),250251		// Can't use generic json serialization way, because it depends on number to string concatenation (std.jsonnet:890)252		(Val::Num(n), Val::Str(o)) => Val::Str(format!("{}{}", n, o).into()),253		(Val::Str(o), Val::Num(n)) => Val::Str(format!("{}{}", o, n).into()),254255		(Val::Str(s), o) => Val::Str(format!("{}{}", s, o.clone().to_string()?).into()),256		(o, Val::Str(s)) => Val::Str(format!("{}{}", o.clone().to_string()?, s).into()),257258		(Val::Obj(v1), Val::Obj(v2)) => Val::Obj(v2.extend_from(v1.clone())),259		(Val::Arr(a), Val::Arr(b)) => {260			let mut out = Vec::with_capacity(a.len() + b.len());261			out.extend(a.iter_lazy());262			out.extend(b.iter_lazy());263			Val::Arr(out.into())264		}265		(Val::Num(v1), Val::Num(v2)) => Val::new_checked_num(v1 + v2)?,266		_ => throw!(BinaryOperatorDoesNotOperateOnValues(267			BinaryOpType::Add,268			a.value_type(),269			b.value_type(),270		)),271	})272}273274pub fn evaluate_binary_op_special(275	context: Context,276	a: &LocExpr,277	op: BinaryOpType,278	b: &LocExpr,279) -> Result<Val> {280	Ok(match (evaluate(context.clone(), a)?, op, b) {281		(Val::Bool(true), BinaryOpType::Or, _o) => Val::Bool(true),282		(Val::Bool(false), BinaryOpType::And, _o) => Val::Bool(false),283		(a, op, eb) => evaluate_binary_op_normal(&a, op, &evaluate(context, eb)?)?,284	})285}286287pub fn evaluate_binary_op_normal(a: &Val, op: BinaryOpType, b: &Val) -> Result<Val> {288	Ok(match (a, op, b) {289		(a, BinaryOpType::Add, b) => evaluate_add_op(a, b)?,290291		(a, BinaryOpType::Eq, b) => Val::Bool(equals(a, b)?),292		(a, BinaryOpType::Neq, b) => Val::Bool(!equals(a, b)?),293294		(Val::Str(v1), BinaryOpType::Mul, Val::Num(v2)) => Val::Str(v1.repeat(*v2 as usize).into()),295296		// Bool X Bool297		(Val::Bool(a), BinaryOpType::And, Val::Bool(b)) => Val::Bool(*a && *b),298		(Val::Bool(a), BinaryOpType::Or, Val::Bool(b)) => Val::Bool(*a || *b),299300		// Str X Str301		(Val::Str(v1), BinaryOpType::Lt, Val::Str(v2)) => Val::Bool(v1 < v2),302		(Val::Str(v1), BinaryOpType::Gt, Val::Str(v2)) => Val::Bool(v1 > v2),303		(Val::Str(v1), BinaryOpType::Lte, Val::Str(v2)) => Val::Bool(v1 <= v2),304		(Val::Str(v1), BinaryOpType::Gte, Val::Str(v2)) => Val::Bool(v1 >= v2),305306		// Num X Num307		(Val::Num(v1), BinaryOpType::Mul, Val::Num(v2)) => Val::new_checked_num(v1 * v2)?,308		(Val::Num(v1), BinaryOpType::Div, Val::Num(v2)) => {309			if *v2 <= f64::EPSILON {310				throw!(DivisionByZero)311			}312			Val::new_checked_num(v1 / v2)?313		}314315		(Val::Num(v1), BinaryOpType::Sub, Val::Num(v2)) => Val::new_checked_num(v1 - v2)?,316317		(Val::Num(v1), BinaryOpType::Lt, Val::Num(v2)) => Val::Bool(v1 < v2),318		(Val::Num(v1), BinaryOpType::Gt, Val::Num(v2)) => Val::Bool(v1 > v2),319		(Val::Num(v1), BinaryOpType::Lte, Val::Num(v2)) => Val::Bool(v1 <= v2),320		(Val::Num(v1), BinaryOpType::Gte, Val::Num(v2)) => Val::Bool(v1 >= v2),321322		(Val::Num(v1), BinaryOpType::BitAnd, Val::Num(v2)) => {323			Val::Num(((*v1 as i32) & (*v2 as i32)) as f64)324		}325		(Val::Num(v1), BinaryOpType::BitOr, Val::Num(v2)) => {326			Val::Num(((*v1 as i32) | (*v2 as i32)) as f64)327		}328		(Val::Num(v1), BinaryOpType::BitXor, Val::Num(v2)) => {329			Val::Num(((*v1 as i32) ^ (*v2 as i32)) as f64)330		}331		(Val::Num(v1), BinaryOpType::Lhs, Val::Num(v2)) => {332			if *v2 < 0.0 {333				throw!(RuntimeError("shift by negative exponent".into()))334			}335			Val::Num(((*v1 as i32) << (*v2 as i32)) as f64)336		}337		(Val::Num(v1), BinaryOpType::Rhs, Val::Num(v2)) => {338			if *v2 < 0.0 {339				throw!(RuntimeError("shift by negative exponent".into()))340			}341			Val::Num(((*v1 as i32) >> (*v2 as i32)) as f64)342		}343344		_ => throw!(BinaryOperatorDoesNotOperateOnValues(345			op,346			a.value_type(),347			b.value_type(),348		)),349	})350}351352pub fn evaluate_comp(353	context: Context,354	specs: &[CompSpec],355	callback: &mut impl FnMut(Context) -> Result<()>,356) -> Result<()> {357	match specs.get(0) {358		None => callback(context)?,359		Some(CompSpec::IfSpec(IfSpecData(cond))) => {360			if evaluate(context.clone(), cond)?.try_cast_bool("if spec")? {361				evaluate_comp(context, &specs[1..], callback)?362			}363		}364		Some(CompSpec::ForSpec(ForSpecData(var, expr))) => match evaluate(context.clone(), expr)? {365			Val::Arr(list) => {366				for item in list.iter() {367					evaluate_comp(368						context.clone().with_var(var.clone(), item?.clone()),369						&specs[1..],370						callback,371					)?372				}373			}374			_ => throw!(InComprehensionCanOnlyIterateOverArray),375		},376	}377	Ok(())378}379380pub fn evaluate_member_list_object(context: Context, members: &[Member]) -> Result<ObjValue> {381	let new_bindings = FutureWrapper::new();382	let future_this = FutureWrapper::new();383	let context_creator = ContextCreator(context.clone(), new_bindings.clone());384	{385		let mut bindings: FxHashMap<IStr, LazyBinding> =386			FxHashMap::with_capacity_and_hasher(members.len(), BuildHasherDefault::default());387		for (n, b) in members388			.iter()389			.filter_map(|m| match m {390				Member::BindStmt(b) => Some(b.clone()),391				_ => None,392			})393			.map(|b| evaluate_binding(&b, context_creator.clone()))394		{395			bindings.insert(n, b);396		}397		new_bindings.fill(bindings);398	}399400	let mut new_members = FxHashMap::default();401	let mut assertions: Vec<Box<dyn ObjectAssertion>> = Vec::new();402	for member in members.iter() {403		match member {404			Member::Field(FieldMember {405				name,406				plus,407				params: None,408				visibility,409				value,410			}) => {411				let name = evaluate_field_name(context.clone(), name)?;412				if name.is_none() {413					continue;414				}415				let name = name.unwrap();416417				#[derive(Trace, Finalize)]418				struct ObjMemberBinding {419					context_creator: ContextCreator,420					value: LocExpr,421					name: IStr,422				}423				impl Bindable for ObjMemberBinding {424					fn bind(425						&self,426						this: Option<ObjValue>,427						super_obj: Option<ObjValue>,428					) -> Result<LazyVal> {429						Ok(LazyVal::new_resolved(evaluate_named(430							self.context_creator.create(this, super_obj)?,431							&self.value,432							self.name.clone(),433						)?))434					}435				}436				new_members.insert(437					name.clone(),438					ObjMember {439						add: *plus,440						visibility: *visibility,441						invoke: LazyBinding::Bindable(Gc::new(Box::new(ObjMemberBinding {442							context_creator: context_creator.clone(),443							value: value.clone(),444							name,445						}))),446						location: value.1.clone(),447					},448				);449			}450			Member::Field(FieldMember {451				name,452				params: Some(params),453				value,454				..455			}) => {456				let name = evaluate_field_name(context.clone(), name)?;457				if name.is_none() {458					continue;459				}460				let name = name.unwrap();461				#[derive(Trace, Finalize)]462				struct ObjMemberBinding {463					context_creator: ContextCreator,464					value: LocExpr,465					params: ParamsDesc,466					name: IStr,467				}468				impl Bindable for ObjMemberBinding {469					fn bind(470						&self,471						this: Option<ObjValue>,472						super_obj: Option<ObjValue>,473					) -> Result<LazyVal> {474						Ok(LazyVal::new_resolved(evaluate_method(475							self.context_creator.create(this, super_obj)?,476							self.name.clone(),477							self.params.clone(),478							self.value.clone(),479						)))480					}481				}482				new_members.insert(483					name.clone(),484					ObjMember {485						add: false,486						visibility: Visibility::Hidden,487						invoke: LazyBinding::Bindable(Gc::new(Box::new(ObjMemberBinding {488							context_creator: context_creator.clone(),489							value: value.clone(),490							params: params.clone(),491							name,492						}))),493						location: value.1.clone(),494					},495				);496			}497			Member::BindStmt(_) => {}498			Member::AssertStmt(stmt) => {499				struct ObjectAssert {500					context_creator: ContextCreator,501					assert: AssertStmt,502				}503				impl Finalize for ObjectAssert {}504				unsafe impl Trace for ObjectAssert {505					custom_trace!(this, {506						mark(&this.context_creator);507						mark(&this.assert);508					});509				}510				impl ObjectAssertion for ObjectAssert {511					fn run(512						&self,513						this: Option<ObjValue>,514						super_obj: Option<ObjValue>,515					) -> Result<()> {516						let ctx = self.context_creator.create(this, super_obj)?;517						evaluate_assert(ctx, &self.assert)518					}519				}520				assertions.push(Box::new(ObjectAssert {521					context_creator: context_creator.clone(),522					assert: stmt.clone(),523				}));524			}525		}526	}527	let this = ObjValue::new(None, Gc::new(new_members), Gc::new(assertions));528	future_this.fill(this.clone());529	Ok(this)530}531532pub fn evaluate_object(context: Context, object: &ObjBody) -> Result<ObjValue> {533	Ok(match object {534		ObjBody::MemberList(members) => evaluate_member_list_object(context, members)?,535		ObjBody::ObjComp(obj) => {536			let future_this = FutureWrapper::new();537			let mut new_members = FxHashMap::default();538			evaluate_comp(context.clone(), &obj.compspecs, &mut |ctx| {539				let new_bindings = FutureWrapper::new();540				let context_creator = ContextCreator(context.clone(), new_bindings.clone());541				let mut bindings: FxHashMap<IStr, LazyBinding> =542					FxHashMap::with_capacity_and_hasher(543						obj.pre_locals.len() + obj.post_locals.len(),544						BuildHasherDefault::default(),545					);546				for (n, b) in obj547					.pre_locals548					.iter()549					.chain(obj.post_locals.iter())550					.map(|b| evaluate_binding(b, context_creator.clone()))551				{552					bindings.insert(n, b);553				}554				new_bindings.fill(bindings.clone());555				let ctx = ctx.extend_unbound(bindings, None, None, None)?;556				let key = evaluate(ctx.clone(), &obj.key)?;557558				match key {559					Val::Null => {}560					Val::Str(n) => {561						#[derive(Trace, Finalize)]562						struct ObjCompBinding {563							context: Context,564							value: LocExpr,565						}566						impl Bindable for ObjCompBinding {567							fn bind(568								&self,569								this: Option<ObjValue>,570								_super_obj: Option<ObjValue>,571							) -> Result<LazyVal> {572								Ok(LazyVal::new_resolved(evaluate(573									self.context.clone().extend(574										FxHashMap::default(),575										None,576										this,577										None,578									),579									&self.value,580								)?))581							}582						}583						new_members.insert(584							n,585							ObjMember {586								add: false,587								visibility: Visibility::Normal,588								invoke: LazyBinding::Bindable(Gc::new(Box::new(ObjCompBinding {589									context: ctx.clone(),590									value: obj.value.clone(),591								}))),592								location: obj.value.1.clone(),593							},594						);595					}596					v => throw!(FieldMustBeStringGot(v.value_type())),597				}598599				Ok(())600			})?;601602			let this = ObjValue::new(None, Gc::new(new_members), Gc::new(Vec::new()));603			future_this.fill(this.clone());604			this605		}606	})607}608609pub fn evaluate_apply(610	context: Context,611	value: &LocExpr,612	args: &ArgsDesc,613	loc: Option<&ExprLocation>,614	tailstrict: bool,615) -> Result<Val> {616	let value = evaluate(context.clone(), value)?;617	Ok(match value {618		Val::Func(f) => {619			let body = || f.evaluate(context, loc, args, tailstrict);620			if tailstrict {621				body()?622			} else {623				push(loc, || format!("function <{}> call", f.name()), body)?624			}625		}626		v => throw!(OnlyFunctionsCanBeCalledGot(v.value_type())),627	})628}629630pub fn evaluate_assert(context: Context, assertion: &AssertStmt) -> Result<()> {631	let value = &assertion.0;632	let msg = &assertion.1;633	let assertion_result = push(634		value.1.as_ref(),635		|| "assertion condition".to_owned(),636		|| {637			evaluate(context.clone(), value)?638				.try_cast_bool("assertion condition should be of type `boolean`")639		},640	)?;641	if !assertion_result {642		push(643			value.1.as_ref(),644			|| "assertion failure".to_owned(),645			|| {646				if let Some(msg) = msg {647					throw!(AssertionFailed(evaluate(context, msg)?.to_string()?));648				} else {649					throw!(AssertionFailed(Val::Null.to_string()?));650				}651			},652		)?653	}654	Ok(())655}656657pub fn evaluate_named(context: Context, lexpr: &LocExpr, name: IStr) -> Result<Val> {658	use Expr::*;659	let LocExpr(expr, _loc) = lexpr;660	Ok(match &**expr {661		Function(params, body) => evaluate_method(context, name, params.clone(), body.clone()),662		_ => evaluate(context, lexpr)?,663	})664}665666pub fn evaluate(context: Context, expr: &LocExpr) -> Result<Val> {667	use Expr::*;668	let LocExpr(expr, loc) = expr;669	Ok(match &**expr {670		Literal(LiteralType::This) => {671			Val::Obj(context.this().clone().ok_or(CantUseSelfOutsideOfObject)?)672		}673		Literal(LiteralType::Super) => Val::Obj(674			context675				.super_obj()676				.clone()677				.ok_or(NoSuperFound)?678				.with_this(context.this().clone().unwrap()),679		),680		Literal(LiteralType::Dollar) => {681			Val::Obj(context.dollar().clone().ok_or(NoTopLevelObjectFound)?)682		}683		Literal(LiteralType::True) => Val::Bool(true),684		Literal(LiteralType::False) => Val::Bool(false),685		Literal(LiteralType::Null) => Val::Null,686		Parened(e) => evaluate(context, e)?,687		Str(v) => Val::Str(v.clone()),688		Num(v) => Val::new_checked_num(*v)?,689		BinaryOp(v1, o, v2) => evaluate_binary_op_special(context, v1, *o, v2)?,690		UnaryOp(o, v) => evaluate_unary_op(*o, &evaluate(context, v)?)?,691		Var(name) => push(692			loc.as_ref(),693			|| format!("variable <{}>", name),694			|| context.binding(name.clone())?.evaluate(),695		)?,696		Index(value, index) => {697			match (evaluate(context.clone(), value)?, evaluate(context, index)?) {698				(Val::Obj(v), Val::Str(s)) => {699					let sn = s.clone();700					push(701						loc.as_ref(),702						|| format!("field <{}> access", sn),703						|| {704							if let Some(v) = v.get(s.clone())? {705								Ok(v)706							} else if v.get("__intrinsic_namespace__".into())?.is_some() {707								Ok(Val::Func(Gc::new(FuncVal::Intrinsic(s))))708							} else {709								throw!(NoSuchField(s))710							}711						},712					)?713				}714				(Val::Obj(_), n) => throw!(ValueIndexMustBeTypeGot(715					ValType::Obj,716					ValType::Str,717					n.value_type(),718				)),719720				(Val::Arr(v), Val::Num(n)) => {721					if n.fract() > f64::EPSILON {722						throw!(FractionalIndex)723					}724					v.get(n as usize)?725						.ok_or_else(|| ArrayBoundsError(n as usize, v.len()))?726				}727				(Val::Arr(_), Val::Str(n)) => throw!(AttemptedIndexAnArrayWithString(n)),728				(Val::Arr(_), n) => throw!(ValueIndexMustBeTypeGot(729					ValType::Arr,730					ValType::Num,731					n.value_type(),732				)),733734				(Val::Str(s), Val::Num(n)) => Val::Str(735					s.chars()736						.skip(n as usize)737						.take(1)738						.collect::<String>()739						.into(),740				),741				(Val::Str(_), n) => throw!(ValueIndexMustBeTypeGot(742					ValType::Str,743					ValType::Num,744					n.value_type(),745				)),746747				(v, _) => throw!(CantIndexInto(v.value_type())),748			}749		}750		LocalExpr(bindings, returned) => {751			let mut new_bindings: FxHashMap<IStr, LazyVal> = HashMap::with_capacity_and_hasher(752				bindings.len(),753				BuildHasherDefault::<FxHasher>::default(),754			);755			let future_context = Context::new_future();756			for b in bindings {757				new_bindings.insert(758					b.name.clone(),759					evaluate_binding_in_future(b, future_context.clone()),760				);761			}762			let context = context763				.extend_bound(new_bindings)764				.into_future(future_context);765			evaluate(context, &returned.clone())?766		}767		Arr(items) => {768			let mut out = Vec::with_capacity(items.len());769			for item in items {770				// TODO: Implement ArrValue::Lazy with same context for every element?771				struct ArrayElement {772					context: Context,773					item: LocExpr,774				}775				impl Finalize for ArrayElement {}776				unsafe impl Trace for ArrayElement {777					custom_trace!(this, {778						mark(&this.context);779						mark(&this.item);780					});781				}782				impl LazyValValue for ArrayElement {783					fn get(self: Box<Self>) -> Result<Val> {784						evaluate(self.context, &self.item)785					}786				}787				out.push(LazyVal::new(Box::new(ArrayElement {788					context: context.clone(),789					item: item.clone(),790				})));791			}792			Val::Arr(out.into())793		}794		ArrComp(expr, comp_specs) => {795			let mut out = Vec::new();796			evaluate_comp(context, comp_specs, &mut |ctx| {797				out.push(evaluate(ctx, expr)?);798				Ok(())799			})?;800			Val::Arr(ArrValue::Eager(Gc::new(out)))801		}802		Obj(body) => Val::Obj(evaluate_object(context, body)?),803		ObjExtend(s, t) => evaluate_add_op(804			&evaluate(context.clone(), s)?,805			&Val::Obj(evaluate_object(context, t)?),806		)?,807		Apply(value, args, tailstrict) => {808			evaluate_apply(context, value, args, loc.as_ref(), *tailstrict)?809		}810		Function(params, body) => {811			evaluate_method(context, "anonymous".into(), params.clone(), body.clone())812		}813		Intrinsic(name) => Val::Func(Gc::new(FuncVal::Intrinsic(name.clone()))),814		AssertExpr(assert, returned) => {815			evaluate_assert(context.clone(), assert)?;816			evaluate(context, returned)?817		}818		ErrorStmt(e) => push(819			loc.as_ref(),820			|| "error statement".to_owned(),821			|| {822				throw!(RuntimeError(823					evaluate(context, e)?.try_cast_str("error text should be of type `string`")?,824				))825			},826		)?,827		IfElse {828			cond,829			cond_then,830			cond_else,831		} => {832			if push(833				loc.as_ref(),834				|| "if condition".to_owned(),835				|| evaluate(context.clone(), &cond.0)?.try_cast_bool("in if condition"),836			)? {837				evaluate(context, cond_then)?838			} else {839				match cond_else {840					Some(v) => evaluate(context, v)?,841					None => Val::Null,842				}843			}844		}845		Import(path) => {846			let mut tmp = loc847				.clone()848				.expect("imports cannot be used without loc_data")849				.0;850			let import_location = Rc::make_mut(&mut tmp);851			import_location.pop();852			push(853				loc.as_ref(),854				|| format!("import {:?}", path),855				|| with_state(|s| s.import_file(import_location, path)),856			)?857		}858		ImportStr(path) => {859			let mut tmp = loc860				.clone()861				.expect("imports cannot be used without loc_data")862				.0;863			let import_location = Rc::make_mut(&mut tmp);864			import_location.pop();865			Val::Str(with_state(|s| s.import_file_str(import_location, path))?)866		}867	})868}