git.delta.rocks / jrsonnet / refs/commits / 625fbae2cdcf

difftreelog

perf(evaluator) use hashmap for object body

Лач2020-07-01parent: #dcbb761.patch.diff
in: master

4 files changed

modifiedbindings/jsonnet/src/lib.rsdiffbeforeafterboth
--- a/bindings/jsonnet/src/lib.rs
+++ b/bindings/jsonnet/src/lib.rs
@@ -8,7 +8,7 @@
 	alloc::Layout,
 	any::Any,
 	cell::RefCell,
-	collections::BTreeMap,
+	collections::HashMap,
 	ffi::{CStr, CString},
 	fs::File,
 	io::Read,
@@ -191,7 +191,7 @@
 ) {
 	match obj {
 		Val::Obj(old) => {
-			let mut new = BTreeMap::new();
+			let mut new = HashMap::new();
 			new.insert(
 				CStr::from_ptr(name).to_str().unwrap().into(),
 				ObjMember {
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::{13	collections::{BTreeMap, HashMap},14	rc::Rc,15};1617pub fn evaluate_binding(b: &BindSpec, context_creator: ContextCreator) -> (Rc<str>, LazyBinding) {18	let b = b.clone();19	if let Some(params) = &b.params {20		let params = params.clone();21		(22			b.name.clone(),23			LazyBinding::Bindable(Rc::new(move |this, super_obj| {24				Ok(lazy_val!(25					closure!(clone b, clone params, clone context_creator, || Ok(evaluate_method(26						context_creator.0(this.clone(), super_obj.clone())?,27						params.clone(),28						b.value.clone(),29					)))30				))31			})),32		)33	} else {34		(35			b.name.clone(),36			LazyBinding::Bindable(Rc::new(move |this, super_obj| {37				Ok(lazy_val!(closure!(clone context_creator, clone b, ||38					push(&b.value.1, "thunk", ||{39						evaluate(40							context_creator.0(this.clone(), super_obj.clone())?,41							&b.value42						)43					})44				)))45			})),46		)47	}48}4950pub fn evaluate_method(ctx: Context, params: ParamsDesc, body: LocExpr) -> Val {51	Val::Func(FuncDesc { ctx, params, body })52}5354pub fn evaluate_field_name(55	context: Context,56	field_name: &jrsonnet_parser::FieldName,57) -> Result<Option<Rc<str>>> {58	Ok(match field_name {59		jrsonnet_parser::FieldName::Fixed(n) => Some(n.clone()),60		jrsonnet_parser::FieldName::Dyn(expr) => {61			let lazy = evaluate(context, expr)?;62			let value = lazy.unwrap_if_lazy()?;63			if matches!(value, Val::Null) {64				None65			} else {66				Some(value.try_cast_str("dynamic field name")?)67			}68		}69	})70}7172pub fn evaluate_unary_op(op: UnaryOpType, b: &Val) -> Result<Val> {73	Ok(match (op, b) {74		(o, Val::Lazy(l)) => evaluate_unary_op(o, &l.evaluate()?)?,75		(UnaryOpType::Not, Val::Bool(v)) => Val::Bool(!v),76		(UnaryOpType::Minus, Val::Num(n)) => Val::Num(-*n),77		(UnaryOpType::BitNot, Val::Num(n)) => Val::Num(!(*n as i32) as f64),78		(op, o) => create_error_result(Error::UnaryOperatorDoesNotOperateOnType(79			op,80			o.value_type()?,81		))?,82	})83}8485pub(crate) fn evaluate_add_op(a: &Val, b: &Val) -> Result<Val> {86	Ok(match (a, b) {87		(Val::Str(v1), Val::Str(v2)) => Val::Str(((**v1).to_owned() + &v2).into()),8889		// Can't use generic json serialization way, because it depends on number to string concatenation (std.jsonnet:890)90		(Val::Num(n), Val::Str(o)) => Val::Str(format!("{}{}", n, o).into()),91		(Val::Str(o), Val::Num(n)) => Val::Str(format!("{}{}", o, n).into()),9293		(Val::Str(s), o) => Val::Str(format!("{}{}", s, o.clone().into_json(0)?).into()),94		(o, Val::Str(s)) => Val::Str(format!("{}{}", o.clone().into_json(0)?, s).into()),9596		(Val::Obj(v1), Val::Obj(v2)) => Val::Obj(v2.with_super(v1.clone())),97		(Val::Arr(a), Val::Arr(b)) => Val::Arr(Rc::new([&a[..], &b[..]].concat())),98		(Val::Num(v1), Val::Num(v2)) => Val::Num(v1 + v2),99		_ => create_error_result(Error::BinaryOperatorDoesNotOperateOnValues(100			BinaryOpType::Add,101			a.value_type()?,102			b.value_type()?,103		))?,104	})105}106107pub fn evaluate_binary_op_special(108	context: Context,109	a: &LocExpr,110	op: BinaryOpType,111	b: &LocExpr,112) -> Result<Val> {113	Ok(114		match (evaluate(context.clone(), &a)?.unwrap_if_lazy()?, op, b) {115			(Val::Bool(true), BinaryOpType::Or, _o) => Val::Bool(true),116			(Val::Bool(false), BinaryOpType::And, _o) => Val::Bool(false),117			(a, op, eb) => {118				evaluate_binary_op_normal(&a, op, &evaluate(context, eb)?.unwrap_if_lazy()?)?119			}120		},121	)122}123124pub fn evaluate_binary_op_normal(a: &Val, op: BinaryOpType, b: &Val) -> Result<Val> {125	Ok(match (a, op, b) {126		(a, BinaryOpType::Add, b) => evaluate_add_op(a, b)?,127128		(Val::Str(v1), BinaryOpType::Mul, Val::Num(v2)) => Val::Str(v1.repeat(*v2 as usize).into()),129130		// Bool X Bool131		(Val::Bool(a), BinaryOpType::And, Val::Bool(b)) => Val::Bool(*a && *b),132		(Val::Bool(a), BinaryOpType::Or, Val::Bool(b)) => Val::Bool(*a || *b),133134		// Str X Str135		(Val::Str(v1), BinaryOpType::Lt, Val::Str(v2)) => Val::Bool(v1 < v2),136		(Val::Str(v1), BinaryOpType::Gt, Val::Str(v2)) => Val::Bool(v1 > v2),137		(Val::Str(v1), BinaryOpType::Lte, Val::Str(v2)) => Val::Bool(v1 <= v2),138		(Val::Str(v1), BinaryOpType::Gte, Val::Str(v2)) => Val::Bool(v1 >= v2),139140		// Num X Num141		(Val::Num(v1), BinaryOpType::Mul, Val::Num(v2)) => Val::Num(v1 * v2),142		(Val::Num(v1), BinaryOpType::Div, Val::Num(v2)) => {143			if *v2 <= f64::EPSILON {144				create_error_result(crate::Error::DivisionByZero)?145			}146			Val::Num(v1 / v2)147		}148149		(Val::Num(v1), BinaryOpType::Sub, Val::Num(v2)) => Val::Num(v1 - v2),150151		(Val::Num(v1), BinaryOpType::Lt, Val::Num(v2)) => Val::Bool(v1 < v2),152		(Val::Num(v1), BinaryOpType::Gt, Val::Num(v2)) => Val::Bool(v1 > v2),153		(Val::Num(v1), BinaryOpType::Lte, Val::Num(v2)) => Val::Bool(v1 <= v2),154		(Val::Num(v1), BinaryOpType::Gte, Val::Num(v2)) => Val::Bool(v1 >= v2),155156		(Val::Num(v1), BinaryOpType::BitAnd, Val::Num(v2)) => {157			Val::Num(((*v1 as i32) & (*v2 as i32)) as f64)158		}159		(Val::Num(v1), BinaryOpType::BitOr, Val::Num(v2)) => {160			Val::Num(((*v1 as i32) | (*v2 as i32)) as f64)161		}162		(Val::Num(v1), BinaryOpType::BitXor, Val::Num(v2)) => {163			Val::Num(((*v1 as i32) ^ (*v2 as i32)) as f64)164		}165		(Val::Num(v1), BinaryOpType::Lhs, Val::Num(v2)) => {166			Val::Num(((*v1 as i32) << (*v2 as i32)) as f64)167		}168		(Val::Num(v1), BinaryOpType::Rhs, Val::Num(v2)) => {169			Val::Num(((*v1 as i32) >> (*v2 as i32)) as f64)170		}171172		_ => create_error_result(Error::BinaryOperatorDoesNotOperateOnValues(173			op,174			a.value_type()?,175			b.value_type()?,176		))?,177	})178}179180future_wrapper!(HashMap<Rc<str>, LazyBinding>, FutureNewBindings);181future_wrapper!(ObjValue, FutureObjValue);182183pub fn evaluate_comp<T>(184	context: Context,185	value: &impl Fn(Context) -> Result<T>,186	specs: &[CompSpec],187) -> Result<Option<Vec<T>>> {188	Ok(match specs.get(0) {189		None => Some(vec![value(context)?]),190		Some(CompSpec::IfSpec(IfSpecData(cond))) => {191			if evaluate(context.clone(), &cond)?.try_cast_bool("if spec")? {192				evaluate_comp(context, value, &specs[1..])?193			} else {194				None195			}196		}197		Some(CompSpec::ForSpec(ForSpecData(var, expr))) => {198			match evaluate(context.clone(), &expr)?.unwrap_if_lazy()? {199				Val::Arr(list) => {200					let mut out = Vec::new();201					for item in list.iter() {202						let item = item.unwrap_if_lazy()?;203						out.push(evaluate_comp(204							context.with_var(var.clone(), item.clone())?,205							value,206							&specs[1..],207						)?);208					}209					Some(out.into_iter().flatten().flatten().collect())210				}211				_ => create_error_result(Error::InComprehensionCanOnlyIterateOverArray)?,212			}213		}214	})215}216217pub fn evaluate_member_list_object(context: Context, members: &[Member]) -> Result<ObjValue> {218	let new_bindings = FutureNewBindings::new();219	let future_this = FutureObjValue::new();220	let context_creator = context_creator!(221		closure!(clone context, clone new_bindings, |this: Option<ObjValue>, super_obj: Option<ObjValue>| {222			Ok(context.extend_unbound(223				new_bindings.clone().unwrap(),224				context.dollar().clone().or_else(||this.clone()),225				Some(this.unwrap()),226				super_obj227			)?)228		})229	);230	{231		let mut bindings: HashMap<Rc<str>, LazyBinding> = HashMap::new();232		for (n, b) in members233			.iter()234			.filter_map(|m| match m {235				Member::BindStmt(b) => Some(b.clone()),236				_ => None,237			})238			.map(|b| evaluate_binding(&b, context_creator.clone()))239		{240			bindings.insert(n, b);241		}242		new_bindings.fill(bindings);243	}244245	let mut new_members = BTreeMap::new();246	for member in members.iter() {247		match member {248			Member::Field(FieldMember {249				name,250				plus,251				params: None,252				visibility,253				value,254			}) => {255				let name = evaluate_field_name(context.clone(), &name)?;256				if name.is_none() {257					continue;258				}259				let name = name.unwrap();260				new_members.insert(261					name.clone(),262					ObjMember {263						add: *plus,264						visibility: *visibility,265						invoke: LazyBinding::Bindable(Rc::new(266							closure!(clone name, clone value, clone context_creator, |this, super_obj| {267								Ok(LazyVal::new_resolved(push(&value.1, "object field", ||{268									let context = context_creator.0(this, super_obj)?;269									evaluate(270										context,271										&value,272									)273								})?))274							}),275						)),276					},277				);278			}279			Member::Field(FieldMember {280				name,281				params: Some(params),282				value,283				..284			}) => {285				let name = evaluate_field_name(context.clone(), &name)?;286				if name.is_none() {287					continue;288				}289				let name = name.unwrap();290				new_members.insert(291					name,292					ObjMember {293						add: false,294						visibility: Visibility::Hidden,295						invoke: LazyBinding::Bindable(Rc::new(296							closure!(clone value, clone context_creator, clone params, |this, super_obj| {297								// TODO: Assert298								Ok(LazyVal::new_resolved(evaluate_method(299									context_creator.0(this, super_obj)?,300									params.clone(),301									value.clone(),302								)))303							}),304						)),305					},306				);307			}308			Member::BindStmt(_) => {}309			Member::AssertStmt(_) => {}310		}311	}312	Ok(future_this.fill(ObjValue::new(None, Rc::new(new_members))))313}314315pub fn evaluate_object(context: Context, object: &ObjBody) -> Result<ObjValue> {316	Ok(match object {317		ObjBody::MemberList(members) => evaluate_member_list_object(context, &members)?,318		ObjBody::ObjComp(obj) => {319			let future_this = FutureObjValue::new();320			let mut new_members = BTreeMap::new();321			for (k, v) in evaluate_comp(322				context.clone(),323				&|ctx| {324					let new_bindings = FutureNewBindings::new();325					let context_creator = context_creator!(326						closure!(clone context, clone new_bindings, |this: Option<ObjValue>, super_obj: Option<ObjValue>| {327							Ok(context.extend_unbound(328								new_bindings.clone().unwrap(),329								context.dollar().clone().or_else(||this.clone()),330								None,331								super_obj332							)?)333						})334					);335					let mut bindings: HashMap<Rc<str>, LazyBinding> = HashMap::new();336					for (n, b) in obj337						.pre_locals338						.iter()339						.chain(obj.post_locals.iter())340						.map(|b| evaluate_binding(b, context_creator.clone()))341					{342						bindings.insert(n, b);343					}344					let bindings = new_bindings.fill(bindings);345					let ctx = ctx.extend_unbound(bindings, None, None, None)?;346					let key = evaluate(ctx.clone(), &obj.key)?;347					let value = LazyBinding::Bindable(Rc::new(348						closure!(clone ctx, clone obj.value, |this, _super_obj| {349							Ok(LazyVal::new_resolved(evaluate(ctx.extend(HashMap::new(), None, this, None)?, &value)?))350						}),351					));352353					Ok((key, value))354				},355				&obj.compspecs,356			)?357			.unwrap()358			{359				match k {360					Val::Null => {}361					Val::Str(n) => {362						new_members.insert(363							n,364							ObjMember {365								add: false,366								visibility: Visibility::Normal,367								invoke: v,368							},369						);370					}371					v => create_error_result(Error::FieldMustBeStringGot(v.value_type()?))?,372				}373			}374375			future_this.fill(ObjValue::new(None, Rc::new(new_members)))376		}377	})378}379380/// Extracts code block and disables inlining for them381/// Fixes WASM to java bytecode compilation failing because of very large method382macro_rules! noinline {383	($e:expr) => {384		(#[inline(never)]385		move || $e)()386	};387}388389pub fn evaluate_apply(390	context: Context,391	value: &LocExpr,392	args: &ArgsDesc,393	loc: &Option<ExprLocation>,394	tailstrict: bool,395) -> Result<Val> {396	let lazy = evaluate(context.clone(), value)?;397	let value = lazy.unwrap_if_lazy()?;398	Ok(match value {399		Val::Intristic(ns, name) => match (&ns as &str, &name as &str) {400			// arr/string/function401			("std", "length") => noinline!(parse_args!(context, "std.length", args, 1, [402				0, x: [Val::Str|Val::Arr|Val::Obj], vec![ValType::Str, ValType::Arr, ValType::Obj];403			], {404				Ok(match x {405					Val::Str(n) => Val::Num(n.chars().count() as f64),406					Val::Arr(i) => Val::Num(i.len() as f64),407					Val::Obj(o) => Val::Num(408						o.fields_visibility()409							.into_iter()410							.filter(|(_k, v)| *v)411							.count() as f64,412					),413					_ => unreachable!(),414				})415			}))?,416			// any417			("std", "type") => parse_args!(context, "std.type", args, 1, [418				0, x, vec![];419			], {420				Val::Str(x.value_type()?.name().into())421			}),422			// length, idx=>any423			("std", "makeArray") => noinline!(parse_args!(context, "std.makeArray", args, 2, [424				0, sz: [Val::Num]!!Val::Num, vec![ValType::Num];425				1, func: [Val::Func]!!Val::Func, vec![ValType::Func];426			], {427				assert!(sz >= 0.0);428				let mut out = Vec::with_capacity(sz as usize);429				for i in 0..sz as usize {430					out.push(func.evaluate_values(431						Context::new(),432						&[Val::Num(i as f64)]433					)?)434				}435				Ok(Val::Arr(Rc::new(out)))436			}))?,437			// string438			("std", "codepoint") => parse_args!(context, "std.codepoint", args, 1, [439				0, str: [Val::Str]!!Val::Str, vec![ValType::Str];440			], {441				assert!(442					str.chars().count() == 1,443					"std.codepoint should receive single char string"444				);445				Val::Num(str.chars().take(1).next().unwrap() as u32 as f64)446			}),447			// object, includeHidden448			("std", "objectFieldsEx") => {449				noinline!(parse_args!(context, "std.objectFieldsEx",args, 2, [450					0, obj: [Val::Obj]!!Val::Obj, vec![ValType::Obj];451					1, inc_hidden: [Val::Bool]!!Val::Bool, vec![ValType::Bool];452				], {453					Ok(Val::Arr(Rc::new(454						obj.fields_visibility()455							.into_iter()456							.filter(|(_k, v)| *v || inc_hidden)457							.map(|(k, _v)| Val::Str(k))458							.collect(),459					)))460				}))?461			}462			// object, field, includeHidden463			("std", "objectHasEx") => parse_args!(context, "std.objectHasEx", args, 3, [464				0, obj: [Val::Obj]!!Val::Obj, vec![ValType::Obj];465				1, f: [Val::Str]!!Val::Str, vec![ValType::Str];466				2, inc_hidden: [Val::Bool]!!Val::Bool, vec![ValType::Bool];467			], {468				Val::Bool(469					obj.fields_visibility()470						.into_iter()471						.filter(|(_k, v)| *v || inc_hidden)472						.any(|(k, _v)| *k == *f),473				)474			}),475			("std", "primitiveEquals") => parse_args!(context, "std.primitiveEquals", args, 2, [476				0, a, vec![];477				1, b, vec![];478			], {479				Val::Bool(a == b)480			}),481			("std", "modulo") => parse_args!(context, "std.modulo", args, 2, [482				0, a: [Val::Num]!!Val::Num, vec![ValType::Num];483				1, b: [Val::Num]!!Val::Num, vec![ValType::Num];484			], {485				Val::Num(a % b)486			}),487			("std", "floor") => parse_args!(context, "std.floor", args, 1, [488				0, x: [Val::Num]!!Val::Num, vec![ValType::Num];489			], {490				Val::Num(x.floor())491			}),492			("std", "trace") => parse_args!(context, "std.trace", args, 2, [493				0, str: [Val::Str]!!Val::Str, vec![ValType::Str];494				1, rest, vec![];495			], {496				eprint!("TRACE: ");497				if let Some(loc) = loc {498					with_state(|s|{499						let locs = s.map_source_locations(&loc.0, &[loc.1]);500						eprint!("{}:{} ", loc.0.display(), locs[0].line);501					});502				}503				eprintln!("{}", str);504				rest505			}),506			("std", "pow") => parse_args!(context, "std.modulo", args, 2, [507				0, x: [Val::Num]!!Val::Num, vec![ValType::Num];508				1, n: [Val::Num]!!Val::Num, vec![ValType::Num];509			], {510				Val::Num(x.powf(n))511			}),512			("std", "extVar") => parse_args!(context, "std.extVar", args, 2, [513				0, x: [Val::Str]!!Val::Str, vec![ValType::Str];514			], {515				with_state(|s| s.settings().ext_vars.get(&x).cloned()).ok_or_else(516					|| create_error(crate::Error::UndefinedExternalVariable(x)),517				)?518			}),519			("std", "filter") => noinline!(parse_args!(context, "std.filter", args, 2, [520				0, func: [Val::Func]!!Val::Func, vec![ValType::Func];521				1, arr: [Val::Arr]!!Val::Arr, vec![ValType::Arr];522			], {523				Ok(Val::Arr(Rc::new(524					arr.iter()525						.cloned()526						.filter(|e| {527							func528								.evaluate_values(context.clone(), &[e.clone()])529								.unwrap()530								.try_cast_bool("filter predicate")531								.unwrap()532						})533						.collect(),534				)))535			}))?,536			("std", "char") => parse_args!(context, "std.char", args, 1, [537				0, n: [Val::Num]!!Val::Num, vec![ValType::Num];538			], {539				let mut out = String::new();540				out.push(std::char::from_u32(n as u32).unwrap());541				Val::Str(out.into())542			}),543			("std", "encodeUTF8") => parse_args!(context, "std.encodeUtf8", args, 1, [544				0, str: [Val::Str]!!Val::Str, vec![ValType::Str];545			], {546				Val::Arr(Rc::new(str.bytes().map(|b| Val::Num(b as f64)).collect()))547			}),548			("std", "md5") => noinline!(parse_args!(context, "std.md5", args, 1, [549				0, str: [Val::Str]!!Val::Str, vec![ValType::Str];550			], {551				Ok(Val::Str(format!("{:x}", md5::compute(&str.as_bytes())).into()))552			}))?,553			// faster554			("std", "join") => noinline!(parse_args!(context, "std.join", args, 2, [555				0, sep: [Val::Str|Val::Arr], vec![ValType::Str, ValType::Arr];556				1, arr: [Val::Arr]!!Val::Arr, vec![ValType::Arr];557			], {558				Ok(match sep {559					Val::Arr(joiner_items) => {560						let mut out = Vec::new();561562						let mut first = true;563						for item in arr.iter().cloned() {564							if let Val::Arr(items) = item.unwrap_if_lazy()? {565								if !first {566									out.reserve(joiner_items.len());567									out.extend(joiner_items.iter().cloned());568								}569								first = false;570								out.reserve(items.len());571								out.extend(items.iter().cloned());572							} else {573								create_error_result(crate::Error::RuntimeError("in std.join all items should be arrays".into()))?;574							}575						}576577						Val::Arr(Rc::new(out))578					},579					Val::Str(sep) => {580						let mut out = String::new();581582						let mut first = true;583						for item in arr.iter().cloned() {584							if let Val::Str(item) = item.unwrap_if_lazy()? {585								if !first {586									out += &sep;587								}588								first = false;589								out += &item;590							} else {591								create_error_result(crate::Error::RuntimeError("in std.join all items should be strings".into()))?;592							}593						}594595						Val::Str(out.into())596					},597					_ => unreachable!()598				})599			}))?,600			// Faster601			("std", "escapeStringJson") => parse_args!(context, "std.escapeStringJson", args, 1, [602				0, str_: [Val::Str]!!Val::Str, vec![ValType::Str];603			], {604				Val::Str(escape_string_json(&str_).into())605			}),606			// Faster607			("std", "manifestJsonEx") => parse_args!(context, "std.manifestJsonEx", args, 2, [608				0, value, vec![];609				1, indent: [Val::Str]!!Val::Str, vec![ValType::Str];610			], {611				Val::Str(manifest_json_ex(&value, &indent)?.into())612			}),613			(ns, name) => {614				create_error_result(crate::Error::IntristicNotFound(ns.into(), name.into()))?615			}616		},617		Val::Func(f) => {618			let body = || f.evaluate(context, args, tailstrict);619			if tailstrict {620				body()?621			} else {622				push(loc, "function call", body)?623			}624		}625		v => create_error_result(crate::Error::OnlyFunctionsCanBeCalledGot(v.value_type()?))?,626	})627}628629pub fn evaluate(context: Context, expr: &LocExpr) -> Result<Val> {630	use Expr::*;631	let LocExpr(expr, loc) = expr;632	Ok(match &**expr {633		Literal(LiteralType::This) => Val::Obj(634			context635				.this()636				.clone()637				.ok_or_else(|| create_error(crate::Error::CantUseSelfOutsideOfObject))?,638		),639		Literal(LiteralType::Dollar) => Val::Obj(640			context641				.dollar()642				.clone()643				.ok_or_else(|| create_error(crate::Error::NoTopLevelObjectFound))?,644		),645		Literal(LiteralType::True) => Val::Bool(true),646		Literal(LiteralType::False) => Val::Bool(false),647		Literal(LiteralType::Null) => Val::Null,648		Parened(e) => evaluate(context, e)?,649		Str(v) => Val::Str(v.clone()),650		Num(v) => Val::Num(*v),651		BinaryOp(v1, o, v2) => evaluate_binary_op_special(context, &v1, *o, &v2)?,652		UnaryOp(o, v) => evaluate_unary_op(*o, &evaluate(context, v)?)?,653		Var(name) => push(loc, "var", || {654			Ok(Val::Lazy(context.binding(name.clone())?).unwrap_if_lazy()?)655		})?,656		Index(LocExpr(v, _), index) if matches!(&**v, Expr::Literal(LiteralType::Super)) => {657			let name = evaluate(context.clone(), index)?.try_cast_str("object index")?;658			context659				.super_obj()660				.clone()661				.expect("no super found")662				.get_raw(&name, &context.this().clone().expect("no this found"))?663				.expect("value not found")664		}665		Index(value, index) => {666			match (667				evaluate(context.clone(), value)?.unwrap_if_lazy()?,668				evaluate(context, index)?,669			) {670				(Val::Obj(v), Val::Str(s)) => {671					if let Some(v) = v.get(s.clone())? {672						v.unwrap_if_lazy()?673					} else if let Some(Val::Str(n)) = v.get("__intristic_namespace__".into())? {674						Val::Intristic(n, s)675					} else {676						create_error_result(crate::Error::NoSuchField(s))?677					}678				}679				(Val::Obj(_), n) => create_error_result(crate::Error::ValueIndexMustBeTypeGot(680					ValType::Obj,681					ValType::Str,682					n.value_type()?,683				))?,684685				(Val::Arr(v), Val::Num(n)) => {686					if n.fract() > f64::EPSILON {687						create_error_result(crate::Error::FractionalIndex)?688					}689					v.get(n as usize)690						.ok_or_else(|| {691							create_error(crate::Error::ArrayBoundsError(n as usize, v.len()))692						})?693						.clone()694						.unwrap_if_lazy()?695				}696				(Val::Arr(_), Val::Str(n)) => {697					create_error_result(crate::Error::AttemptedIndexAnArrayWithString(n))?698				}699				(Val::Arr(_), n) => create_error_result(crate::Error::ValueIndexMustBeTypeGot(700					ValType::Arr,701					ValType::Num,702					n.value_type()?,703				))?,704705				(Val::Str(s), Val::Num(n)) => Val::Str(706					s.chars()707						.skip(n as usize)708						.take(1)709						.collect::<String>()710						.into(),711				),712				(Val::Str(_), n) => create_error_result(crate::Error::ValueIndexMustBeTypeGot(713					ValType::Str,714					ValType::Num,715					n.value_type()?,716				))?,717718				(v, _) => create_error_result(crate::Error::CantIndexInto(v.value_type()?))?,719			}720		}721		LocalExpr(bindings, returned) => {722			let mut new_bindings: HashMap<Rc<str>, LazyBinding> = HashMap::new();723			let future_context = Context::new_future();724725			let context_creator = context_creator!(726				closure!(clone future_context, |_, _| Ok(future_context.clone().unwrap()))727			);728729			for (k, v) in bindings730				.iter()731				.map(|b| evaluate_binding(b, context_creator.clone()))732			{733				new_bindings.insert(k, v);734			}735736			let context = context737				.extend_unbound(new_bindings, None, None, None)?738				.into_future(future_context);739			evaluate(context, &returned.clone())?740		}741		Arr(items) => {742			let mut out = Vec::with_capacity(items.len());743			for item in items {744				out.push(Val::Lazy(lazy_val!(745					closure!(clone context, clone item, || {746						evaluate(context.clone(), &item)747					})748				)));749			}750			Val::Arr(Rc::new(out))751		}752		ArrComp(expr, compspecs) => Val::Arr(753			// First compspec should be forspec, so no "None" possible here754			Rc::new(evaluate_comp(context, &|ctx| evaluate(ctx, expr), compspecs)?.unwrap()),755		),756		Obj(body) => Val::Obj(evaluate_object(context, body)?),757		ObjExtend(s, t) => evaluate_add_op(758			&evaluate(context.clone(), s)?,759			&Val::Obj(evaluate_object(context, t)?),760		)?,761		Apply(value, args, tailstrict) => evaluate_apply(context, value, args, loc, *tailstrict)?,762		Function(params, body) => evaluate_method(context, params.clone(), body.clone()),763		AssertExpr(AssertStmt(value, msg), returned) => {764			let assertion_result = push(&value.1, "assertion condition", || {765				evaluate(context.clone(), &value)?766					.try_cast_bool("assertion condition should be boolean")767			})?;768			if assertion_result {769				evaluate(context, returned)?770			} else if let Some(msg) = msg {771				create_error_result(crate::Error::AssertionFailed(evaluate(context, msg)?))?772			} else {773				create_error_result(crate::Error::AssertionFailed(Val::Null))?774			}775		}776		Error(e) => create_error_result(crate::Error::RuntimeError(777			evaluate(context, e)?.try_cast_str("error text should be string")?,778		))?,779		IfElse {780			cond,781			cond_then,782			cond_else,783		} => {784			if evaluate(context.clone(), &cond.0)?785				.try_cast_bool("if condition should be boolean")?786			{787				evaluate(context, cond_then)?788			} else {789				match cond_else {790					Some(v) => evaluate(context, v)?,791					None => Val::Null,792				}793			}794		}795		Import(path) => {796			let mut tmp = loc797				.clone()798				.expect("imports can't be used without loc_data")799				.0;800			let import_location = Rc::make_mut(&mut tmp);801			import_location.pop();802			with_state(|s| s.import_file(&import_location, path))?803		}804		ImportStr(path) => {805			let mut tmp = loc806				.clone()807				.expect("imports can't be used without loc_data")808				.0;809			let import_location = Rc::make_mut(&mut tmp);810			import_location.pop();811			Val::Str(with_state(|s| s.import_file_str(&import_location, path))?)812		}813		Literal(LiteralType::Super) => return create_error_result(crate::Error::StandaloneSuper),814	})815}
modifiedcrates/jrsonnet-evaluator/src/obj.rsdiffbeforeafterboth
--- a/crates/jrsonnet-evaluator/src/obj.rs
+++ b/crates/jrsonnet-evaluator/src/obj.rs
@@ -1,12 +1,7 @@
 use crate::{evaluate_add_op, LazyBinding, Result, Val};
 use indexmap::IndexMap;
-use jrsonnet_parser::Visibility;
-use std::{
-	cell::RefCell,
-	collections::{BTreeMap, HashMap},
-	fmt::Debug,
-	rc::Rc,
-};
+use jrsonnet_parser::{ExprLocation, Visibility};
+use std::{cell::RefCell, collections::HashMap, fmt::Debug, rc::Rc};
 
 #[derive(Debug)]
 pub struct ObjMember {
@@ -18,7 +13,7 @@
 #[derive(Debug)]
 pub struct ObjValueInternals {
 	super_obj: Option<ObjValue>,
-	this_entries: Rc<BTreeMap<Rc<str>, ObjMember>>,
+	this_entries: Rc<HashMap<Rc<str>, ObjMember>>,
 	value_cache: RefCell<HashMap<Rc<str>, Val>>,
 }
 #[derive(Clone)]
@@ -44,7 +39,7 @@
 impl ObjValue {
 	pub fn new(
 		super_obj: Option<ObjValue>,
-		this_entries: Rc<BTreeMap<Rc<str>, ObjMember>>,
+		this_entries: Rc<HashMap<Rc<str>, ObjMember>>,
 	) -> ObjValue {
 		ObjValue(Rc::new(ObjValueInternals {
 			super_obj,
@@ -53,7 +48,7 @@
 		}))
 	}
 	pub fn new_empty() -> ObjValue {
-		Self::new(None, Rc::new(BTreeMap::new()))
+		Self::new(None, Rc::new(HashMap::new()))
 	}
 	pub fn with_super(&self, super_obj: ObjValue) -> ObjValue {
 		match &self.0.super_obj {
modifiedcrates/jrsonnet-evaluator/src/val.rsdiffbeforeafterboth
--- a/crates/jrsonnet-evaluator/src/val.rs
+++ b/crates/jrsonnet-evaluator/src/val.rs
@@ -246,7 +246,8 @@
 		}
 		Val::Obj(obj) => {
 			buf.push_str("{\n");
-			let fields = obj.visible_fields();
+			let mut fields = obj.visible_fields();
+			fields.sort();
 			if !fields.is_empty() {
 				let old_len = cur_padding.len();
 				cur_padding.push_str(padding);