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

difftreelog

refactor split evaluation code

Yaroslav Bolyukin2021-07-04parent: #8d08861.patch.diff
in: master

5 files changed

deletedcrates/jrsonnet-evaluator/src/evaluate.rsdiffbeforeafterboth
--- a/crates/jrsonnet-evaluator/src/evaluate.rs
+++ /dev/null
@@ -1,830 +0,0 @@
-use crate::{
-	equals, error::Error::*, push, throw, with_state, ArrValue, Bindable, Context, ContextCreator,
-	FuncDesc, FuncVal, FutureWrapper, LazyBinding, LazyVal, LazyValValue, ObjMember, ObjValue,
-	ObjectAssertion, Result, Val,
-};
-use jrsonnet_gc::{Gc, Trace};
-use jrsonnet_interner::IStr;
-use jrsonnet_parser::{
-	ArgsDesc, AssertStmt, BinaryOpType, BindSpec, CompSpec, Expr, ExprLocation, FieldMember,
-	ForSpecData, IfSpecData, LiteralType, LocExpr, Member, ObjBody, ParamsDesc, UnaryOpType,
-	Visibility,
-};
-use jrsonnet_types::ValType;
-use rustc_hash::{FxHashMap, FxHasher};
-use std::{collections::HashMap, hash::BuildHasherDefault};
-
-pub fn evaluate_binding_in_future(
-	b: &BindSpec,
-	context_creator: FutureWrapper<Context>,
-) -> LazyVal {
-	let b = b.clone();
-	if let Some(params) = &b.params {
-		let params = params.clone();
-
-		#[derive(Trace)]
-		#[trivially_drop]
-		struct LazyMethodBinding {
-			context_creator: FutureWrapper<Context>,
-			name: IStr,
-			params: ParamsDesc,
-			value: LocExpr,
-		}
-		impl LazyValValue for LazyMethodBinding {
-			fn get(self: Box<Self>) -> Result<Val> {
-				Ok(evaluate_method(
-					self.context_creator.unwrap(),
-					self.name,
-					self.params,
-					self.value,
-				))
-			}
-		}
-
-		LazyVal::new(Box::new(LazyMethodBinding {
-			context_creator,
-			name: b.name.clone(),
-			params,
-			value: b.value.clone(),
-		}))
-	} else {
-		#[derive(Trace)]
-		#[trivially_drop]
-		struct LazyNamedBinding {
-			context_creator: FutureWrapper<Context>,
-			name: IStr,
-			value: LocExpr,
-		}
-		impl LazyValValue for LazyNamedBinding {
-			fn get(self: Box<Self>) -> Result<Val> {
-				evaluate_named(self.context_creator.unwrap(), &self.value, self.name)
-			}
-		}
-		LazyVal::new(Box::new(LazyNamedBinding {
-			context_creator,
-			name: b.name.clone(),
-			value: b.value,
-		}))
-	}
-}
-
-pub fn evaluate_binding(b: &BindSpec, context_creator: ContextCreator) -> (IStr, LazyBinding) {
-	let b = b.clone();
-	if let Some(params) = &b.params {
-		let params = params.clone();
-
-		#[derive(Trace)]
-		#[trivially_drop]
-		struct BindableMethodLazyVal {
-			this: Option<ObjValue>,
-			super_obj: Option<ObjValue>,
-
-			context_creator: ContextCreator,
-			name: IStr,
-			params: ParamsDesc,
-			value: LocExpr,
-		}
-		impl LazyValValue for BindableMethodLazyVal {
-			fn get(self: Box<Self>) -> Result<Val> {
-				Ok(evaluate_method(
-					self.context_creator.create(self.this, self.super_obj)?,
-					self.name,
-					self.params,
-					self.value,
-				))
-			}
-		}
-
-		#[derive(Trace)]
-		#[trivially_drop]
-		struct BindableMethod {
-			context_creator: ContextCreator,
-			name: IStr,
-			params: ParamsDesc,
-			value: LocExpr,
-		}
-		impl Bindable for BindableMethod {
-			fn bind(&self, this: Option<ObjValue>, super_obj: Option<ObjValue>) -> Result<LazyVal> {
-				Ok(LazyVal::new(Box::new(BindableMethodLazyVal {
-					this,
-					super_obj,
-
-					context_creator: self.context_creator.clone(),
-					name: self.name.clone(),
-					params: self.params.clone(),
-					value: self.value.clone(),
-				})))
-			}
-		}
-
-		(
-			b.name.clone(),
-			LazyBinding::Bindable(Gc::new(Box::new(BindableMethod {
-				context_creator,
-				name: b.name.clone(),
-				params,
-				value: b.value.clone(),
-			}))),
-		)
-	} else {
-		#[derive(Trace)]
-		#[trivially_drop]
-		struct BindableNamedLazyVal {
-			this: Option<ObjValue>,
-			super_obj: Option<ObjValue>,
-
-			context_creator: ContextCreator,
-			name: IStr,
-			value: LocExpr,
-		}
-		impl LazyValValue for BindableNamedLazyVal {
-			fn get(self: Box<Self>) -> Result<Val> {
-				evaluate_named(
-					self.context_creator.create(self.this, self.super_obj)?,
-					&self.value,
-					self.name,
-				)
-			}
-		}
-
-		#[derive(Trace)]
-		#[trivially_drop]
-		struct BindableNamed {
-			context_creator: ContextCreator,
-			name: IStr,
-			value: LocExpr,
-		}
-		impl Bindable for BindableNamed {
-			fn bind(&self, this: Option<ObjValue>, super_obj: Option<ObjValue>) -> Result<LazyVal> {
-				Ok(LazyVal::new(Box::new(BindableNamedLazyVal {
-					this,
-					super_obj,
-
-					context_creator: self.context_creator.clone(),
-					name: self.name.clone(),
-					value: self.value.clone(),
-				})))
-			}
-		}
-
-		(
-			b.name.clone(),
-			LazyBinding::Bindable(Gc::new(Box::new(BindableNamed {
-				context_creator,
-				name: b.name.clone(),
-				value: b.value.clone(),
-			}))),
-		)
-	}
-}
-
-pub fn evaluate_method(ctx: Context, name: IStr, params: ParamsDesc, body: LocExpr) -> Val {
-	Val::Func(Gc::new(FuncVal::Normal(FuncDesc {
-		name,
-		ctx,
-		params,
-		body,
-	})))
-}
-
-pub fn evaluate_field_name(
-	context: Context,
-	field_name: &jrsonnet_parser::FieldName,
-) -> Result<Option<IStr>> {
-	Ok(match field_name {
-		jrsonnet_parser::FieldName::Fixed(n) => Some(n.clone()),
-		jrsonnet_parser::FieldName::Dyn(expr) => {
-			let value = evaluate(context, expr)?;
-			if matches!(value, Val::Null) {
-				None
-			} else {
-				Some(value.try_cast_str("dynamic field name")?)
-			}
-		}
-	})
-}
-
-pub fn evaluate_unary_op(op: UnaryOpType, b: &Val) -> Result<Val> {
-	Ok(match (op, b) {
-		(UnaryOpType::Not, Val::Bool(v)) => Val::Bool(!v),
-		(UnaryOpType::Minus, Val::Num(n)) => Val::Num(-*n),
-		(UnaryOpType::BitNot, Val::Num(n)) => Val::Num(!(*n as i32) as f64),
-		(op, o) => throw!(UnaryOperatorDoesNotOperateOnType(op, o.value_type())),
-	})
-}
-
-pub fn evaluate_add_op(a: &Val, b: &Val) -> Result<Val> {
-	Ok(match (a, b) {
-		(Val::Str(v1), Val::Str(v2)) => Val::Str(((**v1).to_owned() + v2).into()),
-
-		// Can't use generic json serialization way, because it depends on number to string concatenation (std.jsonnet:890)
-		(Val::Num(n), Val::Str(o)) => Val::Str(format!("{}{}", n, o).into()),
-		(Val::Str(o), Val::Num(n)) => Val::Str(format!("{}{}", o, n).into()),
-
-		(Val::Str(s), o) => Val::Str(format!("{}{}", s, o.clone().to_string()?).into()),
-		(o, Val::Str(s)) => Val::Str(format!("{}{}", o.clone().to_string()?, s).into()),
-
-		(Val::Obj(v1), Val::Obj(v2)) => Val::Obj(v2.extend_from(v1.clone())),
-		(Val::Arr(a), Val::Arr(b)) => {
-			let mut out = Vec::with_capacity(a.len() + b.len());
-			out.extend(a.iter_lazy());
-			out.extend(b.iter_lazy());
-			Val::Arr(out.into())
-		}
-		(Val::Num(v1), Val::Num(v2)) => Val::new_checked_num(v1 + v2)?,
-		_ => throw!(BinaryOperatorDoesNotOperateOnValues(
-			BinaryOpType::Add,
-			a.value_type(),
-			b.value_type(),
-		)),
-	})
-}
-
-pub fn evaluate_binary_op_special(
-	context: Context,
-	a: &LocExpr,
-	op: BinaryOpType,
-	b: &LocExpr,
-) -> Result<Val> {
-	Ok(match (evaluate(context.clone(), a)?, op, b) {
-		(Val::Bool(true), BinaryOpType::Or, _o) => Val::Bool(true),
-		(Val::Bool(false), BinaryOpType::And, _o) => Val::Bool(false),
-		(a, op, eb) => evaluate_binary_op_normal(&a, op, &evaluate(context, eb)?)?,
-	})
-}
-
-pub fn evaluate_binary_op_normal(a: &Val, op: BinaryOpType, b: &Val) -> Result<Val> {
-	Ok(match (a, op, b) {
-		(a, BinaryOpType::Add, b) => evaluate_add_op(a, b)?,
-
-		(a, BinaryOpType::Eq, b) => Val::Bool(equals(a, b)?),
-		(a, BinaryOpType::Neq, b) => Val::Bool(!equals(a, b)?),
-
-		(Val::Str(v1), BinaryOpType::Mul, Val::Num(v2)) => Val::Str(v1.repeat(*v2 as usize).into()),
-
-		// Bool X Bool
-		(Val::Bool(a), BinaryOpType::And, Val::Bool(b)) => Val::Bool(*a && *b),
-		(Val::Bool(a), BinaryOpType::Or, Val::Bool(b)) => Val::Bool(*a || *b),
-
-		// Str X Str
-		(Val::Str(v1), BinaryOpType::Lt, Val::Str(v2)) => Val::Bool(v1 < v2),
-		(Val::Str(v1), BinaryOpType::Gt, Val::Str(v2)) => Val::Bool(v1 > v2),
-		(Val::Str(v1), BinaryOpType::Lte, Val::Str(v2)) => Val::Bool(v1 <= v2),
-		(Val::Str(v1), BinaryOpType::Gte, Val::Str(v2)) => Val::Bool(v1 >= v2),
-
-		// Num X Num
-		(Val::Num(v1), BinaryOpType::Mul, Val::Num(v2)) => Val::new_checked_num(v1 * v2)?,
-		(Val::Num(v1), BinaryOpType::Div, Val::Num(v2)) => {
-			if *v2 <= f64::EPSILON {
-				throw!(DivisionByZero)
-			}
-			Val::new_checked_num(v1 / v2)?
-		}
-
-		(Val::Num(v1), BinaryOpType::Sub, Val::Num(v2)) => Val::new_checked_num(v1 - v2)?,
-
-		(Val::Num(v1), BinaryOpType::Lt, Val::Num(v2)) => Val::Bool(v1 < v2),
-		(Val::Num(v1), BinaryOpType::Gt, Val::Num(v2)) => Val::Bool(v1 > v2),
-		(Val::Num(v1), BinaryOpType::Lte, Val::Num(v2)) => Val::Bool(v1 <= v2),
-		(Val::Num(v1), BinaryOpType::Gte, Val::Num(v2)) => Val::Bool(v1 >= v2),
-
-		(Val::Num(v1), BinaryOpType::BitAnd, Val::Num(v2)) => {
-			Val::Num(((*v1 as i32) & (*v2 as i32)) as f64)
-		}
-		(Val::Num(v1), BinaryOpType::BitOr, Val::Num(v2)) => {
-			Val::Num(((*v1 as i32) | (*v2 as i32)) as f64)
-		}
-		(Val::Num(v1), BinaryOpType::BitXor, Val::Num(v2)) => {
-			Val::Num(((*v1 as i32) ^ (*v2 as i32)) as f64)
-		}
-		(Val::Num(v1), BinaryOpType::Lhs, Val::Num(v2)) => {
-			if *v2 < 0.0 {
-				throw!(RuntimeError("shift by negative exponent".into()))
-			}
-			Val::Num(((*v1 as i32) << (*v2 as i32)) as f64)
-		}
-		(Val::Num(v1), BinaryOpType::Rhs, Val::Num(v2)) => {
-			if *v2 < 0.0 {
-				throw!(RuntimeError("shift by negative exponent".into()))
-			}
-			Val::Num(((*v1 as i32) >> (*v2 as i32)) as f64)
-		}
-
-		_ => throw!(BinaryOperatorDoesNotOperateOnValues(
-			op,
-			a.value_type(),
-			b.value_type(),
-		)),
-	})
-}
-
-pub fn evaluate_comp(
-	context: Context,
-	specs: &[CompSpec],
-	callback: &mut impl FnMut(Context) -> Result<()>,
-) -> Result<()> {
-	match specs.get(0) {
-		None => callback(context)?,
-		Some(CompSpec::IfSpec(IfSpecData(cond))) => {
-			if evaluate(context.clone(), cond)?.try_cast_bool("if spec")? {
-				evaluate_comp(context, &specs[1..], callback)?
-			}
-		}
-		Some(CompSpec::ForSpec(ForSpecData(var, expr))) => match evaluate(context.clone(), expr)? {
-			Val::Arr(list) => {
-				for item in list.iter() {
-					evaluate_comp(
-						context.clone().with_var(var.clone(), item?.clone()),
-						&specs[1..],
-						callback,
-					)?
-				}
-			}
-			_ => throw!(InComprehensionCanOnlyIterateOverArray),
-		},
-	}
-	Ok(())
-}
-
-pub fn evaluate_member_list_object(context: Context, members: &[Member]) -> Result<ObjValue> {
-	let new_bindings = FutureWrapper::new();
-	let future_this = FutureWrapper::new();
-	let context_creator = ContextCreator(context.clone(), new_bindings.clone());
-	{
-		let mut bindings: FxHashMap<IStr, LazyBinding> =
-			FxHashMap::with_capacity_and_hasher(members.len(), BuildHasherDefault::default());
-		for (n, b) in members
-			.iter()
-			.filter_map(|m| match m {
-				Member::BindStmt(b) => Some(b.clone()),
-				_ => None,
-			})
-			.map(|b| evaluate_binding(&b, context_creator.clone()))
-		{
-			bindings.insert(n, b);
-		}
-		new_bindings.fill(bindings);
-	}
-
-	let mut new_members = FxHashMap::default();
-	let mut assertions: Vec<Box<dyn ObjectAssertion>> = Vec::new();
-	for member in members.iter() {
-		match member {
-			Member::Field(FieldMember {
-				name,
-				plus,
-				params: None,
-				visibility,
-				value,
-			}) => {
-				let name = evaluate_field_name(context.clone(), name)?;
-				if name.is_none() {
-					continue;
-				}
-				let name = name.unwrap();
-
-				#[derive(Trace)]
-				#[trivially_drop]
-				struct ObjMemberBinding {
-					context_creator: ContextCreator,
-					value: LocExpr,
-					name: IStr,
-				}
-				impl Bindable for ObjMemberBinding {
-					fn bind(
-						&self,
-						this: Option<ObjValue>,
-						super_obj: Option<ObjValue>,
-					) -> Result<LazyVal> {
-						Ok(LazyVal::new_resolved(evaluate_named(
-							self.context_creator.create(this, super_obj)?,
-							&self.value,
-							self.name.clone(),
-						)?))
-					}
-				}
-				new_members.insert(
-					name.clone(),
-					ObjMember {
-						add: *plus,
-						visibility: *visibility,
-						invoke: LazyBinding::Bindable(Gc::new(Box::new(ObjMemberBinding {
-							context_creator: context_creator.clone(),
-							value: value.clone(),
-							name,
-						}))),
-						location: value.1.clone(),
-					},
-				);
-			}
-			Member::Field(FieldMember {
-				name,
-				params: Some(params),
-				value,
-				..
-			}) => {
-				let name = evaluate_field_name(context.clone(), name)?;
-				if name.is_none() {
-					continue;
-				}
-				let name = name.unwrap();
-				#[derive(Trace)]
-				#[trivially_drop]
-				struct ObjMemberBinding {
-					context_creator: ContextCreator,
-					value: LocExpr,
-					params: ParamsDesc,
-					name: IStr,
-				}
-				impl Bindable for ObjMemberBinding {
-					fn bind(
-						&self,
-						this: Option<ObjValue>,
-						super_obj: Option<ObjValue>,
-					) -> Result<LazyVal> {
-						Ok(LazyVal::new_resolved(evaluate_method(
-							self.context_creator.create(this, super_obj)?,
-							self.name.clone(),
-							self.params.clone(),
-							self.value.clone(),
-						)))
-					}
-				}
-				new_members.insert(
-					name.clone(),
-					ObjMember {
-						add: false,
-						visibility: Visibility::Hidden,
-						invoke: LazyBinding::Bindable(Gc::new(Box::new(ObjMemberBinding {
-							context_creator: context_creator.clone(),
-							value: value.clone(),
-							params: params.clone(),
-							name,
-						}))),
-						location: value.1.clone(),
-					},
-				);
-			}
-			Member::BindStmt(_) => {}
-			Member::AssertStmt(stmt) => {
-				#[derive(Trace)]
-				#[trivially_drop]
-				struct ObjectAssert {
-					context_creator: ContextCreator,
-					assert: AssertStmt,
-				}
-				impl ObjectAssertion for ObjectAssert {
-					fn run(
-						&self,
-						this: Option<ObjValue>,
-						super_obj: Option<ObjValue>,
-					) -> Result<()> {
-						let ctx = self.context_creator.create(this, super_obj)?;
-						evaluate_assert(ctx, &self.assert)
-					}
-				}
-				assertions.push(Box::new(ObjectAssert {
-					context_creator: context_creator.clone(),
-					assert: stmt.clone(),
-				}));
-			}
-		}
-	}
-	let this = ObjValue::new(None, Gc::new(new_members), Gc::new(assertions));
-	future_this.fill(this.clone());
-	Ok(this)
-}
-
-pub fn evaluate_object(context: Context, object: &ObjBody) -> Result<ObjValue> {
-	Ok(match object {
-		ObjBody::MemberList(members) => evaluate_member_list_object(context, members)?,
-		ObjBody::ObjComp(obj) => {
-			let future_this = FutureWrapper::new();
-			let mut new_members = FxHashMap::default();
-			evaluate_comp(context.clone(), &obj.compspecs, &mut |ctx| {
-				let new_bindings = FutureWrapper::new();
-				let context_creator = ContextCreator(context.clone(), new_bindings.clone());
-				let mut bindings: FxHashMap<IStr, LazyBinding> =
-					FxHashMap::with_capacity_and_hasher(
-						obj.pre_locals.len() + obj.post_locals.len(),
-						BuildHasherDefault::default(),
-					);
-				for (n, b) in obj
-					.pre_locals
-					.iter()
-					.chain(obj.post_locals.iter())
-					.map(|b| evaluate_binding(b, context_creator.clone()))
-				{
-					bindings.insert(n, b);
-				}
-				new_bindings.fill(bindings.clone());
-				let ctx = ctx.extend_unbound(bindings, None, None, None)?;
-				let key = evaluate(ctx.clone(), &obj.key)?;
-
-				match key {
-					Val::Null => {}
-					Val::Str(n) => {
-						#[derive(Trace)]
-						#[trivially_drop]
-						struct ObjCompBinding {
-							context: Context,
-							value: LocExpr,
-						}
-						impl Bindable for ObjCompBinding {
-							fn bind(
-								&self,
-								this: Option<ObjValue>,
-								_super_obj: Option<ObjValue>,
-							) -> Result<LazyVal> {
-								Ok(LazyVal::new_resolved(evaluate(
-									self.context.clone().extend(
-										FxHashMap::default(),
-										None,
-										this,
-										None,
-									),
-									&self.value,
-								)?))
-							}
-						}
-						new_members.insert(
-							n,
-							ObjMember {
-								add: false,
-								visibility: Visibility::Normal,
-								invoke: LazyBinding::Bindable(Gc::new(Box::new(ObjCompBinding {
-									context: ctx,
-									value: obj.value.clone(),
-								}))),
-								location: obj.value.1.clone(),
-							},
-						);
-					}
-					v => throw!(FieldMustBeStringGot(v.value_type())),
-				}
-
-				Ok(())
-			})?;
-
-			let this = ObjValue::new(None, Gc::new(new_members), Gc::new(Vec::new()));
-			future_this.fill(this.clone());
-			this
-		}
-	})
-}
-
-pub fn evaluate_apply(
-	context: Context,
-	value: &LocExpr,
-	args: &ArgsDesc,
-	loc: Option<&ExprLocation>,
-	tailstrict: bool,
-) -> Result<Val> {
-	let value = evaluate(context.clone(), value)?;
-	Ok(match value {
-		Val::Func(f) => {
-			let body = || f.evaluate(context, loc, args, tailstrict);
-			if tailstrict {
-				body()?
-			} else {
-				push(loc, || format!("function <{}> call", f.name()), body)?
-			}
-		}
-		v => throw!(OnlyFunctionsCanBeCalledGot(v.value_type())),
-	})
-}
-
-pub fn evaluate_assert(context: Context, assertion: &AssertStmt) -> Result<()> {
-	let value = &assertion.0;
-	let msg = &assertion.1;
-	let assertion_result = push(
-		value.1.as_ref(),
-		|| "assertion condition".to_owned(),
-		|| {
-			evaluate(context.clone(), value)?
-				.try_cast_bool("assertion condition should be of type `boolean`")
-		},
-	)?;
-	if !assertion_result {
-		push(
-			value.1.as_ref(),
-			|| "assertion failure".to_owned(),
-			|| {
-				if let Some(msg) = msg {
-					throw!(AssertionFailed(evaluate(context, msg)?.to_string()?));
-				} else {
-					throw!(AssertionFailed(Val::Null.to_string()?));
-				}
-			},
-		)?
-	}
-	Ok(())
-}
-
-pub fn evaluate_named(context: Context, lexpr: &LocExpr, name: IStr) -> Result<Val> {
-	use Expr::*;
-	let LocExpr(expr, _loc) = lexpr;
-	Ok(match &**expr {
-		Function(params, body) => evaluate_method(context, name, params.clone(), body.clone()),
-		_ => evaluate(context, lexpr)?,
-	})
-}
-
-pub fn evaluate(context: Context, expr: &LocExpr) -> Result<Val> {
-	use Expr::*;
-	let LocExpr(expr, loc) = expr;
-	Ok(match &**expr {
-		Literal(LiteralType::This) => {
-			Val::Obj(context.this().clone().ok_or(CantUseSelfOutsideOfObject)?)
-		}
-		Literal(LiteralType::Super) => Val::Obj(
-			context
-				.super_obj()
-				.clone()
-				.ok_or(NoSuperFound)?
-				.with_this(context.this().clone().unwrap()),
-		),
-		Literal(LiteralType::Dollar) => {
-			Val::Obj(context.dollar().clone().ok_or(NoTopLevelObjectFound)?)
-		}
-		Literal(LiteralType::True) => Val::Bool(true),
-		Literal(LiteralType::False) => Val::Bool(false),
-		Literal(LiteralType::Null) => Val::Null,
-		Parened(e) => evaluate(context, e)?,
-		Str(v) => Val::Str(v.clone()),
-		Num(v) => Val::new_checked_num(*v)?,
-		BinaryOp(v1, o, v2) => evaluate_binary_op_special(context, v1, *o, v2)?,
-		UnaryOp(o, v) => evaluate_unary_op(*o, &evaluate(context, v)?)?,
-		Var(name) => push(
-			loc.as_ref(),
-			|| format!("variable <{}>", name),
-			|| context.binding(name.clone())?.evaluate(),
-		)?,
-		Index(value, index) => {
-			match (evaluate(context.clone(), value)?, evaluate(context, index)?) {
-				(Val::Obj(v), Val::Str(s)) => {
-					let sn = s.clone();
-					push(
-						loc.as_ref(),
-						|| format!("field <{}> access", sn),
-						|| {
-							if let Some(v) = v.get(s.clone())? {
-								Ok(v)
-							} else if v.get("__intrinsic_namespace__".into())?.is_some() {
-								Ok(Val::Func(Gc::new(FuncVal::Intrinsic(s))))
-							} else {
-								throw!(NoSuchField(s))
-							}
-						},
-					)?
-				}
-				(Val::Obj(_), n) => throw!(ValueIndexMustBeTypeGot(
-					ValType::Obj,
-					ValType::Str,
-					n.value_type(),
-				)),
-
-				(Val::Arr(v), Val::Num(n)) => {
-					if n.fract() > f64::EPSILON {
-						throw!(FractionalIndex)
-					}
-					v.get(n as usize)?
-						.ok_or_else(|| ArrayBoundsError(n as usize, v.len()))?
-				}
-				(Val::Arr(_), Val::Str(n)) => throw!(AttemptedIndexAnArrayWithString(n)),
-				(Val::Arr(_), n) => throw!(ValueIndexMustBeTypeGot(
-					ValType::Arr,
-					ValType::Num,
-					n.value_type(),
-				)),
-
-				(Val::Str(s), Val::Num(n)) => Val::Str(
-					s.chars()
-						.skip(n as usize)
-						.take(1)
-						.collect::<String>()
-						.into(),
-				),
-				(Val::Str(_), n) => throw!(ValueIndexMustBeTypeGot(
-					ValType::Str,
-					ValType::Num,
-					n.value_type(),
-				)),
-
-				(v, _) => throw!(CantIndexInto(v.value_type())),
-			}
-		}
-		LocalExpr(bindings, returned) => {
-			let mut new_bindings: FxHashMap<IStr, LazyVal> = HashMap::with_capacity_and_hasher(
-				bindings.len(),
-				BuildHasherDefault::<FxHasher>::default(),
-			);
-			let future_context = Context::new_future();
-			for b in bindings {
-				new_bindings.insert(
-					b.name.clone(),
-					evaluate_binding_in_future(b, future_context.clone()),
-				);
-			}
-			let context = context
-				.extend_bound(new_bindings)
-				.into_future(future_context);
-			evaluate(context, &returned.clone())?
-		}
-		Arr(items) => {
-			let mut out = Vec::with_capacity(items.len());
-			for item in items {
-				// TODO: Implement ArrValue::Lazy with same context for every element?
-				#[derive(Trace)]
-				#[trivially_drop]
-				struct ArrayElement {
-					context: Context,
-					item: LocExpr,
-				}
-				impl LazyValValue for ArrayElement {
-					fn get(self: Box<Self>) -> Result<Val> {
-						evaluate(self.context, &self.item)
-					}
-				}
-				out.push(LazyVal::new(Box::new(ArrayElement {
-					context: context.clone(),
-					item: item.clone(),
-				})));
-			}
-			Val::Arr(out.into())
-		}
-		ArrComp(expr, comp_specs) => {
-			let mut out = Vec::new();
-			evaluate_comp(context, comp_specs, &mut |ctx| {
-				out.push(evaluate(ctx, expr)?);
-				Ok(())
-			})?;
-			Val::Arr(ArrValue::Eager(Gc::new(out)))
-		}
-		Obj(body) => Val::Obj(evaluate_object(context, body)?),
-		ObjExtend(s, t) => evaluate_add_op(
-			&evaluate(context.clone(), s)?,
-			&Val::Obj(evaluate_object(context, t)?),
-		)?,
-		Apply(value, args, tailstrict) => {
-			evaluate_apply(context, value, args, loc.as_ref(), *tailstrict)?
-		}
-		Function(params, body) => {
-			evaluate_method(context, "anonymous".into(), params.clone(), body.clone())
-		}
-		Intrinsic(name) => Val::Func(Gc::new(FuncVal::Intrinsic(name.clone()))),
-		AssertExpr(assert, returned) => {
-			evaluate_assert(context.clone(), assert)?;
-			evaluate(context, returned)?
-		}
-		ErrorStmt(e) => push(
-			loc.as_ref(),
-			|| "error statement".to_owned(),
-			|| {
-				throw!(RuntimeError(
-					evaluate(context, e)?.try_cast_str("error text should be of type `string`")?,
-				))
-			},
-		)?,
-		IfElse {
-			cond,
-			cond_then,
-			cond_else,
-		} => {
-			if push(
-				loc.as_ref(),
-				|| "if condition".to_owned(),
-				|| evaluate(context.clone(), &cond.0)?.try_cast_bool("in if condition"),
-			)? {
-				evaluate(context, cond_then)?
-			} else {
-				match cond_else {
-					Some(v) => evaluate(context, v)?,
-					None => Val::Null,
-				}
-			}
-		}
-		Import(path) => {
-			let tmp = loc
-				.clone()
-				.expect("imports cannot be used without loc_data")
-				.0;
-			let mut import_location = tmp.to_path_buf();
-			import_location.pop();
-			push(
-				loc.as_ref(),
-				|| format!("import {:?}", path),
-				|| with_state(|s| s.import_file(&import_location, path)),
-			)?
-		}
-		ImportStr(path) => {
-			let tmp = loc
-				.clone()
-				.expect("imports cannot be used without loc_data")
-				.0;
-			let mut import_location = tmp.to_path_buf();
-			import_location.pop();
-			Val::Str(with_state(|s| s.import_file_str(&import_location, path))?)
-		}
-	})
-}
addedcrates/jrsonnet-evaluator/src/evaluate/mod.rsdiffbeforeafterboth
after · crates/jrsonnet-evaluator/src/evaluate/mod.rs
1use crate::{2	error::Error::*,3	evaluate::operator::{evaluate_add_op, evaluate_binary_op_special, evaluate_unary_op},4	push, throw, with_state, ArrValue, Bindable, Context, ContextCreator, FuncDesc, FuncVal,5	FutureWrapper, LazyBinding, LazyVal, LazyValValue, ObjMember, ObjValue, ObjectAssertion,6	Result, Val,7};8use jrsonnet_gc::{Gc, Trace};9use jrsonnet_interner::IStr;10use jrsonnet_parser::{11	ArgsDesc, AssertStmt, BindSpec, CompSpec, Expr, ExprLocation, FieldMember, ForSpecData,12	IfSpecData, LiteralType, LocExpr, Member, ObjBody, ParamsDesc, Visibility,13};14use jrsonnet_types::ValType;15use rustc_hash::{FxHashMap, FxHasher};16use std::{collections::HashMap, hash::BuildHasherDefault};17pub mod operator;1819pub fn evaluate_binding_in_future(20	b: &BindSpec,21	context_creator: FutureWrapper<Context>,22) -> LazyVal {23	let b = b.clone();24	if let Some(params) = &b.params {25		let params = params.clone();2627		#[derive(Trace)]28		#[trivially_drop]29		struct LazyMethodBinding {30			context_creator: FutureWrapper<Context>,31			name: IStr,32			params: ParamsDesc,33			value: LocExpr,34		}35		impl LazyValValue for LazyMethodBinding {36			fn get(self: Box<Self>) -> Result<Val> {37				Ok(evaluate_method(38					self.context_creator.unwrap(),39					self.name,40					self.params,41					self.value,42				))43			}44		}4546		LazyVal::new(Box::new(LazyMethodBinding {47			context_creator,48			name: b.name.clone(),49			params,50			value: b.value.clone(),51		}))52	} else {53		#[derive(Trace)]54		#[trivially_drop]55		struct LazyNamedBinding {56			context_creator: FutureWrapper<Context>,57			name: IStr,58			value: LocExpr,59		}60		impl LazyValValue for LazyNamedBinding {61			fn get(self: Box<Self>) -> Result<Val> {62				evaluate_named(self.context_creator.unwrap(), &self.value, self.name)63			}64		}65		LazyVal::new(Box::new(LazyNamedBinding {66			context_creator,67			name: b.name.clone(),68			value: b.value,69		}))70	}71}7273pub fn evaluate_binding(b: &BindSpec, context_creator: ContextCreator) -> (IStr, LazyBinding) {74	let b = b.clone();75	if let Some(params) = &b.params {76		let params = params.clone();7778		#[derive(Trace)]79		#[trivially_drop]80		struct BindableMethodLazyVal {81			this: Option<ObjValue>,82			super_obj: Option<ObjValue>,8384			context_creator: ContextCreator,85			name: IStr,86			params: ParamsDesc,87			value: LocExpr,88		}89		impl LazyValValue for BindableMethodLazyVal {90			fn get(self: Box<Self>) -> Result<Val> {91				Ok(evaluate_method(92					self.context_creator.create(self.this, self.super_obj)?,93					self.name,94					self.params,95					self.value,96				))97			}98		}99100		#[derive(Trace)]101		#[trivially_drop]102		struct BindableMethod {103			context_creator: ContextCreator,104			name: IStr,105			params: ParamsDesc,106			value: LocExpr,107		}108		impl Bindable for BindableMethod {109			fn bind(&self, this: Option<ObjValue>, super_obj: Option<ObjValue>) -> Result<LazyVal> {110				Ok(LazyVal::new(Box::new(BindableMethodLazyVal {111					this,112					super_obj,113114					context_creator: self.context_creator.clone(),115					name: self.name.clone(),116					params: self.params.clone(),117					value: self.value.clone(),118				})))119			}120		}121122		(123			b.name.clone(),124			LazyBinding::Bindable(Gc::new(Box::new(BindableMethod {125				context_creator,126				name: b.name.clone(),127				params,128				value: b.value.clone(),129			}))),130		)131	} else {132		#[derive(Trace)]133		#[trivially_drop]134		struct BindableNamedLazyVal {135			this: Option<ObjValue>,136			super_obj: Option<ObjValue>,137138			context_creator: ContextCreator,139			name: IStr,140			value: LocExpr,141		}142		impl LazyValValue for BindableNamedLazyVal {143			fn get(self: Box<Self>) -> Result<Val> {144				evaluate_named(145					self.context_creator.create(self.this, self.super_obj)?,146					&self.value,147					self.name,148				)149			}150		}151152		#[derive(Trace)]153		#[trivially_drop]154		struct BindableNamed {155			context_creator: ContextCreator,156			name: IStr,157			value: LocExpr,158		}159		impl Bindable for BindableNamed {160			fn bind(&self, this: Option<ObjValue>, super_obj: Option<ObjValue>) -> Result<LazyVal> {161				Ok(LazyVal::new(Box::new(BindableNamedLazyVal {162					this,163					super_obj,164165					context_creator: self.context_creator.clone(),166					name: self.name.clone(),167					value: self.value.clone(),168				})))169			}170		}171172		(173			b.name.clone(),174			LazyBinding::Bindable(Gc::new(Box::new(BindableNamed {175				context_creator,176				name: b.name.clone(),177				value: b.value.clone(),178			}))),179		)180	}181}182183pub fn evaluate_method(ctx: Context, name: IStr, params: ParamsDesc, body: LocExpr) -> Val {184	Val::Func(Gc::new(FuncVal::Normal(FuncDesc {185		name,186		ctx,187		params,188		body,189	})))190}191192pub fn evaluate_field_name(193	context: Context,194	field_name: &jrsonnet_parser::FieldName,195) -> Result<Option<IStr>> {196	Ok(match field_name {197		jrsonnet_parser::FieldName::Fixed(n) => Some(n.clone()),198		jrsonnet_parser::FieldName::Dyn(expr) => {199			let value = evaluate(context, expr)?;200			if matches!(value, Val::Null) {201				None202			} else {203				Some(value.try_cast_str("dynamic field name")?)204			}205		}206	})207}208209pub fn evaluate_comp(210	context: Context,211	specs: &[CompSpec],212	callback: &mut impl FnMut(Context) -> Result<()>,213) -> Result<()> {214	match specs.get(0) {215		None => callback(context)?,216		Some(CompSpec::IfSpec(IfSpecData(cond))) => {217			if evaluate(context.clone(), cond)?.try_cast_bool("if spec")? {218				evaluate_comp(context, &specs[1..], callback)?219			}220		}221		Some(CompSpec::ForSpec(ForSpecData(var, expr))) => match evaluate(context.clone(), expr)? {222			Val::Arr(list) => {223				for item in list.iter() {224					evaluate_comp(225						context.clone().with_var(var.clone(), item?.clone()),226						&specs[1..],227						callback,228					)?229				}230			}231			_ => throw!(InComprehensionCanOnlyIterateOverArray),232		},233	}234	Ok(())235}236237pub fn evaluate_member_list_object(context: Context, members: &[Member]) -> Result<ObjValue> {238	let new_bindings = FutureWrapper::new();239	let future_this = FutureWrapper::new();240	let context_creator = ContextCreator(context.clone(), new_bindings.clone());241	{242		let mut bindings: FxHashMap<IStr, LazyBinding> =243			FxHashMap::with_capacity_and_hasher(members.len(), BuildHasherDefault::default());244		for (n, b) in members245			.iter()246			.filter_map(|m| match m {247				Member::BindStmt(b) => Some(b.clone()),248				_ => None,249			})250			.map(|b| evaluate_binding(&b, context_creator.clone()))251		{252			bindings.insert(n, b);253		}254		new_bindings.fill(bindings);255	}256257	let mut new_members = FxHashMap::default();258	let mut assertions: Vec<Box<dyn ObjectAssertion>> = Vec::new();259	for member in members.iter() {260		match member {261			Member::Field(FieldMember {262				name,263				plus,264				params: None,265				visibility,266				value,267			}) => {268				let name = evaluate_field_name(context.clone(), name)?;269				if name.is_none() {270					continue;271				}272				let name = name.unwrap();273274				#[derive(Trace)]275				#[trivially_drop]276				struct ObjMemberBinding {277					context_creator: ContextCreator,278					value: LocExpr,279					name: IStr,280				}281				impl Bindable for ObjMemberBinding {282					fn bind(283						&self,284						this: Option<ObjValue>,285						super_obj: Option<ObjValue>,286					) -> Result<LazyVal> {287						Ok(LazyVal::new_resolved(evaluate_named(288							self.context_creator.create(this, super_obj)?,289							&self.value,290							self.name.clone(),291						)?))292					}293				}294				new_members.insert(295					name.clone(),296					ObjMember {297						add: *plus,298						visibility: *visibility,299						invoke: LazyBinding::Bindable(Gc::new(Box::new(ObjMemberBinding {300							context_creator: context_creator.clone(),301							value: value.clone(),302							name,303						}))),304						location: value.1.clone(),305					},306				);307			}308			Member::Field(FieldMember {309				name,310				params: Some(params),311				value,312				..313			}) => {314				let name = evaluate_field_name(context.clone(), name)?;315				if name.is_none() {316					continue;317				}318				let name = name.unwrap();319				#[derive(Trace)]320				#[trivially_drop]321				struct ObjMemberBinding {322					context_creator: ContextCreator,323					value: LocExpr,324					params: ParamsDesc,325					name: IStr,326				}327				impl Bindable for ObjMemberBinding {328					fn bind(329						&self,330						this: Option<ObjValue>,331						super_obj: Option<ObjValue>,332					) -> Result<LazyVal> {333						Ok(LazyVal::new_resolved(evaluate_method(334							self.context_creator.create(this, super_obj)?,335							self.name.clone(),336							self.params.clone(),337							self.value.clone(),338						)))339					}340				}341				new_members.insert(342					name.clone(),343					ObjMember {344						add: false,345						visibility: Visibility::Hidden,346						invoke: LazyBinding::Bindable(Gc::new(Box::new(ObjMemberBinding {347							context_creator: context_creator.clone(),348							value: value.clone(),349							params: params.clone(),350							name,351						}))),352						location: value.1.clone(),353					},354				);355			}356			Member::BindStmt(_) => {}357			Member::AssertStmt(stmt) => {358				#[derive(Trace)]359				#[trivially_drop]360				struct ObjectAssert {361					context_creator: ContextCreator,362					assert: AssertStmt,363				}364				impl ObjectAssertion for ObjectAssert {365					fn run(366						&self,367						this: Option<ObjValue>,368						super_obj: Option<ObjValue>,369					) -> Result<()> {370						let ctx = self.context_creator.create(this, super_obj)?;371						evaluate_assert(ctx, &self.assert)372					}373				}374				assertions.push(Box::new(ObjectAssert {375					context_creator: context_creator.clone(),376					assert: stmt.clone(),377				}));378			}379		}380	}381	let this = ObjValue::new(None, Gc::new(new_members), Gc::new(assertions));382	future_this.fill(this.clone());383	Ok(this)384}385386pub fn evaluate_object(context: Context, object: &ObjBody) -> Result<ObjValue> {387	Ok(match object {388		ObjBody::MemberList(members) => evaluate_member_list_object(context, members)?,389		ObjBody::ObjComp(obj) => {390			let future_this = FutureWrapper::new();391			let mut new_members = FxHashMap::default();392			evaluate_comp(context.clone(), &obj.compspecs, &mut |ctx| {393				let new_bindings = FutureWrapper::new();394				let context_creator = ContextCreator(context.clone(), new_bindings.clone());395				let mut bindings: FxHashMap<IStr, LazyBinding> =396					FxHashMap::with_capacity_and_hasher(397						obj.pre_locals.len() + obj.post_locals.len(),398						BuildHasherDefault::default(),399					);400				for (n, b) in obj401					.pre_locals402					.iter()403					.chain(obj.post_locals.iter())404					.map(|b| evaluate_binding(b, context_creator.clone()))405				{406					bindings.insert(n, b);407				}408				new_bindings.fill(bindings.clone());409				let ctx = ctx.extend_unbound(bindings, None, None, None)?;410				let key = evaluate(ctx.clone(), &obj.key)?;411412				match key {413					Val::Null => {}414					Val::Str(n) => {415						#[derive(Trace)]416						#[trivially_drop]417						struct ObjCompBinding {418							context: Context,419							value: LocExpr,420						}421						impl Bindable for ObjCompBinding {422							fn bind(423								&self,424								this: Option<ObjValue>,425								_super_obj: Option<ObjValue>,426							) -> Result<LazyVal> {427								Ok(LazyVal::new_resolved(evaluate(428									self.context.clone().extend(429										FxHashMap::default(),430										None,431										this,432										None,433									),434									&self.value,435								)?))436							}437						}438						new_members.insert(439							n,440							ObjMember {441								add: false,442								visibility: Visibility::Normal,443								invoke: LazyBinding::Bindable(Gc::new(Box::new(ObjCompBinding {444									context: ctx,445									value: obj.value.clone(),446								}))),447								location: obj.value.1.clone(),448							},449						);450					}451					v => throw!(FieldMustBeStringGot(v.value_type())),452				}453454				Ok(())455			})?;456457			let this = ObjValue::new(None, Gc::new(new_members), Gc::new(Vec::new()));458			future_this.fill(this.clone());459			this460		}461	})462}463464pub fn evaluate_apply(465	context: Context,466	value: &LocExpr,467	args: &ArgsDesc,468	loc: Option<&ExprLocation>,469	tailstrict: bool,470) -> Result<Val> {471	let value = evaluate(context.clone(), value)?;472	Ok(match value {473		Val::Func(f) => {474			let body = || f.evaluate(context, loc, args, tailstrict);475			if tailstrict {476				body()?477			} else {478				push(loc, || format!("function <{}> call", f.name()), body)?479			}480		}481		v => throw!(OnlyFunctionsCanBeCalledGot(v.value_type())),482	})483}484485pub fn evaluate_assert(context: Context, assertion: &AssertStmt) -> Result<()> {486	let value = &assertion.0;487	let msg = &assertion.1;488	let assertion_result = push(489		value.1.as_ref(),490		|| "assertion condition".to_owned(),491		|| {492			evaluate(context.clone(), value)?493				.try_cast_bool("assertion condition should be of type `boolean`")494		},495	)?;496	if !assertion_result {497		push(498			value.1.as_ref(),499			|| "assertion failure".to_owned(),500			|| {501				if let Some(msg) = msg {502					throw!(AssertionFailed(evaluate(context, msg)?.to_string()?));503				} else {504					throw!(AssertionFailed(Val::Null.to_string()?));505				}506			},507		)?508	}509	Ok(())510}511512pub fn evaluate_named(context: Context, lexpr: &LocExpr, name: IStr) -> Result<Val> {513	use Expr::*;514	let LocExpr(expr, _loc) = lexpr;515	Ok(match &**expr {516		Function(params, body) => evaluate_method(context, name, params.clone(), body.clone()),517		_ => evaluate(context, lexpr)?,518	})519}520521pub fn evaluate(context: Context, expr: &LocExpr) -> Result<Val> {522	use Expr::*;523	let LocExpr(expr, loc) = expr;524	Ok(match &**expr {525		Literal(LiteralType::This) => {526			Val::Obj(context.this().clone().ok_or(CantUseSelfOutsideOfObject)?)527		}528		Literal(LiteralType::Super) => Val::Obj(529			context530				.super_obj()531				.clone()532				.ok_or(NoSuperFound)?533				.with_this(context.this().clone().unwrap()),534		),535		Literal(LiteralType::Dollar) => {536			Val::Obj(context.dollar().clone().ok_or(NoTopLevelObjectFound)?)537		}538		Literal(LiteralType::True) => Val::Bool(true),539		Literal(LiteralType::False) => Val::Bool(false),540		Literal(LiteralType::Null) => Val::Null,541		Parened(e) => evaluate(context, e)?,542		Str(v) => Val::Str(v.clone()),543		Num(v) => Val::new_checked_num(*v)?,544		BinaryOp(v1, o, v2) => evaluate_binary_op_special(context, v1, *o, v2)?,545		UnaryOp(o, v) => evaluate_unary_op(*o, &evaluate(context, v)?)?,546		Var(name) => push(547			loc.as_ref(),548			|| format!("variable <{}>", name),549			|| context.binding(name.clone())?.evaluate(),550		)?,551		Index(value, index) => {552			match (evaluate(context.clone(), value)?, evaluate(context, index)?) {553				(Val::Obj(v), Val::Str(s)) => {554					let sn = s.clone();555					push(556						loc.as_ref(),557						|| format!("field <{}> access", sn),558						|| {559							if let Some(v) = v.get(s.clone())? {560								Ok(v)561							} else if v.get("__intrinsic_namespace__".into())?.is_some() {562								Ok(Val::Func(Gc::new(FuncVal::Intrinsic(s))))563							} else {564								throw!(NoSuchField(s))565							}566						},567					)?568				}569				(Val::Obj(_), n) => throw!(ValueIndexMustBeTypeGot(570					ValType::Obj,571					ValType::Str,572					n.value_type(),573				)),574575				(Val::Arr(v), Val::Num(n)) => {576					if n.fract() > f64::EPSILON {577						throw!(FractionalIndex)578					}579					v.get(n as usize)?580						.ok_or_else(|| ArrayBoundsError(n as usize, v.len()))?581				}582				(Val::Arr(_), Val::Str(n)) => throw!(AttemptedIndexAnArrayWithString(n)),583				(Val::Arr(_), n) => throw!(ValueIndexMustBeTypeGot(584					ValType::Arr,585					ValType::Num,586					n.value_type(),587				)),588589				(Val::Str(s), Val::Num(n)) => Val::Str(590					s.chars()591						.skip(n as usize)592						.take(1)593						.collect::<String>()594						.into(),595				),596				(Val::Str(_), n) => throw!(ValueIndexMustBeTypeGot(597					ValType::Str,598					ValType::Num,599					n.value_type(),600				)),601602				(v, _) => throw!(CantIndexInto(v.value_type())),603			}604		}605		LocalExpr(bindings, returned) => {606			let mut new_bindings: FxHashMap<IStr, LazyVal> = HashMap::with_capacity_and_hasher(607				bindings.len(),608				BuildHasherDefault::<FxHasher>::default(),609			);610			let future_context = Context::new_future();611			for b in bindings {612				new_bindings.insert(613					b.name.clone(),614					evaluate_binding_in_future(b, future_context.clone()),615				);616			}617			let context = context618				.extend_bound(new_bindings)619				.into_future(future_context);620			evaluate(context, &returned.clone())?621		}622		Arr(items) => {623			let mut out = Vec::with_capacity(items.len());624			for item in items {625				// TODO: Implement ArrValue::Lazy with same context for every element?626				#[derive(Trace)]627				#[trivially_drop]628				struct ArrayElement {629					context: Context,630					item: LocExpr,631				}632				impl LazyValValue for ArrayElement {633					fn get(self: Box<Self>) -> Result<Val> {634						evaluate(self.context, &self.item)635					}636				}637				out.push(LazyVal::new(Box::new(ArrayElement {638					context: context.clone(),639					item: item.clone(),640				})));641			}642			Val::Arr(out.into())643		}644		ArrComp(expr, comp_specs) => {645			let mut out = Vec::new();646			evaluate_comp(context, comp_specs, &mut |ctx| {647				out.push(evaluate(ctx, expr)?);648				Ok(())649			})?;650			Val::Arr(ArrValue::Eager(Gc::new(out)))651		}652		Obj(body) => Val::Obj(evaluate_object(context, body)?),653		ObjExtend(s, t) => evaluate_add_op(654			&evaluate(context.clone(), s)?,655			&Val::Obj(evaluate_object(context, t)?),656		)?,657		Apply(value, args, tailstrict) => {658			evaluate_apply(context, value, args, loc.as_ref(), *tailstrict)?659		}660		Function(params, body) => {661			evaluate_method(context, "anonymous".into(), params.clone(), body.clone())662		}663		Intrinsic(name) => Val::Func(Gc::new(FuncVal::Intrinsic(name.clone()))),664		AssertExpr(assert, returned) => {665			evaluate_assert(context.clone(), assert)?;666			evaluate(context, returned)?667		}668		ErrorStmt(e) => push(669			loc.as_ref(),670			|| "error statement".to_owned(),671			|| {672				throw!(RuntimeError(673					evaluate(context, e)?.try_cast_str("error text should be of type `string`")?,674				))675			},676		)?,677		IfElse {678			cond,679			cond_then,680			cond_else,681		} => {682			if push(683				loc.as_ref(),684				|| "if condition".to_owned(),685				|| evaluate(context.clone(), &cond.0)?.try_cast_bool("in if condition"),686			)? {687				evaluate(context, cond_then)?688			} else {689				match cond_else {690					Some(v) => evaluate(context, v)?,691					None => Val::Null,692				}693			}694		}695		Import(path) => {696			let tmp = loc697				.clone()698				.expect("imports cannot be used without loc_data")699				.0;700			let mut import_location = tmp.to_path_buf();701			import_location.pop();702			push(703				loc.as_ref(),704				|| format!("import {:?}", path),705				|| with_state(|s| s.import_file(&import_location, path)),706			)?707		}708		ImportStr(path) => {709			let tmp = loc710				.clone()711				.expect("imports cannot be used without loc_data")712				.0;713			let mut import_location = tmp.to_path_buf();714			import_location.pop();715			Val::Str(with_state(|s| s.import_file_str(&import_location, path))?)716		}717	})718}
addedcrates/jrsonnet-evaluator/src/evaluate/operator.rsdiffbeforeafterboth
--- /dev/null
+++ b/crates/jrsonnet-evaluator/src/evaluate/operator.rs
@@ -0,0 +1,118 @@
+use crate::{equals, evaluate, Context, Val};
+use crate::{error::Error::*, throw, Result};
+use jrsonnet_parser::{BinaryOpType, LocExpr, UnaryOpType};
+
+pub fn evaluate_unary_op(op: UnaryOpType, b: &Val) -> Result<Val> {
+	use UnaryOpType::*;
+	use Val::*;
+	Ok(match (op, b) {
+		(Not, Bool(v)) => Bool(!v),
+		(Minus, Num(n)) => Num(-*n),
+		(BitNot, Num(n)) => Num(!(*n as i32) as f64),
+		(op, o) => throw!(UnaryOperatorDoesNotOperateOnType(op, o.value_type())),
+	})
+}
+
+pub fn evaluate_add_op(a: &Val, b: &Val) -> Result<Val> {
+	use Val::*;
+	Ok(match (a, b) {
+		(Str(v1), Str(v2)) => Str(((**v1).to_owned() + v2).into()),
+
+		// Can't use generic json serialization way, because it depends on number to string concatenation (std.jsonnet:890)
+		(Num(n), Str(o)) => Str(format!("{}{}", n, o).into()),
+		(Str(o), Num(n)) => Str(format!("{}{}", o, n).into()),
+
+		(Str(s), o) => Str(format!("{}{}", s, o.clone().to_string()?).into()),
+		(o, Str(s)) => Str(format!("{}{}", o.clone().to_string()?, s).into()),
+
+		(Obj(v1), Obj(v2)) => Obj(v2.extend_from(v1.clone())),
+		(Arr(a), Arr(b)) => {
+			let mut out = Vec::with_capacity(a.len() + b.len());
+			out.extend(a.iter_lazy());
+			out.extend(b.iter_lazy());
+			Arr(out.into())
+		}
+		(Num(v1), Num(v2)) => Val::new_checked_num(v1 + v2)?,
+		_ => throw!(BinaryOperatorDoesNotOperateOnValues(
+			BinaryOpType::Add,
+			a.value_type(),
+			b.value_type(),
+		)),
+	})
+}
+
+pub fn evaluate_binary_op_special(
+	context: Context,
+	a: &LocExpr,
+	op: BinaryOpType,
+	b: &LocExpr,
+) -> Result<Val> {
+	use BinaryOpType::*;
+	use Val::*;
+	Ok(match (evaluate(context.clone(), a)?, op, b) {
+		(Bool(true), Or, _o) => Val::Bool(true),
+		(Bool(false), And, _o) => Val::Bool(false),
+		(a, op, eb) => evaluate_binary_op_normal(&a, op, &evaluate(context, eb)?)?,
+	})
+}
+
+pub fn evaluate_binary_op_normal(a: &Val, op: BinaryOpType, b: &Val) -> Result<Val> {
+	use BinaryOpType::*;
+	use Val::*;
+	Ok(match (a, op, b) {
+		(a, Add, b) => evaluate_add_op(a, b)?,
+
+		(a, Eq, b) => Bool(equals(a, b)?),
+		(a, Neq, b) => Bool(!equals(a, b)?),
+
+		(Str(v1), Mul, Num(v2)) => Str(v1.repeat(*v2 as usize).into()),
+
+		// Bool X Bool
+		(Bool(a), And, Bool(b)) => Bool(*a && *b),
+		(Bool(a), Or, Bool(b)) => Bool(*a || *b),
+
+		// Str X Str
+		(Str(v1), Lt, Str(v2)) => Bool(v1 < v2),
+		(Str(v1), Gt, Str(v2)) => Bool(v1 > v2),
+		(Str(v1), Lte, Str(v2)) => Bool(v1 <= v2),
+		(Str(v1), Gte, Str(v2)) => Bool(v1 >= v2),
+
+		// Num X Num
+		(Num(v1), Mul, Num(v2)) => Val::new_checked_num(v1 * v2)?,
+		(Num(v1), Div, Num(v2)) => {
+			if *v2 <= f64::EPSILON {
+				throw!(DivisionByZero)
+			}
+			Val::new_checked_num(v1 / v2)?
+		}
+
+		(Num(v1), Sub, Num(v2)) => Val::new_checked_num(v1 - v2)?,
+
+		(Num(v1), Lt, Num(v2)) => Bool(v1 < v2),
+		(Num(v1), Gt, Num(v2)) => Bool(v1 > v2),
+		(Num(v1), Lte, Num(v2)) => Bool(v1 <= v2),
+		(Num(v1), Gte, Num(v2)) => Bool(v1 >= v2),
+
+		(Num(v1), BitAnd, Num(v2)) => Num(((*v1 as i32) & (*v2 as i32)) as f64),
+		(Num(v1), BitOr, Num(v2)) => Num(((*v1 as i32) | (*v2 as i32)) as f64),
+		(Num(v1), BitXor, Num(v2)) => Num(((*v1 as i32) ^ (*v2 as i32)) as f64),
+		(Num(v1), Lhs, Num(v2)) => {
+			if *v2 < 0.0 {
+				throw!(RuntimeError("shift by negative exponent".into()))
+			}
+			Num(((*v1 as i32) << (*v2 as i32)) as f64)
+		}
+		(Num(v1), Rhs, Num(v2)) => {
+			if *v2 < 0.0 {
+				throw!(RuntimeError("shift by negative exponent".into()))
+			}
+			Num(((*v1 as i32) >> (*v2 as i32)) as f64)
+		}
+
+		_ => throw!(BinaryOperatorDoesNotOperateOnValues(
+			op,
+			a.value_type(),
+			b.value_type(),
+		)),
+	})
+}
modifiedcrates/jrsonnet-evaluator/src/lib.rsdiffbeforeafterboth
--- a/crates/jrsonnet-evaluator/src/lib.rs
+++ b/crates/jrsonnet-evaluator/src/lib.rs
@@ -1033,7 +1033,7 @@
 				local conf = {
 					n: ""
 				};
-				
+
 				local result = conf + {
 					assert std.isNumber(self.n): "is number"
 				};
modifiedcrates/jrsonnet-evaluator/src/obj.rsdiffbeforeafterboth
--- a/crates/jrsonnet-evaluator/src/obj.rs
+++ b/crates/jrsonnet-evaluator/src/obj.rs
@@ -1,4 +1,5 @@
-use crate::{evaluate_add_op, LazyBinding, Result, Val};
+use crate::operator::evaluate_add_op;
+use crate::{LazyBinding, Result, Val};
 use jrsonnet_gc::{Gc, GcCell, Trace};
 use jrsonnet_interner::IStr;
 use jrsonnet_parser::{ExprLocation, Visibility};