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

difftreelog

style rename bindable -> unbound

Yaroslav Bolyukin2022-04-24parent: #c65967c.patch.diff
in: master

4 files changed

modifiedcrates/jrsonnet-evaluator/src/evaluate/mod.rsdiffbeforeafterboth
before · crates/jrsonnet-evaluator/src/evaluate/mod.rs
1use std::rc::Rc;23use gcmodule::{Cc, Trace};4use jrsonnet_interner::IStr;5use jrsonnet_parser::{6	ArgsDesc, AssertStmt, BindSpec, CompSpec, Expr, FieldMember, ForSpecData, IfSpecData,7	LiteralType, LocExpr, Member, ObjBody, ParamsDesc,8};9use jrsonnet_types::ValType;1011use crate::{12	destructure::evaluate_dest,13	error::Error::*,14	evaluate::operator::{evaluate_add_op, evaluate_binary_op_special, evaluate_unary_op},15	function::{CallLocation, FuncDesc, FuncVal},16	stdlib::{std_slice, BUILTINS},17	tb, throw,18	typed::Typed,19	val::{ArrValue, CachedBindable, Thunk, ThunkValue},20	Bindable, Context, GcHashMap, ObjValue, ObjValueBuilder, ObjectAssertion, Pending, Result,21	State, Val,22};23pub mod destructure;24pub mod operator;2526pub fn evaluate_method(ctx: Context, name: IStr, params: ParamsDesc, body: LocExpr) -> Val {27	Val::Func(FuncVal::Normal(Cc::new(FuncDesc {28		name,29		ctx,30		params,31		body,32	})))33}3435pub fn evaluate_field_name(36	s: State,37	ctx: Context,38	field_name: &jrsonnet_parser::FieldName,39) -> Result<Option<IStr>> {40	Ok(match field_name {41		jrsonnet_parser::FieldName::Fixed(n) => Some(n.clone()),42		jrsonnet_parser::FieldName::Dyn(expr) => s.push(43			CallLocation::new(&expr.1),44			|| "evaluating field name".to_string(),45			|| {46				let value = evaluate(s.clone(), ctx, expr)?;47				if matches!(value, Val::Null) {48					Ok(None)49				} else {50					Ok(Some(IStr::from_untyped(value, s.clone())?))51				}52			},53		)?,54	})55}5657pub fn evaluate_comp(58	s: State,59	ctx: Context,60	specs: &[CompSpec],61	callback: &mut impl FnMut(Context) -> Result<()>,62) -> Result<()> {63	match specs.get(0) {64		None => callback(ctx)?,65		Some(CompSpec::IfSpec(IfSpecData(cond))) => {66			if bool::from_untyped(evaluate(s.clone(), ctx.clone(), cond)?, s.clone())? {67				evaluate_comp(s, ctx, &specs[1..], callback)?;68			}69		}70		Some(CompSpec::ForSpec(ForSpecData(var, expr))) => {71			match evaluate(s.clone(), ctx.clone(), expr)? {72				Val::Arr(list) => {73					for item in list.iter(s.clone()) {74						evaluate_comp(75							s.clone(),76							ctx.clone().with_var(var.clone(), item?.clone()),77							&specs[1..],78							callback,79						)?;80					}81				}82				_ => throw!(InComprehensionCanOnlyIterateOverArray),83			}84		}85	}86	Ok(())87}8889trait CloneableBindable<T>: Bindable<Bound = T> + Clone {}9091fn evaluate_object_locals(92	fctx: Pending<Context>,93	locals: Rc<Vec<BindSpec>>,94) -> impl CloneableBindable<Context> {95	#[derive(Trace, Clone)]96	struct WithObjectLocals {97		fctx: Pending<Context>,98		locals: Rc<Vec<BindSpec>>,99	}100	impl CloneableBindable<Context> for WithObjectLocals {}101	impl Bindable for WithObjectLocals {102		type Bound = Context;103104		fn bind(105			&self,106			_s: State,107			sup: Option<ObjValue>,108			this: Option<ObjValue>,109		) -> Result<Context> {110			let fctx = Context::new_future();111			let mut new_bindings = GcHashMap::new();112			for b in self.locals.iter() {113				evaluate_dest(b, fctx.clone(), &mut new_bindings)?;114			}115116			let ctx = self.fctx.unwrap();117			let new_dollar = ctx.dollar().clone().or_else(|| this.clone());118119			let ctx = ctx120				.extend(new_bindings, new_dollar, sup, this)121				.into_future(fctx);122123			Ok(ctx)124		}125	}126127	WithObjectLocals { fctx, locals }128}129130#[allow(clippy::too_many_lines)]131pub fn evaluate_member_list_object(s: State, ctx: Context, members: &[Member]) -> Result<ObjValue> {132	let mut builder = ObjValueBuilder::new();133	let locals = Rc::new(134		members135			.iter()136			.filter_map(|m| match m {137				Member::BindStmt(bind) => Some(bind.clone()),138				_ => None,139			})140			.collect::<Vec<_>>(),141	);142143	let fctx = Context::new_future();144145	// We have single context for all fields, so we can cache binds146	let uctx = CachedBindable::new(evaluate_object_locals(fctx.clone(), locals));147148	for member in members.iter() {149		match member {150			Member::Field(FieldMember {151				name,152				plus,153				params: None,154				visibility,155				value,156			}) => {157				#[derive(Trace)]158				struct ObjMemberBinding<B> {159					uctx: B,160					value: LocExpr,161					name: IStr,162				}163				impl<B: Bindable<Bound = Context>> Bindable for ObjMemberBinding<B> {164					type Bound = Thunk<Val>;165					fn bind(166						&self,167						s: State,168						sup: Option<ObjValue>,169						this: Option<ObjValue>,170					) -> Result<Thunk<Val>> {171						Ok(Thunk::evaluated(evaluate_named(172							s.clone(),173							self.uctx.bind(s, sup, this)?,174							&self.value,175							self.name.clone(),176						)?))177					}178				}179180				let name = evaluate_field_name(s.clone(), ctx.clone(), name)?;181				let name = if let Some(name) = name {182					name183				} else {184					continue;185				};186187				builder188					.member(name.clone())189					.with_add(*plus)190					.with_visibility(*visibility)191					.with_location(value.1.clone())192					.bindable(193						s.clone(),194						tb!(ObjMemberBinding {195							uctx: uctx.clone(),196							value: value.clone(),197							name: name.clone()198						}),199					)?;200			}201			Member::Field(FieldMember {202				name,203				params: Some(params),204				value,205				..206			}) => {207				#[derive(Trace)]208				struct ObjMemberBinding<B> {209					uctx: B,210					value: LocExpr,211					params: ParamsDesc,212					name: IStr,213				}214				impl<B: Bindable<Bound = Context>> Bindable for ObjMemberBinding<B> {215					type Bound = Thunk<Val>;216					fn bind(217						&self,218						s: State,219						sup: Option<ObjValue>,220						this: Option<ObjValue>,221					) -> Result<Thunk<Val>> {222						Ok(Thunk::evaluated(evaluate_method(223							self.uctx.bind(s, sup, this)?,224							self.name.clone(),225							self.params.clone(),226							self.value.clone(),227						)))228					}229				}230231				let name = if let Some(name) = evaluate_field_name(s.clone(), ctx.clone(), name)? {232					name233				} else {234					continue;235				};236237				builder238					.member(name.clone())239					.hide()240					.with_location(value.1.clone())241					.bindable(242						s.clone(),243						tb!(ObjMemberBinding {244							uctx: uctx.clone(),245							value: value.clone(),246							params: params.clone(),247							name: name.clone()248						}),249					)?;250			}251			Member::BindStmt(_) => {}252			Member::AssertStmt(stmt) => {253				#[derive(Trace)]254				struct ObjectAssert<B> {255					uctx: B,256					assert: AssertStmt,257				}258				impl<B: Bindable<Bound = Context>> ObjectAssertion for ObjectAssert<B> {259					fn run(260						&self,261						s: State,262						sup: Option<ObjValue>,263						this: Option<ObjValue>,264					) -> Result<()> {265						let ctx = self.uctx.bind(s.clone(), sup, this)?;266						evaluate_assert(s, ctx, &self.assert)267					}268				}269				builder.assert(tb!(ObjectAssert {270					uctx: uctx.clone(),271					assert: stmt.clone(),272				}));273			}274		}275	}276	let this = builder.build();277	let _ctx = ctx278		.extend(GcHashMap::new(), None, None, Some(this.clone()))279		.into_future(fctx);280	Ok(this)281}282283pub fn evaluate_object(s: State, ctx: Context, object: &ObjBody) -> Result<ObjValue> {284	Ok(match object {285		ObjBody::MemberList(members) => evaluate_member_list_object(s, ctx, members)?,286		ObjBody::ObjComp(obj) => {287			let mut builder = ObjValueBuilder::new();288			let locals = Rc::new(289				obj.pre_locals290					.iter()291					.chain(obj.post_locals.iter())292					.cloned()293					.collect::<Vec<_>>(),294			);295			let mut ctxs = vec![];296			evaluate_comp(s.clone(), ctx, &obj.compspecs, &mut |ctx| {297				let key = evaluate(s.clone(), ctx.clone(), &obj.key)?;298				let fctx = Context::new_future();299				ctxs.push((ctx, fctx.clone()));300				let uctx = evaluate_object_locals(fctx, locals.clone());301302				match key {303					Val::Null => {}304					Val::Str(n) => {305						#[derive(Trace)]306						struct ObjCompBinding<B> {307							uctx: B,308							value: LocExpr,309						}310						impl<B: Bindable<Bound = Context>> Bindable for ObjCompBinding<B> {311							type Bound = Thunk<Val>;312							fn bind(313								&self,314								s: State,315								sup: Option<ObjValue>,316								this: Option<ObjValue>,317							) -> Result<Thunk<Val>> {318								Ok(Thunk::evaluated(evaluate(319									s.clone(),320									self.uctx.bind(s, sup, this.clone())?.extend(321										GcHashMap::new(),322										None,323										None,324										this,325									),326									&self.value,327								)?))328							}329						}330						builder331							.member(n)332							.with_location(obj.value.1.clone())333							.with_add(obj.plus)334							.bindable(335								s.clone(),336								tb!(ObjCompBinding {337									uctx,338									value: obj.value.clone(),339								}),340							)?;341					}342					v => throw!(FieldMustBeStringGot(v.value_type())),343				}344345				Ok(())346			})?;347348			let this = builder.build();349			for (ctx, fctx) in ctxs {350				let _ctx = ctx351					.extend(GcHashMap::new(), None, None, Some(this.clone()))352					.into_future(fctx);353			}354			this355		}356	})357}358359pub fn evaluate_apply(360	s: State,361	ctx: Context,362	value: &LocExpr,363	args: &ArgsDesc,364	loc: CallLocation,365	tailstrict: bool,366) -> Result<Val> {367	let value = evaluate(s.clone(), ctx.clone(), value)?;368	Ok(match value {369		Val::Func(f) => {370			let body = || f.evaluate(s.clone(), ctx, loc, args, tailstrict);371			if tailstrict {372				body()?373			} else {374				s.push(loc, || format!("function <{}> call", f.name()), body)?375			}376		}377		v => throw!(OnlyFunctionsCanBeCalledGot(v.value_type())),378	})379}380381pub fn evaluate_assert(s: State, ctx: Context, assertion: &AssertStmt) -> Result<()> {382	let value = &assertion.0;383	let msg = &assertion.1;384	let assertion_result = s.push(385		CallLocation::new(&value.1),386		|| "assertion condition".to_owned(),387		|| bool::from_untyped(evaluate(s.clone(), ctx.clone(), value)?, s.clone()),388	)?;389	if !assertion_result {390		s.push(391			CallLocation::new(&value.1),392			|| "assertion failure".to_owned(),393			|| {394				if let Some(msg) = msg {395					throw!(AssertionFailed(396						evaluate(s.clone(), ctx, msg)?.to_string(s.clone())?397					));398				}399				throw!(AssertionFailed(Val::Null.to_string(s.clone())?));400			},401		)?;402	}403	Ok(())404}405406pub fn evaluate_named(s: State, ctx: Context, expr: &LocExpr, name: IStr) -> Result<Val> {407	use Expr::*;408	let LocExpr(raw_expr, _loc) = expr;409	Ok(match &**raw_expr {410		Function(params, body) => evaluate_method(ctx, name, params.clone(), body.clone()),411		_ => evaluate(s, ctx, expr)?,412	})413}414415#[allow(clippy::too_many_lines)]416pub fn evaluate(s: State, ctx: Context, expr: &LocExpr) -> Result<Val> {417	use Expr::*;418	let LocExpr(expr, loc) = expr;419	// let bp = with_state(|s| s.0.stop_at.borrow().clone());420	Ok(match &**expr {421		Literal(LiteralType::This) => {422			Val::Obj(ctx.this().clone().ok_or(CantUseSelfOutsideOfObject)?)423		}424		Literal(LiteralType::Super) => Val::Obj(425			ctx.super_obj().clone().ok_or(NoSuperFound)?.with_this(426				ctx.this()427					.clone()428					.expect("if super exists - then this should to"),429			),430		),431		Literal(LiteralType::Dollar) => {432			Val::Obj(ctx.dollar().clone().ok_or(NoTopLevelObjectFound)?)433		}434		Literal(LiteralType::True) => Val::Bool(true),435		Literal(LiteralType::False) => Val::Bool(false),436		Literal(LiteralType::Null) => Val::Null,437		Parened(e) => evaluate(s, ctx, e)?,438		Str(v) => Val::Str(v.clone()),439		Num(v) => Val::new_checked_num(*v)?,440		BinaryOp(v1, o, v2) => evaluate_binary_op_special(s, ctx, v1, *o, v2)?,441		UnaryOp(o, v) => evaluate_unary_op(*o, &evaluate(s, ctx, v)?)?,442		Var(name) => s.push(443			CallLocation::new(loc),444			|| format!("variable <{}> access", name),445			|| ctx.binding(name.clone())?.evaluate(s.clone()),446		)?,447		Index(value, index) => {448			match (449				evaluate(s.clone(), ctx.clone(), value)?,450				evaluate(s.clone(), ctx, index)?,451			) {452				(Val::Obj(v), Val::Str(key)) => s.push(453					CallLocation::new(loc),454					|| format!("field <{}> access", key),455					|| match v.get(s.clone(), key.clone()) {456						Ok(Some(v)) => Ok(v),457						Ok(None) => throw!(NoSuchField(key.clone())),458						Err(e) if matches!(e.error(), MagicThisFileUsed) => {459							Ok(Val::Str(loc.0.to_string_lossy().into()))460						}461						Err(e) => Err(e),462					},463				)?,464				(Val::Obj(_), n) => throw!(ValueIndexMustBeTypeGot(465					ValType::Obj,466					ValType::Str,467					n.value_type(),468				)),469470				(Val::Arr(v), Val::Num(n)) => {471					if n.fract() > f64::EPSILON {472						throw!(FractionalIndex)473					}474					v.get(s, n as usize)?475						.ok_or_else(|| ArrayBoundsError(n as usize, v.len()))?476				}477				(Val::Arr(_), Val::Str(n)) => throw!(AttemptedIndexAnArrayWithString(n)),478				(Val::Arr(_), n) => throw!(ValueIndexMustBeTypeGot(479					ValType::Arr,480					ValType::Num,481					n.value_type(),482				)),483484				(Val::Str(s), Val::Num(n)) => Val::Str({485					let v: IStr = s486						.chars()487						.skip(n as usize)488						.take(1)489						.collect::<String>()490						.into();491					if v.is_empty() {492						let size = s.chars().count();493						throw!(StringBoundsError(n as usize, size))494					}495					v496				}),497				(Val::Str(_), n) => throw!(ValueIndexMustBeTypeGot(498					ValType::Str,499					ValType::Num,500					n.value_type(),501				)),502503				(v, _) => throw!(CantIndexInto(v.value_type())),504			}505		}506		LocalExpr(bindings, returned) => {507			let mut new_bindings: GcHashMap<IStr, Thunk<Val>> =508				GcHashMap::with_capacity(bindings.len());509			let fctx = Context::new_future();510			for b in bindings {511				evaluate_dest(b, fctx.clone(), &mut new_bindings)?;512			}513			let ctx = ctx.extend(new_bindings, None, None, None).into_future(fctx);514			evaluate(s, ctx, &returned.clone())?515		}516		Arr(items) => {517			let mut out = Vec::with_capacity(items.len());518			for item in items {519				// TODO: Implement ArrValue::Lazy with same context for every element?520				#[derive(Trace)]521				struct ArrayElement {522					ctx: Context,523					item: LocExpr,524				}525				impl ThunkValue for ArrayElement {526					type Output = Val;527					fn get(self: Box<Self>, s: State) -> Result<Val> {528						evaluate(s, self.ctx, &self.item)529					}530				}531				out.push(Thunk::new(tb!(ArrayElement {532					ctx: ctx.clone(),533					item: item.clone(),534				})));535			}536			Val::Arr(out.into())537		}538		ArrComp(expr, comp_specs) => {539			let mut out = Vec::new();540			evaluate_comp(s.clone(), ctx, comp_specs, &mut |ctx| {541				out.push(evaluate(s.clone(), ctx, expr)?);542				Ok(())543			})?;544			Val::Arr(ArrValue::Eager(Cc::new(out)))545		}546		Obj(body) => Val::Obj(evaluate_object(s, ctx, body)?),547		ObjExtend(a, b) => evaluate_add_op(548			s.clone(),549			&evaluate(s.clone(), ctx.clone(), a)?,550			&Val::Obj(evaluate_object(s, ctx, b)?),551		)?,552		Apply(value, args, tailstrict) => {553			evaluate_apply(s, ctx, value, args, CallLocation::new(loc), *tailstrict)?554		}555		Function(params, body) => {556			evaluate_method(ctx, "anonymous".into(), params.clone(), body.clone())557		}558		Intrinsic(name) => Val::Func(FuncVal::StaticBuiltin(559			BUILTINS560				.with(|b| b.get(name).copied())561				.ok_or_else(|| IntrinsicNotFound(name.clone()))?,562		)),563		IntrinsicThisFile => return Err(MagicThisFileUsed.into()),564		IntrinsicId => Val::Func(FuncVal::identity()),565		AssertExpr(assert, returned) => {566			evaluate_assert(s.clone(), ctx.clone(), assert)?;567			evaluate(s, ctx, returned)?568		}569		ErrorStmt(e) => s.push(570			CallLocation::new(loc),571			|| "error statement".to_owned(),572			|| {573				throw!(RuntimeError(574					evaluate(s.clone(), ctx, e)?.to_string(s.clone())?,575				))576			},577		)?,578		IfElse {579			cond,580			cond_then,581			cond_else,582		} => {583			if s.push(584				CallLocation::new(loc),585				|| "if condition".to_owned(),586				|| bool::from_untyped(evaluate(s.clone(), ctx.clone(), &cond.0)?, s.clone()),587			)? {588				evaluate(s, ctx, cond_then)?589			} else {590				match cond_else {591					Some(v) => evaluate(s, ctx, v)?,592					None => Val::Null,593				}594			}595		}596		Slice(value, desc) => {597			fn parse_idx<T: Typed>(598				loc: CallLocation,599				s: State,600				ctx: &Context,601				expr: &Option<LocExpr>,602				desc: &'static str,603			) -> Result<Option<T>> {604				if let Some(value) = expr {605					Ok(Some(s.push(606						loc,607						|| format!("slice {}", desc),608						|| T::from_untyped(evaluate(s.clone(), ctx.clone(), value)?, s.clone()),609					)?))610				} else {611					Ok(None)612				}613			}614615			let indexable = evaluate(s.clone(), ctx.clone(), value)?;616			let loc = CallLocation::new(loc);617618			let start = parse_idx(loc, s.clone(), &ctx, &desc.start, "start")?;619			let end = parse_idx(loc, s.clone(), &ctx, &desc.end, "end")?;620			let step = parse_idx(loc, s, &ctx, &desc.step, "step")?;621622			std_slice(indexable.into_indexable()?, start, end, step)?623		}624		Import(path) => {625			let tmp = loc.clone().0;626			let mut import_location = tmp.to_path_buf();627			import_location.pop();628			s.push(629				CallLocation::new(loc),630				|| format!("import {:?}", path),631				|| s.import_file(&import_location, path),632			)?633		}634		ImportStr(path) => {635			let tmp = loc.clone().0;636			let mut import_location = tmp.to_path_buf();637			import_location.pop();638			Val::Str(s.import_file_str(&import_location, path)?)639		}640		ImportBin(path) => {641			let tmp = loc.clone().0;642			let mut import_location = tmp.to_path_buf();643			import_location.pop();644			let bytes = s.import_file_bin(&import_location, path)?;645			Val::Arr(ArrValue::Bytes(bytes))646		}647	})648}
after · crates/jrsonnet-evaluator/src/evaluate/mod.rs
1use std::rc::Rc;23use gcmodule::{Cc, Trace};4use jrsonnet_interner::IStr;5use jrsonnet_parser::{6	ArgsDesc, AssertStmt, BindSpec, CompSpec, Expr, FieldMember, FieldName, ForSpecData,7	IfSpecData, LiteralType, LocExpr, Member, ObjBody, ParamsDesc,8};9use jrsonnet_types::ValType;1011use crate::{12	destructure::evaluate_dest,13	error::Error::*,14	evaluate::operator::{evaluate_add_op, evaluate_binary_op_special, evaluate_unary_op},15	function::{CallLocation, FuncDesc, FuncVal},16	stdlib::{std_slice, BUILTINS},17	tb, throw,18	typed::Typed,19	val::{ArrValue, CachedUnbound, Thunk, ThunkValue},20	Context, GcHashMap, ObjValue, ObjValueBuilder, ObjectAssertion, Pending, Result, State,21	Unbound, Val,22};23pub mod destructure;24pub mod operator;2526pub fn evaluate_method(ctx: Context, name: IStr, params: ParamsDesc, body: LocExpr) -> Val {27	Val::Func(FuncVal::Normal(Cc::new(FuncDesc {28		name,29		ctx,30		params,31		body,32	})))33}3435pub fn evaluate_field_name(s: State, ctx: Context, field_name: &FieldName) -> Result<Option<IStr>> {36	Ok(match field_name {37		FieldName::Fixed(n) => Some(n.clone()),38		FieldName::Dyn(expr) => s.push(39			CallLocation::new(&expr.1),40			|| "evaluating field name".to_string(),41			|| {42				let value = evaluate(s.clone(), ctx, expr)?;43				if matches!(value, Val::Null) {44					Ok(None)45				} else {46					Ok(Some(IStr::from_untyped(value, s.clone())?))47				}48			},49		)?,50	})51}5253pub fn evaluate_comp(54	s: State,55	ctx: Context,56	specs: &[CompSpec],57	callback: &mut impl FnMut(Context) -> Result<()>,58) -> Result<()> {59	match specs.get(0) {60		None => callback(ctx)?,61		Some(CompSpec::IfSpec(IfSpecData(cond))) => {62			if bool::from_untyped(evaluate(s.clone(), ctx.clone(), cond)?, s.clone())? {63				evaluate_comp(s, ctx, &specs[1..], callback)?;64			}65		}66		Some(CompSpec::ForSpec(ForSpecData(var, expr))) => {67			match evaluate(s.clone(), ctx.clone(), expr)? {68				Val::Arr(list) => {69					for item in list.iter(s.clone()) {70						evaluate_comp(71							s.clone(),72							ctx.clone().with_var(var.clone(), item?.clone()),73							&specs[1..],74							callback,75						)?;76					}77				}78				_ => throw!(InComprehensionCanOnlyIterateOverArray),79			}80		}81	}82	Ok(())83}8485trait CloneableUnbound<T>: Unbound<Bound = T> + Clone {}8687fn evaluate_object_locals(88	fctx: Pending<Context>,89	locals: Rc<Vec<BindSpec>>,90) -> impl CloneableUnbound<Context> {91	#[derive(Trace, Clone)]92	struct UnboundLocals {93		fctx: Pending<Context>,94		locals: Rc<Vec<BindSpec>>,95	}96	impl CloneableUnbound<Context> for UnboundLocals {}97	impl Unbound for UnboundLocals {98		type Bound = Context;99100		fn bind(101			&self,102			_s: State,103			sup: Option<ObjValue>,104			this: Option<ObjValue>,105		) -> Result<Context> {106			let fctx = Context::new_future();107			let mut new_bindings = GcHashMap::new();108			for b in self.locals.iter() {109				evaluate_dest(b, fctx.clone(), &mut new_bindings)?;110			}111112			let ctx = self.fctx.unwrap();113			let new_dollar = ctx.dollar().clone().or_else(|| this.clone());114115			let ctx = ctx116				.extend(new_bindings, new_dollar, sup, this)117				.into_future(fctx);118119			Ok(ctx)120		}121	}122123	UnboundLocals { fctx, locals }124}125126#[allow(clippy::too_many_lines)]127pub fn evaluate_member_list_object(s: State, ctx: Context, members: &[Member]) -> Result<ObjValue> {128	let mut builder = ObjValueBuilder::new();129	let locals = Rc::new(130		members131			.iter()132			.filter_map(|m| match m {133				Member::BindStmt(bind) => Some(bind.clone()),134				_ => None,135			})136			.collect::<Vec<_>>(),137	);138139	let fctx = Context::new_future();140141	// We have single context for all fields, so we can cache binds142	let uctx = CachedUnbound::new(evaluate_object_locals(fctx.clone(), locals));143144	for member in members.iter() {145		match member {146			Member::Field(FieldMember {147				name,148				plus,149				params: None,150				visibility,151				value,152			}) => {153				#[derive(Trace)]154				struct UnboundValue<B> {155					uctx: B,156					value: LocExpr,157					name: IStr,158				}159				impl<B: Unbound<Bound = Context>> Unbound for UnboundValue<B> {160					type Bound = Thunk<Val>;161					fn bind(162						&self,163						s: State,164						sup: Option<ObjValue>,165						this: Option<ObjValue>,166					) -> Result<Thunk<Val>> {167						Ok(Thunk::evaluated(evaluate_named(168							s.clone(),169							self.uctx.bind(s, sup, this)?,170							&self.value,171							self.name.clone(),172						)?))173					}174				}175176				let name = evaluate_field_name(s.clone(), ctx.clone(), name)?;177				let name = if let Some(name) = name {178					name179				} else {180					continue;181				};182183				builder184					.member(name.clone())185					.with_add(*plus)186					.with_visibility(*visibility)187					.with_location(value.1.clone())188					.bindable(189						s.clone(),190						tb!(UnboundValue {191							uctx: uctx.clone(),192							value: value.clone(),193							name: name.clone()194						}),195					)?;196			}197			Member::Field(FieldMember {198				name,199				params: Some(params),200				value,201				..202			}) => {203				#[derive(Trace)]204				struct UnboundMethod<B> {205					uctx: B,206					value: LocExpr,207					params: ParamsDesc,208					name: IStr,209				}210				impl<B: Unbound<Bound = Context>> Unbound for UnboundMethod<B> {211					type Bound = Thunk<Val>;212					fn bind(213						&self,214						s: State,215						sup: Option<ObjValue>,216						this: Option<ObjValue>,217					) -> Result<Thunk<Val>> {218						Ok(Thunk::evaluated(evaluate_method(219							self.uctx.bind(s, sup, this)?,220							self.name.clone(),221							self.params.clone(),222							self.value.clone(),223						)))224					}225				}226227				let name = if let Some(name) = evaluate_field_name(s.clone(), ctx.clone(), name)? {228					name229				} else {230					continue;231				};232233				builder234					.member(name.clone())235					.hide()236					.with_location(value.1.clone())237					.bindable(238						s.clone(),239						tb!(UnboundMethod {240							uctx: uctx.clone(),241							value: value.clone(),242							params: params.clone(),243							name: name.clone()244						}),245					)?;246			}247			Member::BindStmt(_) => {}248			Member::AssertStmt(stmt) => {249				#[derive(Trace)]250				struct ObjectAssert<B> {251					uctx: B,252					assert: AssertStmt,253				}254				impl<B: Unbound<Bound = Context>> ObjectAssertion for ObjectAssert<B> {255					fn run(256						&self,257						s: State,258						sup: Option<ObjValue>,259						this: Option<ObjValue>,260					) -> Result<()> {261						let ctx = self.uctx.bind(s.clone(), sup, this)?;262						evaluate_assert(s, ctx, &self.assert)263					}264				}265				builder.assert(tb!(ObjectAssert {266					uctx: uctx.clone(),267					assert: stmt.clone(),268				}));269			}270		}271	}272	let this = builder.build();273	let _ctx = ctx274		.extend(GcHashMap::new(), None, None, Some(this.clone()))275		.into_future(fctx);276	Ok(this)277}278279pub fn evaluate_object(s: State, ctx: Context, object: &ObjBody) -> Result<ObjValue> {280	Ok(match object {281		ObjBody::MemberList(members) => evaluate_member_list_object(s, ctx, members)?,282		ObjBody::ObjComp(obj) => {283			let mut builder = ObjValueBuilder::new();284			let locals = Rc::new(285				obj.pre_locals286					.iter()287					.chain(obj.post_locals.iter())288					.cloned()289					.collect::<Vec<_>>(),290			);291			let mut ctxs = vec![];292			evaluate_comp(s.clone(), ctx, &obj.compspecs, &mut |ctx| {293				let key = evaluate(s.clone(), ctx.clone(), &obj.key)?;294				let fctx = Context::new_future();295				ctxs.push((ctx, fctx.clone()));296				let uctx = evaluate_object_locals(fctx, locals.clone());297298				match key {299					Val::Null => {}300					Val::Str(n) => {301						#[derive(Trace)]302						struct UnboundValue<B> {303							uctx: B,304							value: LocExpr,305						}306						impl<B: Unbound<Bound = Context>> Unbound for UnboundValue<B> {307							type Bound = Thunk<Val>;308							fn bind(309								&self,310								s: State,311								sup: Option<ObjValue>,312								this: Option<ObjValue>,313							) -> Result<Thunk<Val>> {314								Ok(Thunk::evaluated(evaluate(315									s.clone(),316									self.uctx.bind(s, sup, this.clone())?.extend(317										GcHashMap::new(),318										None,319										None,320										this,321									),322									&self.value,323								)?))324							}325						}326						builder327							.member(n)328							.with_location(obj.value.1.clone())329							.with_add(obj.plus)330							.bindable(331								s.clone(),332								tb!(UnboundValue {333									uctx,334									value: obj.value.clone(),335								}),336							)?;337					}338					v => throw!(FieldMustBeStringGot(v.value_type())),339				}340341				Ok(())342			})?;343344			let this = builder.build();345			for (ctx, fctx) in ctxs {346				let _ctx = ctx347					.extend(GcHashMap::new(), None, None, Some(this.clone()))348					.into_future(fctx);349			}350			this351		}352	})353}354355pub fn evaluate_apply(356	s: State,357	ctx: Context,358	value: &LocExpr,359	args: &ArgsDesc,360	loc: CallLocation,361	tailstrict: bool,362) -> Result<Val> {363	let value = evaluate(s.clone(), ctx.clone(), value)?;364	Ok(match value {365		Val::Func(f) => {366			let body = || f.evaluate(s.clone(), ctx, loc, args, tailstrict);367			if tailstrict {368				body()?369			} else {370				s.push(loc, || format!("function <{}> call", f.name()), body)?371			}372		}373		v => throw!(OnlyFunctionsCanBeCalledGot(v.value_type())),374	})375}376377pub fn evaluate_assert(s: State, ctx: Context, assertion: &AssertStmt) -> Result<()> {378	let value = &assertion.0;379	let msg = &assertion.1;380	let assertion_result = s.push(381		CallLocation::new(&value.1),382		|| "assertion condition".to_owned(),383		|| bool::from_untyped(evaluate(s.clone(), ctx.clone(), value)?, s.clone()),384	)?;385	if !assertion_result {386		s.push(387			CallLocation::new(&value.1),388			|| "assertion failure".to_owned(),389			|| {390				if let Some(msg) = msg {391					throw!(AssertionFailed(392						evaluate(s.clone(), ctx, msg)?.to_string(s.clone())?393					));394				}395				throw!(AssertionFailed(Val::Null.to_string(s.clone())?));396			},397		)?;398	}399	Ok(())400}401402pub fn evaluate_named(s: State, ctx: Context, expr: &LocExpr, name: IStr) -> Result<Val> {403	use Expr::*;404	let LocExpr(raw_expr, _loc) = expr;405	Ok(match &**raw_expr {406		Function(params, body) => evaluate_method(ctx, name, params.clone(), body.clone()),407		_ => evaluate(s, ctx, expr)?,408	})409}410411#[allow(clippy::too_many_lines)]412pub fn evaluate(s: State, ctx: Context, expr: &LocExpr) -> Result<Val> {413	use Expr::*;414	let LocExpr(expr, loc) = expr;415	// let bp = with_state(|s| s.0.stop_at.borrow().clone());416	Ok(match &**expr {417		Literal(LiteralType::This) => {418			Val::Obj(ctx.this().clone().ok_or(CantUseSelfOutsideOfObject)?)419		}420		Literal(LiteralType::Super) => Val::Obj(421			ctx.super_obj().clone().ok_or(NoSuperFound)?.with_this(422				ctx.this()423					.clone()424					.expect("if super exists - then this should to"),425			),426		),427		Literal(LiteralType::Dollar) => {428			Val::Obj(ctx.dollar().clone().ok_or(NoTopLevelObjectFound)?)429		}430		Literal(LiteralType::True) => Val::Bool(true),431		Literal(LiteralType::False) => Val::Bool(false),432		Literal(LiteralType::Null) => Val::Null,433		Parened(e) => evaluate(s, ctx, e)?,434		Str(v) => Val::Str(v.clone()),435		Num(v) => Val::new_checked_num(*v)?,436		BinaryOp(v1, o, v2) => evaluate_binary_op_special(s, ctx, v1, *o, v2)?,437		UnaryOp(o, v) => evaluate_unary_op(*o, &evaluate(s, ctx, v)?)?,438		Var(name) => s.push(439			CallLocation::new(loc),440			|| format!("variable <{}> access", name),441			|| ctx.binding(name.clone())?.evaluate(s.clone()),442		)?,443		Index(value, index) => {444			match (445				evaluate(s.clone(), ctx.clone(), value)?,446				evaluate(s.clone(), ctx, index)?,447			) {448				(Val::Obj(v), Val::Str(key)) => s.push(449					CallLocation::new(loc),450					|| format!("field <{}> access", key),451					|| match v.get(s.clone(), key.clone()) {452						Ok(Some(v)) => Ok(v),453						Ok(None) => throw!(NoSuchField(key.clone())),454						Err(e) if matches!(e.error(), MagicThisFileUsed) => {455							Ok(Val::Str(loc.0.to_string_lossy().into()))456						}457						Err(e) => Err(e),458					},459				)?,460				(Val::Obj(_), n) => throw!(ValueIndexMustBeTypeGot(461					ValType::Obj,462					ValType::Str,463					n.value_type(),464				)),465466				(Val::Arr(v), Val::Num(n)) => {467					if n.fract() > f64::EPSILON {468						throw!(FractionalIndex)469					}470					v.get(s, n as usize)?471						.ok_or_else(|| ArrayBoundsError(n as usize, v.len()))?472				}473				(Val::Arr(_), Val::Str(n)) => throw!(AttemptedIndexAnArrayWithString(n)),474				(Val::Arr(_), n) => throw!(ValueIndexMustBeTypeGot(475					ValType::Arr,476					ValType::Num,477					n.value_type(),478				)),479480				(Val::Str(s), Val::Num(n)) => Val::Str({481					let v: IStr = s482						.chars()483						.skip(n as usize)484						.take(1)485						.collect::<String>()486						.into();487					if v.is_empty() {488						let size = s.chars().count();489						throw!(StringBoundsError(n as usize, size))490					}491					v492				}),493				(Val::Str(_), n) => throw!(ValueIndexMustBeTypeGot(494					ValType::Str,495					ValType::Num,496					n.value_type(),497				)),498499				(v, _) => throw!(CantIndexInto(v.value_type())),500			}501		}502		LocalExpr(bindings, returned) => {503			let mut new_bindings: GcHashMap<IStr, Thunk<Val>> =504				GcHashMap::with_capacity(bindings.len());505			let fctx = Context::new_future();506			for b in bindings {507				evaluate_dest(b, fctx.clone(), &mut new_bindings)?;508			}509			let ctx = ctx.extend(new_bindings, None, None, None).into_future(fctx);510			evaluate(s, ctx, &returned.clone())?511		}512		Arr(items) => {513			let mut out = Vec::with_capacity(items.len());514			for item in items {515				// TODO: Implement ArrValue::Lazy with same context for every element?516				#[derive(Trace)]517				struct ArrayElement {518					ctx: Context,519					item: LocExpr,520				}521				impl ThunkValue for ArrayElement {522					type Output = Val;523					fn get(self: Box<Self>, s: State) -> Result<Val> {524						evaluate(s, self.ctx, &self.item)525					}526				}527				out.push(Thunk::new(tb!(ArrayElement {528					ctx: ctx.clone(),529					item: item.clone(),530				})));531			}532			Val::Arr(out.into())533		}534		ArrComp(expr, comp_specs) => {535			let mut out = Vec::new();536			evaluate_comp(s.clone(), ctx, comp_specs, &mut |ctx| {537				out.push(evaluate(s.clone(), ctx, expr)?);538				Ok(())539			})?;540			Val::Arr(ArrValue::Eager(Cc::new(out)))541		}542		Obj(body) => Val::Obj(evaluate_object(s, ctx, body)?),543		ObjExtend(a, b) => evaluate_add_op(544			s.clone(),545			&evaluate(s.clone(), ctx.clone(), a)?,546			&Val::Obj(evaluate_object(s, ctx, b)?),547		)?,548		Apply(value, args, tailstrict) => {549			evaluate_apply(s, ctx, value, args, CallLocation::new(loc), *tailstrict)?550		}551		Function(params, body) => {552			evaluate_method(ctx, "anonymous".into(), params.clone(), body.clone())553		}554		Intrinsic(name) => Val::Func(FuncVal::StaticBuiltin(555			BUILTINS556				.with(|b| b.get(name).copied())557				.ok_or_else(|| IntrinsicNotFound(name.clone()))?,558		)),559		IntrinsicThisFile => return Err(MagicThisFileUsed.into()),560		IntrinsicId => Val::Func(FuncVal::identity()),561		AssertExpr(assert, returned) => {562			evaluate_assert(s.clone(), ctx.clone(), assert)?;563			evaluate(s, ctx, returned)?564		}565		ErrorStmt(e) => s.push(566			CallLocation::new(loc),567			|| "error statement".to_owned(),568			|| {569				throw!(RuntimeError(570					evaluate(s.clone(), ctx, e)?.to_string(s.clone())?,571				))572			},573		)?,574		IfElse {575			cond,576			cond_then,577			cond_else,578		} => {579			if s.push(580				CallLocation::new(loc),581				|| "if condition".to_owned(),582				|| bool::from_untyped(evaluate(s.clone(), ctx.clone(), &cond.0)?, s.clone()),583			)? {584				evaluate(s, ctx, cond_then)?585			} else {586				match cond_else {587					Some(v) => evaluate(s, ctx, v)?,588					None => Val::Null,589				}590			}591		}592		Slice(value, desc) => {593			fn parse_idx<T: Typed>(594				loc: CallLocation,595				s: State,596				ctx: &Context,597				expr: &Option<LocExpr>,598				desc: &'static str,599			) -> Result<Option<T>> {600				if let Some(value) = expr {601					Ok(Some(s.push(602						loc,603						|| format!("slice {}", desc),604						|| T::from_untyped(evaluate(s.clone(), ctx.clone(), value)?, s.clone()),605					)?))606				} else {607					Ok(None)608				}609			}610611			let indexable = evaluate(s.clone(), ctx.clone(), value)?;612			let loc = CallLocation::new(loc);613614			let start = parse_idx(loc, s.clone(), &ctx, &desc.start, "start")?;615			let end = parse_idx(loc, s.clone(), &ctx, &desc.end, "end")?;616			let step = parse_idx(loc, s, &ctx, &desc.step, "step")?;617618			std_slice(indexable.into_indexable()?, start, end, step)?619		}620		Import(path) => {621			let tmp = loc.clone().0;622			let mut import_location = tmp.to_path_buf();623			import_location.pop();624			s.push(625				CallLocation::new(loc),626				|| format!("import {:?}", path),627				|| s.import_file(&import_location, path),628			)?629		}630		ImportStr(path) => {631			let tmp = loc.clone().0;632			let mut import_location = tmp.to_path_buf();633			import_location.pop();634			Val::Str(s.import_file_str(&import_location, path)?)635		}636		ImportBin(path) => {637			let tmp = loc.clone().0;638			let mut import_location = tmp.to_path_buf();639			import_location.pop();640			let bytes = s.import_file_bin(&import_location, path)?;641			Val::Arr(ArrValue::Bytes(bytes))642		}643	})644}
modifiedcrates/jrsonnet-evaluator/src/lib.rsdiffbeforeafterboth
--- a/crates/jrsonnet-evaluator/src/lib.rs
+++ b/crates/jrsonnet-evaluator/src/lib.rs
@@ -60,14 +60,14 @@
 use trace::{location_to_offset, offset_to_location, CodeLocation, CompactFormat, TraceFormat};
 pub use val::{ManifestFormat, Thunk, Val};
 
-pub trait Bindable: Trace + 'static {
+pub trait Unbound: Trace {
 	type Bound;
 	fn bind(&self, s: State, sup: Option<ObjValue>, this: Option<ObjValue>) -> Result<Self::Bound>;
 }
 
 #[derive(Clone, Trace)]
 pub enum LazyBinding {
-	Bindable(Cc<TraceBox<dyn Bindable<Bound = Thunk<Val>>>>),
+	Bindable(Cc<TraceBox<dyn Unbound<Bound = Thunk<Val>>>>),
 	Bound(Thunk<Val>),
 }
 
modifiedcrates/jrsonnet-evaluator/src/obj.rsdiffbeforeafterboth
--- a/crates/jrsonnet-evaluator/src/obj.rs
+++ b/crates/jrsonnet-evaluator/src/obj.rs
@@ -16,7 +16,7 @@
 	function::CallLocation,
 	gc::{GcHashMap, GcHashSet, TraceBox},
 	operator::evaluate_add_op,
-	throw, weak_ptr_eq, weak_raw, Bindable, LazyBinding, Result, State, Thunk, Val,
+	throw, weak_ptr_eq, weak_raw, LazyBinding, Result, State, Thunk, Unbound, Val,
 };
 
 #[cfg(not(feature = "exp-preserve-order"))]
@@ -589,7 +589,7 @@
 	pub fn bindable(
 		self,
 		s: State,
-		bindable: TraceBox<dyn Bindable<Bound = Thunk<Val>>>,
+		bindable: TraceBox<dyn Unbound<Bound = Thunk<Val>>>,
 	) -> Result<()> {
 		self.binding(s, LazyBinding::Bindable(Cc::new(bindable)))
 	}
@@ -613,7 +613,7 @@
 	pub fn value(self, value: Val) {
 		self.binding(LazyBinding::Bound(Thunk::evaluated(value)));
 	}
-	pub fn bindable(self, bindable: TraceBox<dyn Bindable<Bound = Thunk<Val>>>) {
+	pub fn bindable(self, bindable: TraceBox<dyn Unbound<Bound = Thunk<Val>>>) {
 		self.binding(LazyBinding::Bindable(Cc::new(bindable)));
 	}
 	pub fn binding(self, binding: LazyBinding) {
modifiedcrates/jrsonnet-evaluator/src/val.rsdiffbeforeafterboth
--- a/crates/jrsonnet-evaluator/src/val.rs
+++ b/crates/jrsonnet-evaluator/src/val.rs
@@ -12,7 +12,7 @@
 	stdlib::manifest::{
 		manifest_json_ex, manifest_yaml_ex, ManifestJsonOptions, ManifestType, ManifestYamlOptions,
 	},
-	throw, Bindable, ObjValue, Result, State, WeakObjValue,
+	throw, ObjValue, Result, State, Unbound, WeakObjValue,
 };
 
 pub trait ThunkValue: Trace {
@@ -74,14 +74,14 @@
 type CacheKey = (Option<WeakObjValue>, Option<WeakObjValue>);
 
 #[derive(Trace, Clone)]
-pub struct CachedBindable<I, T>
+pub struct CachedUnbound<I, T>
 where
-	I: Bindable<Bound = T>,
+	I: Unbound<Bound = T>,
 {
 	cache: Cc<RefCell<GcHashMap<CacheKey, T>>>,
 	value: I,
 }
-impl<I: Bindable<Bound = T>, T: Trace> CachedBindable<I, T> {
+impl<I: Unbound<Bound = T>, T: Trace> CachedUnbound<I, T> {
 	pub fn new(value: I) -> Self {
 		Self {
 			cache: Cc::new(RefCell::new(GcHashMap::new())),
@@ -89,7 +89,7 @@
 		}
 	}
 }
-impl<I: Bindable<Bound = T>, T: Clone + Trace> Bindable for CachedBindable<I, T> {
+impl<I: Unbound<Bound = T>, T: Clone + Trace> Unbound for CachedUnbound<I, T> {
 	type Bound = T;
 	fn bind(&self, s: State, sup: Option<ObjValue>, this: Option<ObjValue>) -> Result<T> {
 		let cache_key = (