git.delta.rocks / jrsonnet / refs/commits / 0b0d703c6d05

difftreelog

refactor do not desugar mod/slice

Yaroslav Bolyukin2021-07-04parent: #53ec857.patch.diff
in: master

7 files changed

modifiedcrates/jrsonnet-evaluator/src/builtin/mod.rsdiffbeforeafterboth
--- a/crates/jrsonnet-evaluator/src/builtin/mod.rs
+++ b/crates/jrsonnet-evaluator/src/builtin/mod.rs
@@ -1,13 +1,14 @@
 use crate::{
 	equals,
 	error::{Error::*, Result},
+	operator::evaluate_mod_op,
 	parse_args, primitive_equals, push, throw, with_state, ArrValue, Context, EvaluationState,
-	FuncVal, LazyVal, Val,
+	FuncVal, IndexableVal, LazyVal, Val,
 };
 use format::{format_arr, format_obj};
 use jrsonnet_gc::Gc;
 use jrsonnet_interner::IStr;
-use jrsonnet_parser::{ArgsDesc, BinaryOpType, ExprLocation};
+use jrsonnet_parser::{ArgsDesc, ExprLocation};
 use jrsonnet_types::ty;
 use std::{collections::HashMap, path::PathBuf, rc::Rc};
 
@@ -20,7 +21,7 @@
 pub mod manifest;
 pub mod sort;
 
-fn std_format(str: IStr, vals: Val) -> Result<Val> {
+pub fn std_format(str: IStr, vals: Val) -> Result<Val> {
 	push(
 		Some(&ExprLocation(Rc::from(PathBuf::from("std.jsonnet")), 0, 0)),
 		|| format!("std.format of {}", str),
@@ -34,6 +35,38 @@
 	)
 }
 
+pub fn std_slice(
+	indexable: IndexableVal,
+	index: Option<usize>,
+	end: Option<usize>,
+	step: Option<usize>,
+) -> Result<Val> {
+	let index = index.unwrap_or(0);
+	let end = end.unwrap_or_else(|| match &indexable {
+		IndexableVal::Str(_) => usize::MAX,
+		IndexableVal::Arr(v) => v.len(),
+	});
+	let step = step.unwrap_or(1);
+	match &indexable {
+		IndexableVal::Str(s) => Ok(Val::Str(
+			(s.chars()
+				.skip(index)
+				.take(end - index)
+				.step_by(step)
+				.collect::<String>())
+			.into(),
+		)),
+		IndexableVal::Arr(arr) => Ok(Val::Arr(
+			(arr.iter()
+				.skip(index)
+				.take(end - index)
+				.step_by(step)
+				.collect::<Result<Vec<Val>>>()?)
+			.into(),
+		)),
+	}
+}
+
 type Builtin = fn(context: Context, loc: Option<&ExprLocation>, args: &ArgsDesc) -> Result<Val>;
 
 type BuiltinsType = HashMap<Box<str>, Builtin>;
@@ -188,34 +221,12 @@
 		2, end: ty!((number | null));
 		3, step: ty!((number | null));
 	], {
-		let index = match index {
-			Val::Num(v) => v as usize,
-			Val::Null => 0,
-			_ => unreachable!(),
-		};
-		let end = match end {
-			Val::Num(v) => v as usize,
-			Val::Null => match &indexable {
-				Val::Str(s) => s.chars().count(),
-				Val::Arr(v) => v.len(),
-				_ => unreachable!()
-			},
-			_ => unreachable!()
-		};
-		let step = match step {
-			Val::Num(v) => v as usize,
-			Val::Null => 1,
-			_ => unreachable!()
-		};
-		match &indexable {
-			Val::Str(s) => {
-				Ok(Val::Str((s.chars().skip(index).take(end-index).step_by(step).collect::<String>()).into()))
-			}
-			Val::Arr(arr) => {
-				Ok(Val::Arr((arr.iter().skip(index).take(end-index).step_by(step).collect::<Result<Vec<Val>>>()?).into()))
-			}
-			_ => unreachable!()
-		}
+		std_slice(
+			indexable.to_indexable()?,
+			index.try_cast_nullable_num("index")?.map(|v| v as usize),
+			end.try_cast_nullable_num("end")?.map(|v| v as usize),
+			step.try_cast_nullable_num("step")?.map(|v| v as usize),
+		)
 	})
 }
 
@@ -257,11 +268,7 @@
 		0, a: ty!((number | string));
 		1, b: ty!(any);
 	], {
-		match (a, b) {
-			(Val::Num(a), Val::Num(b)) => Ok(Val::Num(a % b)),
-			(Val::Str(str), vals) => std_format(str, vals),
-			(a, b) => throw!(BinaryOperatorDoesNotOperateOnValues(BinaryOpType::Mod, a.value_type(), b.value_type()))
-		}
+		evaluate_mod_op(&a, &b)
 	})
 }
 
modifiedcrates/jrsonnet-evaluator/src/error.rsdiffbeforeafterboth
--- a/crates/jrsonnet-evaluator/src/error.rs
+++ b/crates/jrsonnet-evaluator/src/error.rs
@@ -73,6 +73,8 @@
 	ValueIndexMustBeTypeGot(ValType, ValType, ValType),
 	#[error("cant index into {0}")]
 	CantIndexInto(ValType),
+	#[error("{0} is not indexable")]
+	ValueIsNotIndexable(ValType),
 
 	#[error("super can't be used standalone")]
 	StandaloneSuper,
modifiedcrates/jrsonnet-evaluator/src/evaluate/mod.rsdiffbeforeafterboth
before · 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, ObjValue, ObjValueBuilder, 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,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 builder = ObjValueBuilder::new();258	for member in members.iter() {259		match member {260			Member::Field(FieldMember {261				name,262				plus,263				params: None,264				visibility,265				value,266			}) => {267				let name = evaluate_field_name(context.clone(), name)?;268				if name.is_none() {269					continue;270				}271				let name = name.unwrap();272273				#[derive(Trace)]274				#[trivially_drop]275				struct ObjMemberBinding {276					context_creator: ContextCreator,277					value: LocExpr,278					name: IStr,279				}280				impl Bindable for ObjMemberBinding {281					fn bind(282						&self,283						this: Option<ObjValue>,284						super_obj: Option<ObjValue>,285					) -> Result<LazyVal> {286						Ok(LazyVal::new_resolved(evaluate_named(287							self.context_creator.create(this, super_obj)?,288							&self.value,289							self.name.clone(),290						)?))291					}292				}293				builder294					.member(name.clone())295					.with_add(*plus)296					.with_visibility(*visibility)297					.with_location(value.1.clone())298					.bindable(Box::new(ObjMemberBinding {299						context_creator: context_creator.clone(),300						value: value.clone(),301						name,302					}));303			}304			Member::Field(FieldMember {305				name,306				params: Some(params),307				value,308				..309			}) => {310				let name = evaluate_field_name(context.clone(), name)?;311				if name.is_none() {312					continue;313				}314				let name = name.unwrap();315				#[derive(Trace)]316				#[trivially_drop]317				struct ObjMemberBinding {318					context_creator: ContextCreator,319					value: LocExpr,320					params: ParamsDesc,321					name: IStr,322				}323				impl Bindable for ObjMemberBinding {324					fn bind(325						&self,326						this: Option<ObjValue>,327						super_obj: Option<ObjValue>,328					) -> Result<LazyVal> {329						Ok(LazyVal::new_resolved(evaluate_method(330							self.context_creator.create(this, super_obj)?,331							self.name.clone(),332							self.params.clone(),333							self.value.clone(),334						)))335					}336				}337				builder338					.member(name.clone())339					.hide()340					.with_location(value.1.clone())341					.binding(LazyBinding::Bindable(Gc::new(Box::new(ObjMemberBinding {342						context_creator: context_creator.clone(),343						value: value.clone(),344						params: params.clone(),345						name,346					}))));347			}348			Member::BindStmt(_) => {}349			Member::AssertStmt(stmt) => {350				#[derive(Trace)]351				#[trivially_drop]352				struct ObjectAssert {353					context_creator: ContextCreator,354					assert: AssertStmt,355				}356				impl ObjectAssertion for ObjectAssert {357					fn run(358						&self,359						this: Option<ObjValue>,360						super_obj: Option<ObjValue>,361					) -> Result<()> {362						let ctx = self.context_creator.create(this, super_obj)?;363						evaluate_assert(ctx, &self.assert)364					}365				}366				builder.assert(Box::new(ObjectAssert {367					context_creator: context_creator.clone(),368					assert: stmt.clone(),369				}));370			}371		}372	}373	let this = builder.build();374	future_this.fill(this.clone());375	Ok(this)376}377378pub fn evaluate_object(context: Context, object: &ObjBody) -> Result<ObjValue> {379	Ok(match object {380		ObjBody::MemberList(members) => evaluate_member_list_object(context, members)?,381		ObjBody::ObjComp(obj) => {382			let future_this = FutureWrapper::new();383			let mut builder = ObjValueBuilder::new();384			evaluate_comp(context.clone(), &obj.compspecs, &mut |ctx| {385				let new_bindings = FutureWrapper::new();386				let context_creator = ContextCreator(context.clone(), new_bindings.clone());387				let mut bindings: FxHashMap<IStr, LazyBinding> =388					FxHashMap::with_capacity_and_hasher(389						obj.pre_locals.len() + obj.post_locals.len(),390						BuildHasherDefault::default(),391					);392				for (n, b) in obj393					.pre_locals394					.iter()395					.chain(obj.post_locals.iter())396					.map(|b| evaluate_binding(b, context_creator.clone()))397				{398					bindings.insert(n, b);399				}400				new_bindings.fill(bindings.clone());401				let ctx = ctx.extend_unbound(bindings, None, None, None)?;402				let key = evaluate(ctx.clone(), &obj.key)?;403404				match key {405					Val::Null => {}406					Val::Str(n) => {407						#[derive(Trace)]408						#[trivially_drop]409						struct ObjCompBinding {410							context: Context,411							value: LocExpr,412						}413						impl Bindable for ObjCompBinding {414							fn bind(415								&self,416								this: Option<ObjValue>,417								_super_obj: Option<ObjValue>,418							) -> Result<LazyVal> {419								Ok(LazyVal::new_resolved(evaluate(420									self.context.clone().extend(421										FxHashMap::default(),422										None,423										this,424										None,425									),426									&self.value,427								)?))428							}429						}430						builder431							.member(n)432							.with_location(obj.value.1.clone())433							.bindable(Box::new(ObjCompBinding {434								context: ctx,435								value: obj.value.clone(),436							}));437					}438					v => throw!(FieldMustBeStringGot(v.value_type())),439				}440441				Ok(())442			})?;443444			let this = builder.build();445			future_this.fill(this.clone());446			this447		}448	})449}450451pub fn evaluate_apply(452	context: Context,453	value: &LocExpr,454	args: &ArgsDesc,455	loc: Option<&ExprLocation>,456	tailstrict: bool,457) -> Result<Val> {458	let value = evaluate(context.clone(), value)?;459	Ok(match value {460		Val::Func(f) => {461			let body = || f.evaluate(context, loc, args, tailstrict);462			if tailstrict {463				body()?464			} else {465				push(loc, || format!("function <{}> call", f.name()), body)?466			}467		}468		v => throw!(OnlyFunctionsCanBeCalledGot(v.value_type())),469	})470}471472pub fn evaluate_assert(context: Context, assertion: &AssertStmt) -> Result<()> {473	let value = &assertion.0;474	let msg = &assertion.1;475	let assertion_result = push(476		value.1.as_ref(),477		|| "assertion condition".to_owned(),478		|| {479			evaluate(context.clone(), value)?480				.try_cast_bool("assertion condition should be of type `boolean`")481		},482	)?;483	if !assertion_result {484		push(485			value.1.as_ref(),486			|| "assertion failure".to_owned(),487			|| {488				if let Some(msg) = msg {489					throw!(AssertionFailed(evaluate(context, msg)?.to_string()?));490				} else {491					throw!(AssertionFailed(Val::Null.to_string()?));492				}493			},494		)?495	}496	Ok(())497}498499pub fn evaluate_named(context: Context, lexpr: &LocExpr, name: IStr) -> Result<Val> {500	use Expr::*;501	let LocExpr(expr, _loc) = lexpr;502	Ok(match &**expr {503		Function(params, body) => evaluate_method(context, name, params.clone(), body.clone()),504		_ => evaluate(context, lexpr)?,505	})506}507508pub fn evaluate(context: Context, expr: &LocExpr) -> Result<Val> {509	use Expr::*;510	let LocExpr(expr, loc) = expr;511	Ok(match &**expr {512		Literal(LiteralType::This) => {513			Val::Obj(context.this().clone().ok_or(CantUseSelfOutsideOfObject)?)514		}515		Literal(LiteralType::Super) => Val::Obj(516			context517				.super_obj()518				.clone()519				.ok_or(NoSuperFound)?520				.with_this(context.this().clone().unwrap()),521		),522		Literal(LiteralType::Dollar) => {523			Val::Obj(context.dollar().clone().ok_or(NoTopLevelObjectFound)?)524		}525		Literal(LiteralType::True) => Val::Bool(true),526		Literal(LiteralType::False) => Val::Bool(false),527		Literal(LiteralType::Null) => Val::Null,528		Parened(e) => evaluate(context, e)?,529		Str(v) => Val::Str(v.clone()),530		Num(v) => Val::new_checked_num(*v)?,531		BinaryOp(v1, o, v2) => evaluate_binary_op_special(context, v1, *o, v2)?,532		UnaryOp(o, v) => evaluate_unary_op(*o, &evaluate(context, v)?)?,533		Var(name) => push(534			loc.as_ref(),535			|| format!("variable <{}>", name),536			|| context.binding(name.clone())?.evaluate(),537		)?,538		Index(value, index) => {539			match (evaluate(context.clone(), value)?, evaluate(context, index)?) {540				(Val::Obj(v), Val::Str(s)) => {541					let sn = s.clone();542					push(543						loc.as_ref(),544						|| format!("field <{}> access", sn),545						|| {546							if let Some(v) = v.get(s.clone())? {547								Ok(v)548							} else if v.get("__intrinsic_namespace__".into())?.is_some() {549								Ok(Val::Func(Gc::new(FuncVal::Intrinsic(s))))550							} else {551								throw!(NoSuchField(s))552							}553						},554					)?555				}556				(Val::Obj(_), n) => throw!(ValueIndexMustBeTypeGot(557					ValType::Obj,558					ValType::Str,559					n.value_type(),560				)),561562				(Val::Arr(v), Val::Num(n)) => {563					if n.fract() > f64::EPSILON {564						throw!(FractionalIndex)565					}566					v.get(n as usize)?567						.ok_or_else(|| ArrayBoundsError(n as usize, v.len()))?568				}569				(Val::Arr(_), Val::Str(n)) => throw!(AttemptedIndexAnArrayWithString(n)),570				(Val::Arr(_), n) => throw!(ValueIndexMustBeTypeGot(571					ValType::Arr,572					ValType::Num,573					n.value_type(),574				)),575576				(Val::Str(s), Val::Num(n)) => Val::Str(577					s.chars()578						.skip(n as usize)579						.take(1)580						.collect::<String>()581						.into(),582				),583				(Val::Str(_), n) => throw!(ValueIndexMustBeTypeGot(584					ValType::Str,585					ValType::Num,586					n.value_type(),587				)),588589				(v, _) => throw!(CantIndexInto(v.value_type())),590			}591		}592		LocalExpr(bindings, returned) => {593			let mut new_bindings: FxHashMap<IStr, LazyVal> = HashMap::with_capacity_and_hasher(594				bindings.len(),595				BuildHasherDefault::<FxHasher>::default(),596			);597			let future_context = Context::new_future();598			for b in bindings {599				new_bindings.insert(600					b.name.clone(),601					evaluate_binding_in_future(b, future_context.clone()),602				);603			}604			let context = context605				.extend_bound(new_bindings)606				.into_future(future_context);607			evaluate(context, &returned.clone())?608		}609		Arr(items) => {610			let mut out = Vec::with_capacity(items.len());611			for item in items {612				// TODO: Implement ArrValue::Lazy with same context for every element?613				#[derive(Trace)]614				#[trivially_drop]615				struct ArrayElement {616					context: Context,617					item: LocExpr,618				}619				impl LazyValValue for ArrayElement {620					fn get(self: Box<Self>) -> Result<Val> {621						evaluate(self.context, &self.item)622					}623				}624				out.push(LazyVal::new(Box::new(ArrayElement {625					context: context.clone(),626					item: item.clone(),627				})));628			}629			Val::Arr(out.into())630		}631		ArrComp(expr, comp_specs) => {632			let mut out = Vec::new();633			evaluate_comp(context, comp_specs, &mut |ctx| {634				out.push(evaluate(ctx, expr)?);635				Ok(())636			})?;637			Val::Arr(ArrValue::Eager(Gc::new(out)))638		}639		Obj(body) => Val::Obj(evaluate_object(context, body)?),640		ObjExtend(s, t) => evaluate_add_op(641			&evaluate(context.clone(), s)?,642			&Val::Obj(evaluate_object(context, t)?),643		)?,644		Apply(value, args, tailstrict) => {645			evaluate_apply(context, value, args, loc.as_ref(), *tailstrict)?646		}647		Function(params, body) => {648			evaluate_method(context, "anonymous".into(), params.clone(), body.clone())649		}650		Intrinsic(name) => Val::Func(Gc::new(FuncVal::Intrinsic(name.clone()))),651		AssertExpr(assert, returned) => {652			evaluate_assert(context.clone(), assert)?;653			evaluate(context, returned)?654		}655		ErrorStmt(e) => push(656			loc.as_ref(),657			|| "error statement".to_owned(),658			|| {659				throw!(RuntimeError(660					evaluate(context, e)?.try_cast_str("error text should be of type `string`")?,661				))662			},663		)?,664		IfElse {665			cond,666			cond_then,667			cond_else,668		} => {669			if push(670				loc.as_ref(),671				|| "if condition".to_owned(),672				|| evaluate(context.clone(), &cond.0)?.try_cast_bool("in if condition"),673			)? {674				evaluate(context, cond_then)?675			} else {676				match cond_else {677					Some(v) => evaluate(context, v)?,678					None => Val::Null,679				}680			}681		}682		Import(path) => {683			let tmp = loc684				.clone()685				.expect("imports cannot be used without loc_data")686				.0;687			let mut import_location = tmp.to_path_buf();688			import_location.pop();689			push(690				loc.as_ref(),691				|| format!("import {:?}", path),692				|| with_state(|s| s.import_file(&import_location, path)),693			)?694		}695		ImportStr(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			Val::Str(with_state(|s| s.import_file_str(&import_location, path))?)703		}704	})705}
after · crates/jrsonnet-evaluator/src/evaluate/mod.rs
1use crate::{2	builtin::std_slice,3	error::Error::*,4	evaluate::operator::{evaluate_add_op, evaluate_binary_op_special, evaluate_unary_op},5	push, throw, with_state, ArrValue, Bindable, Context, ContextCreator, FuncDesc, FuncVal,6	FutureWrapper, LazyBinding, LazyVal, LazyValValue, ObjValue, ObjValueBuilder, ObjectAssertion,7	Result, Val,8};9use jrsonnet_gc::{Gc, Trace};10use jrsonnet_interner::IStr;11use jrsonnet_parser::{12	ArgsDesc, AssertStmt, BindSpec, CompSpec, Expr, ExprLocation, FieldMember, ForSpecData,13	IfSpecData, LiteralType, LocExpr, Member, ObjBody, ParamsDesc,14};15use jrsonnet_types::ValType;16use rustc_hash::{FxHashMap, FxHasher};17use std::{collections::HashMap, hash::BuildHasherDefault};18pub mod operator;1920pub fn evaluate_binding_in_future(21	b: &BindSpec,22	context_creator: FutureWrapper<Context>,23) -> LazyVal {24	let b = b.clone();25	if let Some(params) = &b.params {26		let params = params.clone();2728		#[derive(Trace)]29		#[trivially_drop]30		struct LazyMethodBinding {31			context_creator: FutureWrapper<Context>,32			name: IStr,33			params: ParamsDesc,34			value: LocExpr,35		}36		impl LazyValValue for LazyMethodBinding {37			fn get(self: Box<Self>) -> Result<Val> {38				Ok(evaluate_method(39					self.context_creator.unwrap(),40					self.name,41					self.params,42					self.value,43				))44			}45		}4647		LazyVal::new(Box::new(LazyMethodBinding {48			context_creator,49			name: b.name.clone(),50			params,51			value: b.value.clone(),52		}))53	} else {54		#[derive(Trace)]55		#[trivially_drop]56		struct LazyNamedBinding {57			context_creator: FutureWrapper<Context>,58			name: IStr,59			value: LocExpr,60		}61		impl LazyValValue for LazyNamedBinding {62			fn get(self: Box<Self>) -> Result<Val> {63				evaluate_named(self.context_creator.unwrap(), &self.value, self.name)64			}65		}66		LazyVal::new(Box::new(LazyNamedBinding {67			context_creator,68			name: b.name.clone(),69			value: b.value,70		}))71	}72}7374pub fn evaluate_binding(b: &BindSpec, context_creator: ContextCreator) -> (IStr, LazyBinding) {75	let b = b.clone();76	if let Some(params) = &b.params {77		let params = params.clone();7879		#[derive(Trace)]80		#[trivially_drop]81		struct BindableMethodLazyVal {82			this: Option<ObjValue>,83			super_obj: Option<ObjValue>,8485			context_creator: ContextCreator,86			name: IStr,87			params: ParamsDesc,88			value: LocExpr,89		}90		impl LazyValValue for BindableMethodLazyVal {91			fn get(self: Box<Self>) -> Result<Val> {92				Ok(evaluate_method(93					self.context_creator.create(self.this, self.super_obj)?,94					self.name,95					self.params,96					self.value,97				))98			}99		}100101		#[derive(Trace)]102		#[trivially_drop]103		struct BindableMethod {104			context_creator: ContextCreator,105			name: IStr,106			params: ParamsDesc,107			value: LocExpr,108		}109		impl Bindable for BindableMethod {110			fn bind(&self, this: Option<ObjValue>, super_obj: Option<ObjValue>) -> Result<LazyVal> {111				Ok(LazyVal::new(Box::new(BindableMethodLazyVal {112					this,113					super_obj,114115					context_creator: self.context_creator.clone(),116					name: self.name.clone(),117					params: self.params.clone(),118					value: self.value.clone(),119				})))120			}121		}122123		(124			b.name.clone(),125			LazyBinding::Bindable(Gc::new(Box::new(BindableMethod {126				context_creator,127				name: b.name.clone(),128				params,129				value: b.value.clone(),130			}))),131		)132	} else {133		#[derive(Trace)]134		#[trivially_drop]135		struct BindableNamedLazyVal {136			this: Option<ObjValue>,137			super_obj: Option<ObjValue>,138139			context_creator: ContextCreator,140			name: IStr,141			value: LocExpr,142		}143		impl LazyValValue for BindableNamedLazyVal {144			fn get(self: Box<Self>) -> Result<Val> {145				evaluate_named(146					self.context_creator.create(self.this, self.super_obj)?,147					&self.value,148					self.name,149				)150			}151		}152153		#[derive(Trace)]154		#[trivially_drop]155		struct BindableNamed {156			context_creator: ContextCreator,157			name: IStr,158			value: LocExpr,159		}160		impl Bindable for BindableNamed {161			fn bind(&self, this: Option<ObjValue>, super_obj: Option<ObjValue>) -> Result<LazyVal> {162				Ok(LazyVal::new(Box::new(BindableNamedLazyVal {163					this,164					super_obj,165166					context_creator: self.context_creator.clone(),167					name: self.name.clone(),168					value: self.value.clone(),169				})))170			}171		}172173		(174			b.name.clone(),175			LazyBinding::Bindable(Gc::new(Box::new(BindableNamed {176				context_creator,177				name: b.name.clone(),178				value: b.value.clone(),179			}))),180		)181	}182}183184pub fn evaluate_method(ctx: Context, name: IStr, params: ParamsDesc, body: LocExpr) -> Val {185	Val::Func(Gc::new(FuncVal::Normal(FuncDesc {186		name,187		ctx,188		params,189		body,190	})))191}192193pub fn evaluate_field_name(194	context: Context,195	field_name: &jrsonnet_parser::FieldName,196) -> Result<Option<IStr>> {197	Ok(match field_name {198		jrsonnet_parser::FieldName::Fixed(n) => Some(n.clone()),199		jrsonnet_parser::FieldName::Dyn(expr) => {200			let value = evaluate(context, expr)?;201			if matches!(value, Val::Null) {202				None203			} else {204				Some(value.try_cast_str("dynamic field name")?)205			}206		}207	})208}209210pub fn evaluate_comp(211	context: Context,212	specs: &[CompSpec],213	callback: &mut impl FnMut(Context) -> Result<()>,214) -> Result<()> {215	match specs.get(0) {216		None => callback(context)?,217		Some(CompSpec::IfSpec(IfSpecData(cond))) => {218			if evaluate(context.clone(), cond)?.try_cast_bool("if spec")? {219				evaluate_comp(context, &specs[1..], callback)?220			}221		}222		Some(CompSpec::ForSpec(ForSpecData(var, expr))) => match evaluate(context.clone(), expr)? {223			Val::Arr(list) => {224				for item in list.iter() {225					evaluate_comp(226						context.clone().with_var(var.clone(), item?.clone()),227						&specs[1..],228						callback,229					)?230				}231			}232			_ => throw!(InComprehensionCanOnlyIterateOverArray),233		},234	}235	Ok(())236}237238pub fn evaluate_member_list_object(context: Context, members: &[Member]) -> Result<ObjValue> {239	let new_bindings = FutureWrapper::new();240	let future_this = FutureWrapper::new();241	let context_creator = ContextCreator(context.clone(), new_bindings.clone());242	{243		let mut bindings: FxHashMap<IStr, LazyBinding> =244			FxHashMap::with_capacity_and_hasher(members.len(), BuildHasherDefault::default());245		for (n, b) in members246			.iter()247			.filter_map(|m| match m {248				Member::BindStmt(b) => Some(b.clone()),249				_ => None,250			})251			.map(|b| evaluate_binding(&b, context_creator.clone()))252		{253			bindings.insert(n, b);254		}255		new_bindings.fill(bindings);256	}257258	let mut builder = ObjValueBuilder::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				builder295					.member(name.clone())296					.with_add(*plus)297					.with_visibility(*visibility)298					.with_location(value.1.clone())299					.bindable(Box::new(ObjMemberBinding {300						context_creator: context_creator.clone(),301						value: value.clone(),302						name,303					}));304			}305			Member::Field(FieldMember {306				name,307				params: Some(params),308				value,309				..310			}) => {311				let name = evaluate_field_name(context.clone(), name)?;312				if name.is_none() {313					continue;314				}315				let name = name.unwrap();316				#[derive(Trace)]317				#[trivially_drop]318				struct ObjMemberBinding {319					context_creator: ContextCreator,320					value: LocExpr,321					params: ParamsDesc,322					name: IStr,323				}324				impl Bindable for ObjMemberBinding {325					fn bind(326						&self,327						this: Option<ObjValue>,328						super_obj: Option<ObjValue>,329					) -> Result<LazyVal> {330						Ok(LazyVal::new_resolved(evaluate_method(331							self.context_creator.create(this, super_obj)?,332							self.name.clone(),333							self.params.clone(),334							self.value.clone(),335						)))336					}337				}338				builder339					.member(name.clone())340					.hide()341					.with_location(value.1.clone())342					.binding(LazyBinding::Bindable(Gc::new(Box::new(ObjMemberBinding {343						context_creator: context_creator.clone(),344						value: value.clone(),345						params: params.clone(),346						name,347					}))));348			}349			Member::BindStmt(_) => {}350			Member::AssertStmt(stmt) => {351				#[derive(Trace)]352				#[trivially_drop]353				struct ObjectAssert {354					context_creator: ContextCreator,355					assert: AssertStmt,356				}357				impl ObjectAssertion for ObjectAssert {358					fn run(359						&self,360						this: Option<ObjValue>,361						super_obj: Option<ObjValue>,362					) -> Result<()> {363						let ctx = self.context_creator.create(this, super_obj)?;364						evaluate_assert(ctx, &self.assert)365					}366				}367				builder.assert(Box::new(ObjectAssert {368					context_creator: context_creator.clone(),369					assert: stmt.clone(),370				}));371			}372		}373	}374	let this = builder.build();375	future_this.fill(this.clone());376	Ok(this)377}378379pub fn evaluate_object(context: Context, object: &ObjBody) -> Result<ObjValue> {380	Ok(match object {381		ObjBody::MemberList(members) => evaluate_member_list_object(context, members)?,382		ObjBody::ObjComp(obj) => {383			let future_this = FutureWrapper::new();384			let mut builder = ObjValueBuilder::new();385			evaluate_comp(context.clone(), &obj.compspecs, &mut |ctx| {386				let new_bindings = FutureWrapper::new();387				let context_creator = ContextCreator(context.clone(), new_bindings.clone());388				let mut bindings: FxHashMap<IStr, LazyBinding> =389					FxHashMap::with_capacity_and_hasher(390						obj.pre_locals.len() + obj.post_locals.len(),391						BuildHasherDefault::default(),392					);393				for (n, b) in obj394					.pre_locals395					.iter()396					.chain(obj.post_locals.iter())397					.map(|b| evaluate_binding(b, context_creator.clone()))398				{399					bindings.insert(n, b);400				}401				new_bindings.fill(bindings.clone());402				let ctx = ctx.extend_unbound(bindings, None, None, None)?;403				let key = evaluate(ctx.clone(), &obj.key)?;404405				match key {406					Val::Null => {}407					Val::Str(n) => {408						#[derive(Trace)]409						#[trivially_drop]410						struct ObjCompBinding {411							context: Context,412							value: LocExpr,413						}414						impl Bindable for ObjCompBinding {415							fn bind(416								&self,417								this: Option<ObjValue>,418								_super_obj: Option<ObjValue>,419							) -> Result<LazyVal> {420								Ok(LazyVal::new_resolved(evaluate(421									self.context.clone().extend(422										FxHashMap::default(),423										None,424										this,425										None,426									),427									&self.value,428								)?))429							}430						}431						builder432							.member(n)433							.with_location(obj.value.1.clone())434							.bindable(Box::new(ObjCompBinding {435								context: ctx,436								value: obj.value.clone(),437							}));438					}439					v => throw!(FieldMustBeStringGot(v.value_type())),440				}441442				Ok(())443			})?;444445			let this = builder.build();446			future_this.fill(this.clone());447			this448		}449	})450}451452pub fn evaluate_apply(453	context: Context,454	value: &LocExpr,455	args: &ArgsDesc,456	loc: Option<&ExprLocation>,457	tailstrict: bool,458) -> Result<Val> {459	let value = evaluate(context.clone(), value)?;460	Ok(match value {461		Val::Func(f) => {462			let body = || f.evaluate(context, loc, args, tailstrict);463			if tailstrict {464				body()?465			} else {466				push(loc, || format!("function <{}> call", f.name()), body)?467			}468		}469		v => throw!(OnlyFunctionsCanBeCalledGot(v.value_type())),470	})471}472473pub fn evaluate_assert(context: Context, assertion: &AssertStmt) -> Result<()> {474	let value = &assertion.0;475	let msg = &assertion.1;476	let assertion_result = push(477		value.1.as_ref(),478		|| "assertion condition".to_owned(),479		|| {480			evaluate(context.clone(), value)?481				.try_cast_bool("assertion condition should be of type `boolean`")482		},483	)?;484	if !assertion_result {485		push(486			value.1.as_ref(),487			|| "assertion failure".to_owned(),488			|| {489				if let Some(msg) = msg {490					throw!(AssertionFailed(evaluate(context, msg)?.to_string()?));491				} else {492					throw!(AssertionFailed(Val::Null.to_string()?));493				}494			},495		)?496	}497	Ok(())498}499500pub fn evaluate_named(context: Context, lexpr: &LocExpr, name: IStr) -> Result<Val> {501	use Expr::*;502	let LocExpr(expr, _loc) = lexpr;503	Ok(match &**expr {504		Function(params, body) => evaluate_method(context, name, params.clone(), body.clone()),505		_ => evaluate(context, lexpr)?,506	})507}508509pub fn evaluate(context: Context, expr: &LocExpr) -> Result<Val> {510	use Expr::*;511	let LocExpr(expr, loc) = expr;512	Ok(match &**expr {513		Literal(LiteralType::This) => {514			Val::Obj(context.this().clone().ok_or(CantUseSelfOutsideOfObject)?)515		}516		Literal(LiteralType::Super) => Val::Obj(517			context518				.super_obj()519				.clone()520				.ok_or(NoSuperFound)?521				.with_this(context.this().clone().unwrap()),522		),523		Literal(LiteralType::Dollar) => {524			Val::Obj(context.dollar().clone().ok_or(NoTopLevelObjectFound)?)525		}526		Literal(LiteralType::True) => Val::Bool(true),527		Literal(LiteralType::False) => Val::Bool(false),528		Literal(LiteralType::Null) => Val::Null,529		Parened(e) => evaluate(context, e)?,530		Str(v) => Val::Str(v.clone()),531		Num(v) => Val::new_checked_num(*v)?,532		BinaryOp(v1, o, v2) => evaluate_binary_op_special(context, v1, *o, v2)?,533		UnaryOp(o, v) => evaluate_unary_op(*o, &evaluate(context, v)?)?,534		Var(name) => push(535			loc.as_ref(),536			|| format!("variable <{}>", name),537			|| context.binding(name.clone())?.evaluate(),538		)?,539		Index(value, index) => {540			match (evaluate(context.clone(), value)?, evaluate(context, index)?) {541				(Val::Obj(v), Val::Str(s)) => {542					let sn = s.clone();543					push(544						loc.as_ref(),545						|| format!("field <{}> access", sn),546						|| {547							if let Some(v) = v.get(s.clone())? {548								Ok(v)549							} else if v.get("__intrinsic_namespace__".into())?.is_some() {550								Ok(Val::Func(Gc::new(FuncVal::Intrinsic(s))))551							} else {552								throw!(NoSuchField(s))553							}554						},555					)?556				}557				(Val::Obj(_), n) => throw!(ValueIndexMustBeTypeGot(558					ValType::Obj,559					ValType::Str,560					n.value_type(),561				)),562563				(Val::Arr(v), Val::Num(n)) => {564					if n.fract() > f64::EPSILON {565						throw!(FractionalIndex)566					}567					v.get(n as usize)?568						.ok_or_else(|| ArrayBoundsError(n as usize, v.len()))?569				}570				(Val::Arr(_), Val::Str(n)) => throw!(AttemptedIndexAnArrayWithString(n)),571				(Val::Arr(_), n) => throw!(ValueIndexMustBeTypeGot(572					ValType::Arr,573					ValType::Num,574					n.value_type(),575				)),576577				(Val::Str(s), Val::Num(n)) => Val::Str(578					s.chars()579						.skip(n as usize)580						.take(1)581						.collect::<String>()582						.into(),583				),584				(Val::Str(_), n) => throw!(ValueIndexMustBeTypeGot(585					ValType::Str,586					ValType::Num,587					n.value_type(),588				)),589590				(v, _) => throw!(CantIndexInto(v.value_type())),591			}592		}593		LocalExpr(bindings, returned) => {594			let mut new_bindings: FxHashMap<IStr, LazyVal> = HashMap::with_capacity_and_hasher(595				bindings.len(),596				BuildHasherDefault::<FxHasher>::default(),597			);598			let future_context = Context::new_future();599			for b in bindings {600				new_bindings.insert(601					b.name.clone(),602					evaluate_binding_in_future(b, future_context.clone()),603				);604			}605			let context = context606				.extend_bound(new_bindings)607				.into_future(future_context);608			evaluate(context, &returned.clone())?609		}610		Arr(items) => {611			let mut out = Vec::with_capacity(items.len());612			for item in items {613				// TODO: Implement ArrValue::Lazy with same context for every element?614				#[derive(Trace)]615				#[trivially_drop]616				struct ArrayElement {617					context: Context,618					item: LocExpr,619				}620				impl LazyValValue for ArrayElement {621					fn get(self: Box<Self>) -> Result<Val> {622						evaluate(self.context, &self.item)623					}624				}625				out.push(LazyVal::new(Box::new(ArrayElement {626					context: context.clone(),627					item: item.clone(),628				})));629			}630			Val::Arr(out.into())631		}632		ArrComp(expr, comp_specs) => {633			let mut out = Vec::new();634			evaluate_comp(context, comp_specs, &mut |ctx| {635				out.push(evaluate(ctx, expr)?);636				Ok(())637			})?;638			Val::Arr(ArrValue::Eager(Gc::new(out)))639		}640		Obj(body) => Val::Obj(evaluate_object(context, body)?),641		ObjExtend(s, t) => evaluate_add_op(642			&evaluate(context.clone(), s)?,643			&Val::Obj(evaluate_object(context, t)?),644		)?,645		Apply(value, args, tailstrict) => {646			evaluate_apply(context, value, args, loc.as_ref(), *tailstrict)?647		}648		Function(params, body) => {649			evaluate_method(context, "anonymous".into(), params.clone(), body.clone())650		}651		Intrinsic(name) => Val::Func(Gc::new(FuncVal::Intrinsic(name.clone()))),652		AssertExpr(assert, returned) => {653			evaluate_assert(context.clone(), assert)?;654			evaluate(context, returned)?655		}656		ErrorStmt(e) => push(657			loc.as_ref(),658			|| "error statement".to_owned(),659			|| {660				throw!(RuntimeError(661					evaluate(context, e)?.try_cast_str("error text should be of type `string`")?,662				))663			},664		)?,665		IfElse {666			cond,667			cond_then,668			cond_else,669		} => {670			if push(671				loc.as_ref(),672				|| "if condition".to_owned(),673				|| evaluate(context.clone(), &cond.0)?.try_cast_bool("in if condition"),674			)? {675				evaluate(context, cond_then)?676			} else {677				match cond_else {678					Some(v) => evaluate(context, v)?,679					None => Val::Null,680				}681			}682		}683		Slice(value, desc) => {684			let indexable = evaluate(context.clone(), value)?;685686			fn parse_num(687				context: &Context,688				expr: Option<&LocExpr>,689				desc: &'static str,690			) -> Result<Option<usize>> {691				Ok(match expr {692					Some(s) => evaluate(context.clone(), &s)?693						.try_cast_nullable_num(desc)?694						.map(|v| v as usize),695					None => None,696				})697			}698699			let start = parse_num(&context, desc.start.as_ref(), "start")?;700			let end = parse_num(&context, desc.end.as_ref(), "end")?;701			let step = parse_num(&context, desc.step.as_ref(), "step")?;702703			std_slice(indexable.to_indexable()?, start, end, step)?704		}705		Import(path) => {706			let tmp = loc707				.clone()708				.expect("imports cannot be used without loc_data")709				.0;710			let mut import_location = tmp.to_path_buf();711			import_location.pop();712			push(713				loc.as_ref(),714				|| format!("import {:?}", path),715				|| with_state(|s| s.import_file(&import_location, path)),716			)?717		}718		ImportStr(path) => {719			let tmp = loc720				.clone()721				.expect("imports cannot be used without loc_data")722				.0;723			let mut import_location = tmp.to_path_buf();724			import_location.pop();725			Val::Str(with_state(|s| s.import_file_str(&import_location, path))?)726		}727	})728}
modifiedcrates/jrsonnet-evaluator/src/evaluate/operator.rsdiffbeforeafterboth
--- a/crates/jrsonnet-evaluator/src/evaluate/operator.rs
+++ b/crates/jrsonnet-evaluator/src/evaluate/operator.rs
@@ -1,3 +1,4 @@
+use crate::builtin::std_format;
 use crate::{equals, evaluate, Context, Val};
 use crate::{error::Error::*, throw, Result};
 use jrsonnet_parser::{BinaryOpType, LocExpr, UnaryOpType};
@@ -41,6 +42,19 @@
 	})
 }
 
+pub fn evaluate_mod_op(a: &Val, b: &Val) -> Result<Val> {
+	use Val::*;
+	match (a, b) {
+		(Num(a), Num(b)) => Ok(Num(a % b)),
+		(Str(str), vals) => std_format(str.clone(), vals.clone()),
+		(a, b) => throw!(BinaryOperatorDoesNotOperateOnValues(
+			BinaryOpType::Mod,
+			a.value_type(),
+			b.value_type()
+		)),
+	}
+}
+
 pub fn evaluate_binary_op_special(
 	context: Context,
 	a: &LocExpr,
@@ -60,13 +74,14 @@
 	use BinaryOpType::*;
 	use Val::*;
 	Ok(match (a, op, b) {
-		(Str(a), In, Obj(obj)) => Bool(obj.has_field_ex(a.clone(), true)),
-
 		(a, Add, b) => evaluate_add_op(a, b)?,
 
 		(a, Eq, b) => Bool(equals(a, b)?),
 		(a, Neq, b) => Bool(!equals(a, b)?),
 
+		(Str(a), In, Obj(obj)) => Bool(obj.has_field_ex(a.clone(), true)),
+		(a, Mod, b) => evaluate_mod_op(a, b)?,
+
 		(Str(v1), Mul, Num(v2)) => Str(v1.repeat(*v2 as usize).into()),
 
 		// Bool X Bool
modifiedcrates/jrsonnet-evaluator/src/val.rsdiffbeforeafterboth
--- a/crates/jrsonnet-evaluator/src/val.rs
+++ b/crates/jrsonnet-evaluator/src/val.rs
@@ -345,6 +345,11 @@
 	}
 }
 
+pub enum IndexableVal {
+	Str(IStr),
+	Arr(ArrValue),
+}
+
 #[derive(Debug, Clone, Trace)]
 #[trivially_drop]
 pub enum Val {
@@ -402,6 +407,17 @@
 		self.assert_type(context, ValType::Num)?;
 		self.unwrap_num()
 	}
+	pub fn try_cast_nullable_num(self, context: &'static str) -> Result<Option<f64>> {
+		Ok(match self {
+			Val::Null => None,
+			Val::Num(num) => Some(num),
+			_ => throw!(TypeMismatch(
+				context,
+				vec![ValType::Null, ValType::Num],
+				self.value_type()
+			)),
+		})
+	}
 	pub const fn value_type(&self) -> ValType {
 		match self {
 			Self::Str(..) => ValType::Str,
@@ -580,6 +596,13 @@
 			.try_cast_str("to json")
 		})
 	}
+	pub fn to_indexable(self) -> Result<IndexableVal> {
+		Ok(match self {
+			Val::Str(s) => IndexableVal::Str(s),
+			Val::Arr(arr) => IndexableVal::Arr(arr),
+			_ => throw!(ValueIsNotIndexable(self.value_type())),
+		})
+	}
 }
 
 const fn is_function_like(val: &Val) -> bool {
modifiedcrates/jrsonnet-parser/src/expr.rsdiffbeforeafterboth
--- a/crates/jrsonnet-parser/src/expr.rs
+++ b/crates/jrsonnet-parser/src/expr.rs
@@ -274,6 +274,8 @@
 	False,
 }
 
+#[cfg_attr(feature = "serialize", derive(Serialize))]
+#[cfg_attr(feature = "deserialize", derive(Deserialize))]
 #[derive(Debug, PartialEq, Trace)]
 #[trivially_drop]
 pub struct SliceDesc {
@@ -349,6 +351,7 @@
 		cond_then: LocExpr,
 		cond_else: Option<LocExpr>,
 	},
+	Slice(LocExpr, SliceDesc),
 }
 
 /// file, begin offset, end offset
modifiedcrates/jrsonnet-parser/src/lib.rsdiffbeforeafterboth
--- a/crates/jrsonnet-parser/src/lib.rs
+++ b/crates/jrsonnet-parser/src/lib.rs
@@ -14,6 +14,17 @@
 	pub file_name: Rc<Path>,
 }
 
+macro_rules! expr_bin {
+	($a:ident $op:ident $b:ident) => {
+		loc_expr_todo!(Expr::BinaryOp($a, $op, $b))
+	};
+}
+macro_rules! expr_un {
+	($op:ident $a:ident) => {
+		loc_expr_todo!(Expr::UnaryOp($op, $a))
+	};
+}
+
 parser! {
 	grammar jsonnet_parser() for str {
 		use peg::ParseLiteral;
@@ -219,54 +230,43 @@
 
 
 		use BinaryOpType::*;
+		use UnaryOpType::*;
 		rule expr(s: &ParserSettings) -> LocExpr
 			= start:position!() a:precedence! {
-				a:(@) _ binop(<"||">) _ b:@ {loc_expr_todo!(Expr::BinaryOp(a, Or, b))}
+				a:(@) _ binop(<"||">) _ b:@ {expr_bin!(a Or b)}
 				--
-				a:(@) _ binop(<"&&">) _ b:@ {loc_expr_todo!(Expr::BinaryOp(a, And, b))}
+				a:(@) _ binop(<"&&">) _ b:@ {expr_bin!(a And b)}
 				--
-				a:(@) _ binop(<"|">) _ b:@ {loc_expr_todo!(Expr::BinaryOp(a, BitOr, b))}
+				a:(@) _ binop(<"|">) _ b:@ {expr_bin!(a BitOr b)}
 				--
-				a:@ _ binop(<"^">) _ b:(@) {loc_expr_todo!(Expr::BinaryOp(a, BitXor, b))}
+				a:@ _ binop(<"^">) _ b:(@) {expr_bin!(a BitXor b)}
 				--
-				a:(@) _ binop(<"&">) _ b:@ {loc_expr_todo!(Expr::BinaryOp(a, BitAnd, b))}
+				a:(@) _ binop(<"&">) _ b:@ {expr_bin!(a BitAnd b)}
 				--
-				a:(@) _ binop(<"==">) _ b:@ {loc_expr_todo!(Expr::BinaryOp(a, Eq, b))}
-				a:(@) _ binop(<"!=">) _ b:@ {loc_expr_todo!(Expr::BinaryOp(a, Neq, b))}
+				a:(@) _ binop(<"==">) _ b:@ {expr_bin!(a Eq b)}
+				a:(@) _ binop(<"!=">) _ b:@ {expr_bin!(a Neq b)}
 				--
-				a:(@) _ binop(<"<">) _ b:@ {loc_expr_todo!(Expr::BinaryOp(a, Lt, b))}
-				a:(@) _ binop(<">">) _ b:@ {loc_expr_todo!(Expr::BinaryOp(a, Gt, b))}
-				a:(@) _ binop(<"<=">) _ b:@ {loc_expr_todo!(Expr::BinaryOp(a, Lte, b))}
-				a:(@) _ binop(<">=">) _ b:@ {loc_expr_todo!(Expr::BinaryOp(a, Gte, b))}
-				a:(@) _ binop(<keyword("in")>) _ b:@ {loc_expr_todo!(Expr::BinaryOp(a, In, b))}
+				a:(@) _ binop(<"<">) _ b:@ {expr_bin!(a Lt b)}
+				a:(@) _ binop(<">">) _ b:@ {expr_bin!(a Gt b)}
+				a:(@) _ binop(<"<=">) _ b:@ {expr_bin!(a Lte b)}
+				a:(@) _ binop(<">=">) _ b:@ {expr_bin!(a Gte b)}
+				a:(@) _ binop(<keyword("in")>) _ b:@ {expr_bin!(a In b)}
 				--
-				a:(@) _ binop(<"<<">) _ b:@ {loc_expr_todo!(Expr::BinaryOp(a, Lhs, b))}
-				a:(@) _ binop(<">>">) _ b:@ {loc_expr_todo!(Expr::BinaryOp(a, Rhs, b))}
+				a:(@) _ binop(<"<<">) _ b:@ {expr_bin!(a Lhs b)}
+				a:(@) _ binop(<">>">) _ b:@ {expr_bin!(a Rhs b)}
 				--
-				a:(@) _ binop(<"+">) _ b:@ {loc_expr_todo!(Expr::BinaryOp(a, Add, b))}
-				a:(@) _ binop(<"-">) _ b:@ {loc_expr_todo!(Expr::BinaryOp(a, Sub, b))}
+				a:(@) _ binop(<"+">) _ b:@ {expr_bin!(a Add b)}
+				a:(@) _ binop(<"-">) _ b:@ {expr_bin!(a Sub b)}
 				--
-				a:(@) _ binop(<"*">) _ b:@ {loc_expr_todo!(Expr::BinaryOp(a, Mul, b))}
-				a:(@) _ binop(<"/">) _ b:@ {loc_expr_todo!(Expr::BinaryOp(a, Div, b))}
-				a:(@) _ binop(<"%">) _ b:@ {loc_expr_todo!(Expr::Apply(
-					el!(Expr::Intrinsic("mod".into())), ArgsDesc(vec![Arg(None, a), Arg(None, b)]),
-					false
-				))}
+				a:(@) _ binop(<"*">) _ b:@ {expr_bin!(a Mul b)}
+				a:(@) _ binop(<"/">) _ b:@ {expr_bin!(a Div b)}
+				a:(@) _ binop(<"%">) _ b:@ {expr_bin!(a Mod b)}
 				--
-						unaryop(<"-">) _ b:@ {loc_expr_todo!(Expr::UnaryOp(UnaryOpType::Minus, b))}
-						unaryop(<"!">) _ b:@ {loc_expr_todo!(Expr::UnaryOp(UnaryOpType::Not, b))}
-						unaryop(<"~">) _ b:@ { loc_expr_todo!(Expr::UnaryOp(UnaryOpType::BitNot, b)) }
+						unaryop(<"-">) _ b:@ {expr_un!(Minus b)}
+						unaryop(<"!">) _ b:@ {expr_un!(Not b)}
+						unaryop(<"~">) _ b:@ {expr_un!(BitNot b)}
 				--
-				a:(@) _ "[" _ s:slice_desc(s) _ "]" {loc_expr_todo!(Expr::Apply(
-					el!(Expr::Intrinsic("slice".into())),
-					ArgsDesc(vec![
-						Arg(None, a),
-						Arg(None, s.start.unwrap_or_else(||el!(Expr::Literal(LiteralType::Null)))),
-						Arg(None, s.end.unwrap_or_else(||el!(Expr::Literal(LiteralType::Null)))),
-						Arg(None, s.step.unwrap_or_else(||el!(Expr::Literal(LiteralType::Null)))),
-					]),
-					true,
-				))}
+				a:(@) _ "[" _ s:slice_desc(s) _ "]" {loc_expr_todo!(Expr::Slice(a, s))}
 				a:(@) _ "." _ s:$(id()) {loc_expr_todo!(Expr::Index(a, el!(Expr::Str(s.into()))))}
 				a:(@) _ "[" _ s:expr(s) _ "]" {loc_expr_todo!(Expr::Index(a, s))}
 				a:(@) _ "(" _ args:args(s) _ ")" ts:(_ keyword("tailstrict"))? {loc_expr_todo!(Expr::Apply(a, args, ts.is_some()))}