git.delta.rocks / jrsonnet / refs/commits / 09a4bd7b68d6

difftreelog

source

crates/jrsonnet-evaluator/src/evaluate/mod.rs18.2 KiBsourcehistory
1use crate::{2	builtin::std_slice,3	error::Error::*,4	evaluate::operator::{evaluate_add_op, evaluate_binary_op_special, evaluate_unary_op},5	push_frame, 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					.bindable(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							.with_add(obj.plus)435							.bindable(Box::new(ObjCompBinding {436								context: ctx,437								value: obj.value.clone(),438							}));439					}440					v => throw!(FieldMustBeStringGot(v.value_type())),441				}442443				Ok(())444			})?;445446			let this = builder.build();447			future_this.fill(this.clone());448			this449		}450	})451}452453pub fn evaluate_apply(454	context: Context,455	value: &LocExpr,456	args: &ArgsDesc,457	loc: Option<&ExprLocation>,458	tailstrict: bool,459) -> Result<Val> {460	let value = evaluate(context.clone(), value)?;461	Ok(match value {462		Val::Func(f) => {463			let body = || f.evaluate(context, loc, args, tailstrict);464			if tailstrict {465				body()?466			} else {467				push_frame(loc, || format!("function <{}> call", f.name()), body)?468			}469		}470		v => throw!(OnlyFunctionsCanBeCalledGot(v.value_type())),471	})472}473474pub fn evaluate_assert(context: Context, assertion: &AssertStmt) -> Result<()> {475	let value = &assertion.0;476	let msg = &assertion.1;477	let assertion_result = push_frame(478		value.1.as_ref(),479		|| "assertion condition".to_owned(),480		|| {481			evaluate(context.clone(), value)?482				.try_cast_bool("assertion condition should be of type `boolean`")483		},484	)?;485	if !assertion_result {486		push_frame(487			value.1.as_ref(),488			|| "assertion failure".to_owned(),489			|| {490				if let Some(msg) = msg {491					throw!(AssertionFailed(evaluate(context, msg)?.to_string()?));492				} else {493					throw!(AssertionFailed(Val::Null.to_string()?));494				}495			},496		)?497	}498	Ok(())499}500501pub fn evaluate_named(context: Context, lexpr: &LocExpr, name: IStr) -> Result<Val> {502	use Expr::*;503	let LocExpr(expr, _loc) = lexpr;504	Ok(match &**expr {505		Function(params, body) => evaluate_method(context, name, params.clone(), body.clone()),506		_ => evaluate(context, lexpr)?,507	})508}509510pub fn evaluate(context: Context, expr: &LocExpr) -> Result<Val> {511	use Expr::*;512	let LocExpr(expr, loc) = expr;513	// let bp = with_state(|s| s.0.stop_at.borrow().clone());514	Ok(match &**expr {515		Literal(LiteralType::This) => {516			Val::Obj(context.this().clone().ok_or(CantUseSelfOutsideOfObject)?)517		}518		Literal(LiteralType::Super) => Val::Obj(519			context520				.super_obj()521				.clone()522				.ok_or(NoSuperFound)?523				.with_this(context.this().clone().unwrap()),524		),525		Literal(LiteralType::Dollar) => {526			Val::Obj(context.dollar().clone().ok_or(NoTopLevelObjectFound)?)527		}528		Literal(LiteralType::True) => Val::Bool(true),529		Literal(LiteralType::False) => Val::Bool(false),530		Literal(LiteralType::Null) => Val::Null,531		Parened(e) => evaluate(context, e)?,532		Str(v) => Val::Str(v.clone()),533		Num(v) => Val::new_checked_num(*v)?,534		BinaryOp(v1, o, v2) => evaluate_binary_op_special(context, v1, *o, v2)?,535		UnaryOp(o, v) => evaluate_unary_op(*o, &evaluate(context, v)?)?,536		Var(name) => push_frame(537			loc.as_ref(),538			|| format!("variable <{}>", name),539			|| context.binding(name.clone())?.evaluate(),540		)?,541		Index(value, index) => {542			match (evaluate(context.clone(), value)?, evaluate(context, index)?) {543				(Val::Obj(v), Val::Str(s)) => {544					let sn = s.clone();545					push_frame(546						loc.as_ref(),547						|| format!("field <{}> access", sn),548						|| {549							if let Some(v) = v.get(s.clone())? {550								Ok(v)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_frame(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_frame(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.into_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_frame(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}