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

difftreelog

perf(evaluator) faster std.equals

Лач2020-07-02parent: #5c0b9a1.patch.diff
in: master

4 files changed

modifiedcrates/jrsonnet-evaluator/build.rsdiffbeforeafterboth
--- a/crates/jrsonnet-evaluator/build.rs
+++ b/crates/jrsonnet-evaluator/build.rs
@@ -35,7 +35,7 @@
 								Member::Field(FieldMember {
 									name: FieldName::Fixed(name),
 									..
-								}) if **name == *"join" || **name == *"manifestJsonEx" || **name == *"escapeStringJson"
+								}) if **name == *"join" || **name == *"manifestJsonEx" || **name == *"escapeStringJson" || **name == *"equals"
 							)
 						})
 						.collect(),
modifiedcrates/jrsonnet-evaluator/src/evaluate.rsdiffbeforeafterboth
before · crates/jrsonnet-evaluator/src/evaluate.rs
1use crate::{2	context_creator, create_error, create_error_result, escape_string_json, future_wrapper,3	lazy_val, manifest_json_ex, parse_args, push, with_state, Context, ContextCreator, Error,4	FuncDesc, LazyBinding, LazyVal, ObjMember, ObjValue, Result, Val, ValType,5};6use closure::closure;7use jrsonnet_parser::{8	ArgsDesc, AssertStmt, BinaryOpType, BindSpec, CompSpec, Expr, ExprLocation, FieldMember,9	ForSpecData, IfSpecData, LiteralType, LocExpr, Member, ObjBody, ParamsDesc, UnaryOpType,10	Visibility,11};12use std::{collections::HashMap, rc::Rc};1314pub fn evaluate_binding(b: &BindSpec, context_creator: ContextCreator) -> (Rc<str>, LazyBinding) {15	let b = b.clone();16	if let Some(params) = &b.params {17		let params = params.clone();18		(19			b.name.clone(),20			LazyBinding::Bindable(Rc::new(move |this, super_obj| {21				Ok(lazy_val!(22					closure!(clone b, clone params, clone context_creator, || Ok(evaluate_method(23						context_creator.0(this.clone(), super_obj.clone())?,24						params.clone(),25						b.value.clone(),26					)))27				))28			})),29		)30	} else {31		(32			b.name.clone(),33			LazyBinding::Bindable(Rc::new(move |this, super_obj| {34				Ok(lazy_val!(closure!(clone context_creator, clone b, ||35					push(&b.value.1, "thunk", ||{36						evaluate(37							context_creator.0(this.clone(), super_obj.clone())?,38							&b.value39						)40					})41				)))42			})),43		)44	}45}4647pub fn evaluate_method(ctx: Context, params: ParamsDesc, body: LocExpr) -> Val {48	Val::Func(FuncDesc { ctx, params, body })49}5051pub fn evaluate_field_name(52	context: Context,53	field_name: &jrsonnet_parser::FieldName,54) -> Result<Option<Rc<str>>> {55	Ok(match field_name {56		jrsonnet_parser::FieldName::Fixed(n) => Some(n.clone()),57		jrsonnet_parser::FieldName::Dyn(expr) => {58			let lazy = evaluate(context, expr)?;59			let value = lazy.unwrap_if_lazy()?;60			if matches!(value, Val::Null) {61				None62			} else {63				Some(value.try_cast_str("dynamic field name")?)64			}65		}66	})67}6869pub fn evaluate_unary_op(op: UnaryOpType, b: &Val) -> Result<Val> {70	Ok(match (op, b) {71		(o, Val::Lazy(l)) => evaluate_unary_op(o, &l.evaluate()?)?,72		(UnaryOpType::Not, Val::Bool(v)) => Val::Bool(!v),73		(UnaryOpType::Minus, Val::Num(n)) => Val::Num(-*n),74		(UnaryOpType::BitNot, Val::Num(n)) => Val::Num(!(*n as i32) as f64),75		(op, o) => create_error_result(Error::UnaryOperatorDoesNotOperateOnType(76			op,77			o.value_type()?,78		))?,79	})80}8182pub(crate) fn evaluate_add_op(a: &Val, b: &Val) -> Result<Val> {83	Ok(match (a, b) {84		(Val::Str(v1), Val::Str(v2)) => Val::Str(((**v1).to_owned() + &v2).into()),8586		// Can't use generic json serialization way, because it depends on number to string concatenation (std.jsonnet:890)87		(Val::Num(n), Val::Str(o)) => Val::Str(format!("{}{}", n, o).into()),88		(Val::Str(o), Val::Num(n)) => Val::Str(format!("{}{}", o, n).into()),8990		(Val::Str(s), o) => Val::Str(format!("{}{}", s, o.clone().into_json(0)?).into()),91		(o, Val::Str(s)) => Val::Str(format!("{}{}", o.clone().into_json(0)?, s).into()),9293		(Val::Obj(v1), Val::Obj(v2)) => Val::Obj(v2.with_super(v1.clone())),94		(Val::Arr(a), Val::Arr(b)) => Val::Arr(Rc::new([&a[..], &b[..]].concat())),95		(Val::Num(v1), Val::Num(v2)) => Val::new_checked_num(v1 + v2)?,96		_ => create_error_result(Error::BinaryOperatorDoesNotOperateOnValues(97			BinaryOpType::Add,98			a.value_type()?,99			b.value_type()?,100		))?,101	})102}103104pub fn evaluate_binary_op_special(105	context: Context,106	a: &LocExpr,107	op: BinaryOpType,108	b: &LocExpr,109) -> Result<Val> {110	Ok(111		match (evaluate(context.clone(), &a)?.unwrap_if_lazy()?, op, b) {112			(Val::Bool(true), BinaryOpType::Or, _o) => Val::Bool(true),113			(Val::Bool(false), BinaryOpType::And, _o) => Val::Bool(false),114			(a, op, eb) => {115				evaluate_binary_op_normal(&a, op, &evaluate(context, eb)?.unwrap_if_lazy()?)?116			}117		},118	)119}120121pub fn evaluate_binary_op_normal(a: &Val, op: BinaryOpType, b: &Val) -> Result<Val> {122	Ok(match (a, op, b) {123		(a, BinaryOpType::Add, b) => evaluate_add_op(a, b)?,124125		(Val::Str(v1), BinaryOpType::Mul, Val::Num(v2)) => Val::Str(v1.repeat(*v2 as usize).into()),126127		// Bool X Bool128		(Val::Bool(a), BinaryOpType::And, Val::Bool(b)) => Val::Bool(*a && *b),129		(Val::Bool(a), BinaryOpType::Or, Val::Bool(b)) => Val::Bool(*a || *b),130131		// Str X Str132		(Val::Str(v1), BinaryOpType::Lt, Val::Str(v2)) => Val::Bool(v1 < v2),133		(Val::Str(v1), BinaryOpType::Gt, Val::Str(v2)) => Val::Bool(v1 > v2),134		(Val::Str(v1), BinaryOpType::Lte, Val::Str(v2)) => Val::Bool(v1 <= v2),135		(Val::Str(v1), BinaryOpType::Gte, Val::Str(v2)) => Val::Bool(v1 >= v2),136137		// Num X Num138		(Val::Num(v1), BinaryOpType::Mul, Val::Num(v2)) => Val::new_checked_num(v1 * v2)?,139		(Val::Num(v1), BinaryOpType::Div, Val::Num(v2)) => {140			if *v2 <= f64::EPSILON {141				create_error_result(crate::Error::DivisionByZero)?142			}143			Val::new_checked_num(v1 / v2)?144		}145146		(Val::Num(v1), BinaryOpType::Sub, Val::Num(v2)) => Val::new_checked_num(v1 - v2)?,147148		(Val::Num(v1), BinaryOpType::Lt, Val::Num(v2)) => Val::Bool(v1 < v2),149		(Val::Num(v1), BinaryOpType::Gt, Val::Num(v2)) => Val::Bool(v1 > v2),150		(Val::Num(v1), BinaryOpType::Lte, Val::Num(v2)) => Val::Bool(v1 <= v2),151		(Val::Num(v1), BinaryOpType::Gte, Val::Num(v2)) => Val::Bool(v1 >= v2),152153		(Val::Num(v1), BinaryOpType::BitAnd, Val::Num(v2)) => {154			Val::Num(((*v1 as i32) & (*v2 as i32)) as f64)155		}156		(Val::Num(v1), BinaryOpType::BitOr, Val::Num(v2)) => {157			Val::Num(((*v1 as i32) | (*v2 as i32)) as f64)158		}159		(Val::Num(v1), BinaryOpType::BitXor, Val::Num(v2)) => {160			Val::Num(((*v1 as i32) ^ (*v2 as i32)) as f64)161		}162		(Val::Num(v1), BinaryOpType::Lhs, Val::Num(v2)) => {163			if *v2 < 0.0 {164				create_error_result(Error::RuntimeError("shift by negative exponent".into()))?165			}166			Val::Num(((*v1 as i32) << (*v2 as i32)) as f64)167		}168		(Val::Num(v1), BinaryOpType::Rhs, Val::Num(v2)) => {169			if *v2 < 0.0 {170				create_error_result(Error::RuntimeError("shift by negative exponent".into()))?171			}172			Val::Num(((*v1 as i32) >> (*v2 as i32)) as f64)173		}174175		_ => create_error_result(Error::BinaryOperatorDoesNotOperateOnValues(176			op,177			a.value_type()?,178			b.value_type()?,179		))?,180	})181}182183future_wrapper!(HashMap<Rc<str>, LazyBinding>, FutureNewBindings);184future_wrapper!(ObjValue, FutureObjValue);185186pub fn evaluate_comp<T>(187	context: Context,188	value: &impl Fn(Context) -> Result<T>,189	specs: &[CompSpec],190) -> Result<Option<Vec<T>>> {191	Ok(match specs.get(0) {192		None => Some(vec![value(context)?]),193		Some(CompSpec::IfSpec(IfSpecData(cond))) => {194			if evaluate(context.clone(), &cond)?.try_cast_bool("if spec")? {195				evaluate_comp(context, value, &specs[1..])?196			} else {197				None198			}199		}200		Some(CompSpec::ForSpec(ForSpecData(var, expr))) => {201			match evaluate(context.clone(), &expr)?.unwrap_if_lazy()? {202				Val::Arr(list) => {203					let mut out = Vec::new();204					for item in list.iter() {205						let item = item.unwrap_if_lazy()?;206						out.push(evaluate_comp(207							context.with_var(var.clone(), item.clone())?,208							value,209							&specs[1..],210						)?);211					}212					Some(out.into_iter().flatten().flatten().collect())213				}214				_ => create_error_result(Error::InComprehensionCanOnlyIterateOverArray)?,215			}216		}217	})218}219220pub fn evaluate_member_list_object(context: Context, members: &[Member]) -> Result<ObjValue> {221	let new_bindings = FutureNewBindings::new();222	let future_this = FutureObjValue::new();223	let context_creator = context_creator!(224		closure!(clone context, clone new_bindings, |this: Option<ObjValue>, super_obj: Option<ObjValue>| {225			Ok(context.extend_unbound(226				new_bindings.clone().unwrap(),227				context.dollar().clone().or_else(||this.clone()),228				Some(this.unwrap()),229				super_obj230			)?)231		})232	);233	{234		let mut bindings: HashMap<Rc<str>, LazyBinding> = HashMap::new();235		for (n, b) in members236			.iter()237			.filter_map(|m| match m {238				Member::BindStmt(b) => Some(b.clone()),239				_ => None,240			})241			.map(|b| evaluate_binding(&b, context_creator.clone()))242		{243			bindings.insert(n, b);244		}245		new_bindings.fill(bindings);246	}247248	let mut new_members = HashMap::new();249	for member in members.iter() {250		match member {251			Member::Field(FieldMember {252				name,253				plus,254				params: None,255				visibility,256				value,257			}) => {258				let name = evaluate_field_name(context.clone(), &name)?;259				if name.is_none() {260					continue;261				}262				let name = name.unwrap();263				new_members.insert(264					name.clone(),265					ObjMember {266						add: *plus,267						visibility: *visibility,268						invoke: LazyBinding::Bindable(Rc::new(269							closure!(clone name, clone value, clone context_creator, |this, super_obj| {270								Ok(LazyVal::new_resolved(push(&value.1, "object field", ||{271									let context = context_creator.0(this, super_obj)?;272									evaluate(273										context,274										&value,275									)276								})?))277							}),278						)),279						location: value.1.clone(),280					},281				);282			}283			Member::Field(FieldMember {284				name,285				params: Some(params),286				value,287				..288			}) => {289				let name = evaluate_field_name(context.clone(), &name)?;290				if name.is_none() {291					continue;292				}293				let name = name.unwrap();294				new_members.insert(295					name,296					ObjMember {297						add: false,298						visibility: Visibility::Hidden,299						invoke: LazyBinding::Bindable(Rc::new(300							closure!(clone value, clone context_creator, clone params, |this, super_obj| {301								// TODO: Assert302								Ok(LazyVal::new_resolved(evaluate_method(303									context_creator.0(this, super_obj)?,304									params.clone(),305									value.clone(),306								)))307							}),308						)),309						location: value.1.clone(),310					},311				);312			}313			Member::BindStmt(_) => {}314			Member::AssertStmt(_) => {}315		}316	}317	Ok(future_this.fill(ObjValue::new(None, Rc::new(new_members))))318}319320pub fn evaluate_object(context: Context, object: &ObjBody) -> Result<ObjValue> {321	Ok(match object {322		ObjBody::MemberList(members) => evaluate_member_list_object(context, &members)?,323		ObjBody::ObjComp(obj) => {324			let future_this = FutureObjValue::new();325			let mut new_members = HashMap::new();326			for (k, v) in evaluate_comp(327				context.clone(),328				&|ctx| {329					let new_bindings = FutureNewBindings::new();330					let context_creator = context_creator!(331						closure!(clone context, clone new_bindings, |this: Option<ObjValue>, super_obj: Option<ObjValue>| {332							Ok(context.extend_unbound(333								new_bindings.clone().unwrap(),334								context.dollar().clone().or_else(||this.clone()),335								None,336								super_obj337							)?)338						})339					);340					let mut bindings: HashMap<Rc<str>, LazyBinding> = HashMap::new();341					for (n, b) in obj342						.pre_locals343						.iter()344						.chain(obj.post_locals.iter())345						.map(|b| evaluate_binding(b, context_creator.clone()))346					{347						bindings.insert(n, b);348					}349					let bindings = new_bindings.fill(bindings);350					let ctx = ctx.extend_unbound(bindings, None, None, None)?;351					let key = evaluate(ctx.clone(), &obj.key)?;352					let value = LazyBinding::Bindable(Rc::new(353						closure!(clone ctx, clone obj.value, |this, _super_obj| {354							Ok(LazyVal::new_resolved(evaluate(ctx.extend(HashMap::new(), None, this, None)?, &value)?))355						}),356					));357358					Ok((key, value))359				},360				&obj.compspecs,361			)?362			.unwrap()363			{364				match k {365					Val::Null => {}366					Val::Str(n) => {367						new_members.insert(368							n,369							ObjMember {370								add: false,371								visibility: Visibility::Normal,372								invoke: v,373								location: obj.value.1.clone(),374							},375						);376					}377					v => create_error_result(Error::FieldMustBeStringGot(v.value_type()?))?,378				}379			}380381			future_this.fill(ObjValue::new(None, Rc::new(new_members)))382		}383	})384}385386/// Extracts code block and disables inlining for them387/// Fixes WASM to java bytecode compilation failing because of very large method388macro_rules! noinline {389	($e:expr) => {390		(#[inline(never)]391		move || $e)()392	};393}394395pub fn evaluate_apply(396	context: Context,397	value: &LocExpr,398	args: &ArgsDesc,399	loc: &Option<ExprLocation>,400	tailstrict: bool,401) -> Result<Val> {402	let lazy = evaluate(context.clone(), value)?;403	let value = lazy.unwrap_if_lazy()?;404	Ok(match value {405		Val::Intristic(ns, name) => match (&ns as &str, &name as &str) {406			// arr/string/function407			("std", "length") => noinline!(parse_args!(context, "std.length", args, 1, [408				0, x: [Val::Str|Val::Arr|Val::Obj], vec![ValType::Str, ValType::Arr, ValType::Obj];409			], {410				Ok(match x {411					Val::Str(n) => Val::Num(n.chars().count() as f64),412					Val::Arr(i) => Val::Num(i.len() as f64),413					Val::Obj(o) => Val::Num(414						o.fields_visibility()415							.into_iter()416							.filter(|(_k, v)| *v)417							.count() as f64,418					),419					_ => unreachable!(),420				})421			}))?,422			// any423			("std", "type") => parse_args!(context, "std.type", args, 1, [424				0, x, vec![];425			], {426				Val::Str(x.value_type()?.name().into())427			}),428			// length, idx=>any429			("std", "makeArray") => noinline!(parse_args!(context, "std.makeArray", args, 2, [430				0, sz: [Val::Num]!!Val::Num, vec![ValType::Num];431				1, func: [Val::Func]!!Val::Func, vec![ValType::Func];432			], {433				if sz < 0.0 {434					create_error_result(crate::error::Error::RuntimeError(format!("makeArray requires size >= 0, got {}", sz).into()))?;435				}436				let mut out = Vec::with_capacity(sz as usize);437				for i in 0..sz as usize {438					out.push(func.evaluate_values(439						Context::new(),440						&[Val::Num(i as f64)]441					)?)442				}443				Ok(Val::Arr(Rc::new(out)))444			}))?,445			// string446			("std", "codepoint") => parse_args!(context, "std.codepoint", args, 1, [447				0, str: [Val::Str]!!Val::Str, vec![ValType::Str];448			], {449				assert!(450					str.chars().count() == 1,451					"std.codepoint should receive single char string"452				);453				Val::Num(str.chars().take(1).next().unwrap() as u32 as f64)454			}),455			// object, includeHidden456			("std", "objectFieldsEx") => {457				noinline!(parse_args!(context, "std.objectFieldsEx",args, 2, [458					0, obj: [Val::Obj]!!Val::Obj, vec![ValType::Obj];459					1, inc_hidden: [Val::Bool]!!Val::Bool, vec![ValType::Bool];460				], {461					let mut out = obj.fields_visibility()462						.into_iter()463						.filter(|(_k, v)| *v || inc_hidden)464						.map(|(k, _v)|k)465						.collect::<Vec<_>>();466					out.sort();467					Ok(Val::Arr(Rc::new(out.into_iter().map(Val::Str).collect())))468				}))?469			}470			// object, field, includeHidden471			("std", "objectHasEx") => parse_args!(context, "std.objectHasEx", args, 3, [472				0, obj: [Val::Obj]!!Val::Obj, vec![ValType::Obj];473				1, f: [Val::Str]!!Val::Str, vec![ValType::Str];474				2, inc_hidden: [Val::Bool]!!Val::Bool, vec![ValType::Bool];475			], {476				Val::Bool(477					obj.fields_visibility()478						.into_iter()479						.filter(|(_k, v)| *v || inc_hidden)480						.any(|(k, _v)| *k == *f),481				)482			}),483			("std", "primitiveEquals") => parse_args!(context, "std.primitiveEquals", args, 2, [484				0, a, vec![];485				1, b, vec![];486			], {487				Val::Bool(a == b)488			}),489			("std", "modulo") => parse_args!(context, "std.modulo", args, 2, [490				0, a: [Val::Num]!!Val::Num, vec![ValType::Num];491				1, b: [Val::Num]!!Val::Num, vec![ValType::Num];492			], {493				Val::Num(a % b)494			}),495			("std", "floor") => parse_args!(context, "std.floor", args, 1, [496				0, x: [Val::Num]!!Val::Num, vec![ValType::Num];497			], {498				Val::Num(x.floor())499			}),500			("std", "trace") => parse_args!(context, "std.trace", args, 2, [501				0, str: [Val::Str]!!Val::Str, vec![ValType::Str];502				1, rest, vec![];503			], {504				eprint!("TRACE: ");505				if let Some(loc) = loc {506					with_state(|s|{507						let locs = s.map_source_locations(&loc.0, &[loc.1]);508						eprint!("{}:{} ", loc.0.display(), locs[0].line);509					});510				}511				eprintln!("{}", str);512				rest513			}),514			("std", "pow") => parse_args!(context, "std.modulo", args, 2, [515				0, x: [Val::Num]!!Val::Num, vec![ValType::Num];516				1, n: [Val::Num]!!Val::Num, vec![ValType::Num];517			], {518				Val::Num(x.powf(n))519			}),520			("std", "extVar") => parse_args!(context, "std.extVar", args, 2, [521				0, x: [Val::Str]!!Val::Str, vec![ValType::Str];522			], {523				with_state(|s| s.settings().ext_vars.get(&x).cloned()).ok_or_else(524					|| create_error(crate::Error::UndefinedExternalVariable(x)),525				)?526			}),527			("std", "filter") => noinline!(parse_args!(context, "std.filter", args, 2, [528				0, func: [Val::Func]!!Val::Func, vec![ValType::Func];529				1, arr: [Val::Arr]!!Val::Arr, vec![ValType::Arr];530			], {531				Ok(Val::Arr(Rc::new(532					arr.iter()533						.cloned()534						.filter(|e| {535							func536								.evaluate_values(context.clone(), &[e.clone()])537								.unwrap()538								.try_cast_bool("filter predicate")539								.unwrap()540						})541						.collect(),542				)))543			}))?,544			("std", "char") => parse_args!(context, "std.char", args, 1, [545				0, n: [Val::Num]!!Val::Num, vec![ValType::Num];546			], {547				let mut out = String::new();548				out.push(std::char::from_u32(n as u32).unwrap());549				Val::Str(out.into())550			}),551			("std", "encodeUTF8") => parse_args!(context, "std.encodeUtf8", args, 1, [552				0, str: [Val::Str]!!Val::Str, vec![ValType::Str];553			], {554				Val::Arr(Rc::new(str.bytes().map(|b| Val::Num(b as f64)).collect()))555			}),556			("std", "md5") => noinline!(parse_args!(context, "std.md5", args, 1, [557				0, str: [Val::Str]!!Val::Str, vec![ValType::Str];558			], {559				Ok(Val::Str(format!("{:x}", md5::compute(&str.as_bytes())).into()))560			}))?,561			// faster562			("std", "join") => noinline!(parse_args!(context, "std.join", args, 2, [563				0, sep: [Val::Str|Val::Arr], vec![ValType::Str, ValType::Arr];564				1, arr: [Val::Arr]!!Val::Arr, vec![ValType::Arr];565			], {566				Ok(match sep {567					Val::Arr(joiner_items) => {568						let mut out = Vec::new();569570						let mut first = true;571						for item in arr.iter().cloned() {572							if let Val::Arr(items) = item.unwrap_if_lazy()? {573								if !first {574									out.reserve(joiner_items.len());575									out.extend(joiner_items.iter().cloned());576								}577								first = false;578								out.reserve(items.len());579								out.extend(items.iter().cloned());580							} else {581								create_error_result(crate::Error::RuntimeError("in std.join all items should be arrays".into()))?;582							}583						}584585						Val::Arr(Rc::new(out))586					},587					Val::Str(sep) => {588						let mut out = String::new();589590						let mut first = true;591						for item in arr.iter().cloned() {592							if let Val::Str(item) = item.unwrap_if_lazy()? {593								if !first {594									out += &sep;595								}596								first = false;597								out += &item;598							} else {599								create_error_result(crate::Error::RuntimeError("in std.join all items should be strings".into()))?;600							}601						}602603						Val::Str(out.into())604					},605					_ => unreachable!()606				})607			}))?,608			// Faster609			("std", "escapeStringJson") => parse_args!(context, "std.escapeStringJson", args, 1, [610				0, str_: [Val::Str]!!Val::Str, vec![ValType::Str];611			], {612				Val::Str(escape_string_json(&str_).into())613			}),614			// Faster615			("std", "manifestJsonEx") => parse_args!(context, "std.manifestJsonEx", args, 2, [616				0, value, vec![];617				1, indent: [Val::Str]!!Val::Str, vec![ValType::Str];618			], {619				Val::Str(manifest_json_ex(&value, &indent)?.into())620			}),621			(ns, name) => {622				create_error_result(crate::Error::IntristicNotFound(ns.into(), name.into()))?623			}624		},625		Val::Func(f) => {626			let body = || f.evaluate(context, args, tailstrict);627			if tailstrict {628				body()?629			} else {630				push(loc, "function call", body)?631			}632		}633		v => create_error_result(crate::Error::OnlyFunctionsCanBeCalledGot(v.value_type()?))?,634	})635}636637pub fn evaluate(context: Context, expr: &LocExpr) -> Result<Val> {638	use Expr::*;639	let LocExpr(expr, loc) = expr;640	Ok(match &**expr {641		Literal(LiteralType::This) => Val::Obj(642			context643				.this()644				.clone()645				.ok_or_else(|| create_error(crate::Error::CantUseSelfOutsideOfObject))?,646		),647		Literal(LiteralType::Dollar) => Val::Obj(648			context649				.dollar()650				.clone()651				.ok_or_else(|| create_error(crate::Error::NoTopLevelObjectFound))?,652		),653		Literal(LiteralType::True) => Val::Bool(true),654		Literal(LiteralType::False) => Val::Bool(false),655		Literal(LiteralType::Null) => Val::Null,656		Parened(e) => evaluate(context, e)?,657		Str(v) => Val::Str(v.clone()),658		Num(v) => Val::new_checked_num(*v)?,659		BinaryOp(v1, o, v2) => evaluate_binary_op_special(context, &v1, *o, &v2)?,660		UnaryOp(o, v) => evaluate_unary_op(*o, &evaluate(context, v)?)?,661		Var(name) => push(662			loc,663			|| "var".to_owned(),664			|| Ok(Val::Lazy(context.binding(name.clone())?).unwrap_if_lazy()?),665		)?,666		Index(LocExpr(v, _), index) if matches!(&**v, Expr::Literal(LiteralType::Super)) => {667			let name = evaluate(context.clone(), index)?.try_cast_str("object index")?;668			context669				.super_obj()670				.clone()671				.expect("no super found")672				.get_raw(&name, &context.this().clone().expect("no this found"))?673				.expect("value not found")674		}675		Index(value, index) => {676			match (677				evaluate(context.clone(), value)?.unwrap_if_lazy()?,678				evaluate(context, index)?,679			) {680				(Val::Obj(v), Val::Str(s)) => {681					if let Some(v) = v.get(s.clone())? {682						v.unwrap_if_lazy()?683					} else if let Some(Val::Str(n)) = v.get("__intristic_namespace__".into())? {684						Val::Intristic(n, s)685					} else {686						create_error_result(crate::Error::NoSuchField(s))?687					}688				}689				(Val::Obj(_), n) => create_error_result(crate::Error::ValueIndexMustBeTypeGot(690					ValType::Obj,691					ValType::Str,692					n.value_type()?,693				))?,694695				(Val::Arr(v), Val::Num(n)) => {696					if n.fract() > f64::EPSILON {697						create_error_result(crate::Error::FractionalIndex)?698					}699					v.get(n as usize)700						.ok_or_else(|| {701							create_error(crate::Error::ArrayBoundsError(n as usize, v.len()))702						})?703						.clone()704						.unwrap_if_lazy()?705				}706				(Val::Arr(_), Val::Str(n)) => {707					create_error_result(crate::Error::AttemptedIndexAnArrayWithString(n))?708				}709				(Val::Arr(_), n) => create_error_result(crate::Error::ValueIndexMustBeTypeGot(710					ValType::Arr,711					ValType::Num,712					n.value_type()?,713				))?,714715				(Val::Str(s), Val::Num(n)) => Val::Str(716					s.chars()717						.skip(n as usize)718						.take(1)719						.collect::<String>()720						.into(),721				),722				(Val::Str(_), n) => create_error_result(crate::Error::ValueIndexMustBeTypeGot(723					ValType::Str,724					ValType::Num,725					n.value_type()?,726				))?,727728				(v, _) => create_error_result(crate::Error::CantIndexInto(v.value_type()?))?,729			}730		}731		LocalExpr(bindings, returned) => {732			let mut new_bindings: HashMap<Rc<str>, LazyBinding> = HashMap::new();733			let future_context = Context::new_future();734735			let context_creator = context_creator!(736				closure!(clone future_context, |_, _| Ok(future_context.clone().unwrap()))737			);738739			for (k, v) in bindings740				.iter()741				.map(|b| evaluate_binding(b, context_creator.clone()))742			{743				new_bindings.insert(k, v);744			}745746			let context = context747				.extend_unbound(new_bindings, None, None, None)?748				.into_future(future_context);749			evaluate(context, &returned.clone())?750		}751		Arr(items) => {752			let mut out = Vec::with_capacity(items.len());753			for item in items {754				out.push(Val::Lazy(lazy_val!(755					closure!(clone context, clone item, || {756						evaluate(context.clone(), &item)757					})758				)));759			}760			Val::Arr(Rc::new(out))761		}762		ArrComp(expr, compspecs) => Val::Arr(763			// First compspec should be forspec, so no "None" possible here764			Rc::new(evaluate_comp(context, &|ctx| evaluate(ctx, expr), compspecs)?.unwrap()),765		),766		Obj(body) => Val::Obj(evaluate_object(context, body)?),767		ObjExtend(s, t) => evaluate_add_op(768			&evaluate(context.clone(), s)?,769			&Val::Obj(evaluate_object(context, t)?),770		)?,771		Apply(value, args, tailstrict) => evaluate_apply(context, value, args, loc, *tailstrict)?,772		Function(params, body) => evaluate_method(context, params.clone(), body.clone()),773		AssertExpr(AssertStmt(value, msg), returned) => {774			let assertion_result = push(775				&value.1,776				|| "assertion condition".to_owned(),777				|| {778					evaluate(context.clone(), &value)?779						.try_cast_bool("assertion condition should be boolean")780				},781			)?;782			if assertion_result {783				evaluate(context, returned)?784			} else if let Some(msg) = msg {785				create_error_result(crate::Error::AssertionFailed(evaluate(context, msg)?))?786			} else {787				create_error_result(crate::Error::AssertionFailed(Val::Null))?788			}789		}790		Error(e) => push(791			&loc,792			|| "error statement".to_owned(),793			|| {794				create_error_result(crate::Error::RuntimeError(795					evaluate(context, e)?.try_cast_str("error text should be string")?,796				))?797			},798		)?,799		IfElse {800			cond,801			cond_then,802			cond_else,803		} => {804			if evaluate(context.clone(), &cond.0)?805				.try_cast_bool("if condition should be boolean")?806			{807				evaluate(context, cond_then)?808			} else {809				match cond_else {810					Some(v) => evaluate(context, v)?,811					None => Val::Null,812				}813			}814		}815		Import(path) => {816			let mut tmp = loc817				.clone()818				.expect("imports can't be used without loc_data")819				.0;820			let import_location = Rc::make_mut(&mut tmp);821			import_location.pop();822			with_state(|s| s.import_file(&import_location, path))?823		}824		ImportStr(path) => {825			let mut tmp = loc826				.clone()827				.expect("imports can't be used without loc_data")828				.0;829			let import_location = Rc::make_mut(&mut tmp);830			import_location.pop();831			Val::Str(with_state(|s| s.import_file_str(&import_location, path))?)832		}833		Literal(LiteralType::Super) => return create_error_result(crate::Error::StandaloneSuper),834	})835}
modifiedcrates/jrsonnet-evaluator/src/lib.rsdiffbeforeafterboth
--- a/crates/jrsonnet-evaluator/src/lib.rs
+++ b/crates/jrsonnet-evaluator/src/lib.rs
@@ -380,7 +380,7 @@
 #[cfg(test)]
 pub mod tests {
 	use super::Val;
-	use crate::EvaluationState;
+	use crate::{create_error, EvaluationState, primitive_equals};
 	use jrsonnet_parser::*;
 	use std::{path::PathBuf, rc::Rc};
 
@@ -411,11 +411,11 @@
 	fn eval_state_standard() {
 		let state = EvaluationState::default();
 		state.with_stdlib();
-		assert_eq!(
-			state
-				.parse_evaluate_raw(r#"std.assertEqual(std.base64("test"), "dGVzdA==")"#)
-				.unwrap(),
-			Val::Bool(true)
+		assert!(
+			primitive_equals(
+				&state.parse_evaluate_raw(r#"std.assertEqual(std.base64("test"), "dGVzdA==")"#).unwrap(),
+				&Val::Bool(true),
+			).unwrap()
 		);
 	}
 
@@ -445,14 +445,14 @@
 	/// Asserts given code returns `true`
 	macro_rules! assert_eval {
 		($str: expr) => {
-			assert_eq!(eval!($str), Val::Bool(true))
+			assert!(primitive_equals(&eval!($str), &Val::Bool(true)).unwrap())
 		};
 	}
 
 	/// Asserts given code returns `false`
 	macro_rules! assert_eval_neg {
 		($str: expr) => {
-			assert_eq!(eval!($str), Val::Bool(false))
+			assert!(primitive_equals(&eval!($str), &Val::Bool(false)).unwrap())
 		};
 	}
 	macro_rules! assert_json {
@@ -663,9 +663,11 @@
 
 	#[test]
 	fn string_is_string() {
-		assert_eq!(
-			eval!("local arr = 'hello'; (!std.isArray(arr)) && (!std.isString(arr))"),
-			Val::Bool(false)
+		assert!(
+			primitive_equals(
+				&eval!("local arr = 'hello'; (!std.isArray(arr)) && (!std.isString(arr))"),
+				&Val::Bool(false),
+			).unwrap()
 		);
 	}
 
@@ -767,4 +769,10 @@
 			)
 		})
 	}
+
+	#[test]
+	fn equality(){
+		println!("{:?}", jrsonnet_parser::parse("{ x: 1, y: 2 } == { x: 1, y: 2 }", &ParserSettings::default()));
+		assert_eval!("{ x: 1, y: 2 } == { x: 1, y: 2 }")
+	}
 }
modifiedcrates/jrsonnet-evaluator/src/val.rsdiffbeforeafterboth
--- a/crates/jrsonnet-evaluator/src/val.rs
+++ b/crates/jrsonnet-evaluator/src/val.rs
@@ -111,7 +111,7 @@
 	}
 }
 
-#[derive(Debug, PartialEq, Clone)]
+#[derive(Debug, Clone)]
 pub enum Val {
 	Bool(bool),
 	Null,
@@ -212,6 +212,67 @@
 	}
 }
 
+fn is_function_like(val: &Val) -> bool {
+	matches!(val, Val::Func(_) | Val::Intristic(_, _))
+}
+
+/// Implements std.primitiveEquals builtin
+pub fn primitive_equals(val_a: &Val, val_b: &Val) -> Result<bool> {
+	Ok(match (val_a.unwrap_if_lazy()?, val_b.unwrap_if_lazy()?) {
+		(Val::Bool(a), Val::Bool(b)) => a == b,
+		(Val::Null, Val::Null) => true,
+		(Val::Str(a), Val::Str(b)) => a == b,
+		(Val::Num(a), Val::Num(b)) => (a - b).abs() <= f64::EPSILON,
+		(Val::Arr(_), Val::Arr(_)) => create_error_result(Error::RuntimeError(
+			"primitiveEquals operates on primitive types, got array".into(),
+		))?,
+		(Val::Obj(_), Val::Obj(_)) => create_error_result(Error::RuntimeError(
+			"primitiveEquals operates on primitive types, got object".into(),
+		))?,
+		(a, b) if is_function_like(&a) && is_function_like(&b) => create_error_result(
+			Error::RuntimeError("cannot test equality of functions".into()),
+		)?,
+		(_, _) => false,
+	})
+}
+
+/// Native implementation of std.equals
+pub fn equals(val_a: &Val, val_b: &Val) -> Result<bool> {
+	let val_a = val_a.unwrap_if_lazy()?;
+	let val_b = val_b.unwrap_if_lazy()?;
+
+	if val_a.value_type()? != val_b.value_type()? {
+		return Ok(false);
+	}
+	match (val_a, val_b) {
+		// Cant test for ptr equality, because all fields needs to be evaluated
+		(Val::Arr(a), Val::Arr(b)) => {
+			if a.len() != b.len() {
+				return Ok(false);
+			}
+			for (a, b) in a.iter().zip(b.iter()) {
+				if !equals(&a.unwrap_if_lazy()?, &b.unwrap_if_lazy()?)? {
+					return Ok(false);
+				}
+			}
+			Ok(true)
+		}
+		(Val::Obj(a), Val::Obj(b)) => {
+			let fields = a.visible_fields();
+			if fields != b.visible_fields() {
+				return Ok(false);
+			}
+			for field in fields {
+				if !equals(&a.get(field.clone())?.unwrap(), &b.get(field)?.unwrap())? {
+					return Ok(false);
+				}
+			}
+			Ok(true)
+		}
+		(a, b) => Ok(primitive_equals(&a, &b)?),
+	}
+}
+
 pub fn manifest_json_ex(val: &Val, padding: &str) -> Result<String> {
 	let mut out = String::new();
 	manifest_json_ex_buf(val, &mut out, padding, &mut String::new())?;