git.delta.rocks / jrsonnet / refs/commits / 1f53e1f057f6

difftreelog

refactor remove future_wrapper

Yaroslav Bolyukin2021-02-21parent: #be90068.patch.diff
in: master

3 files changed

modifiedcrates/jrsonnet-evaluator/src/ctx.rsdiffbeforeafterboth
--- a/crates/jrsonnet-evaluator/src/ctx.rs
+++ b/crates/jrsonnet-evaluator/src/ctx.rs
@@ -1,19 +1,17 @@
 use crate::{
-	error::Error::*, future_wrapper, map::LayeredHashMap, rc_fn_helper, resolved_lazy_val,
+	error::Error::*, map::LayeredHashMap, rc_fn_helper, resolved_lazy_val, FutureWrapper,
 	LazyBinding, LazyVal, ObjValue, Result, Val,
 };
 use jrsonnet_interner::IStr;
 use rustc_hash::FxHashMap;
 use std::hash::BuildHasherDefault;
-use std::{cell::RefCell, collections::HashMap, fmt::Debug, rc::Rc};
+use std::{collections::HashMap, fmt::Debug, rc::Rc};
 
 rc_fn_helper!(
 	ContextCreator,
 	context_creator,
 	dyn Fn(Option<ObjValue>, Option<ObjValue>) -> Result<Context>
 );
-
-future_wrapper!(Context, FutureContext);
 
 struct ContextInternals {
 	dollar: Option<ObjValue>,
@@ -33,8 +31,8 @@
 #[derive(Debug, Clone)]
 pub struct Context(Rc<ContextInternals>);
 impl Context {
-	pub fn new_future() -> FutureContext {
-		FutureContext(Rc::new(RefCell::new(None)))
+	pub fn new_future() -> FutureWrapper<Context> {
+		FutureWrapper::new()
 	}
 
 	pub fn dollar(&self) -> &Option<ObjValue> {
@@ -66,7 +64,7 @@
 			.cloned()
 			.ok_or(VariableIsNotDefined(name))?)
 	}
-	pub fn into_future(self, ctx: FutureContext) -> Self {
+	pub fn into_future(self, ctx: FutureWrapper<Context>) -> Self {
 		{
 			ctx.0.borrow_mut().replace(self);
 		}
modifiedcrates/jrsonnet-evaluator/src/dynamic.rsdiffbeforeafterboth
--- a/crates/jrsonnet-evaluator/src/dynamic.rs
+++ b/crates/jrsonnet-evaluator/src/dynamic.rs
@@ -1,31 +1,26 @@
-#[macro_export]
-macro_rules! future_wrapper {
-	($orig: ty, $wrapper: ident) => {
-		#[derive(Debug, Clone)]
-		pub struct $wrapper(pub std::rc::Rc<std::cell::RefCell<Option<$orig>>>);
-		impl $wrapper {
-			pub fn unwrap(self) -> $orig {
-				self.0.borrow().as_ref().map(|e| e.clone()).unwrap()
-			}
-			pub fn new() -> Self {
-				$wrapper(std::rc::Rc::new(std::cell::RefCell::new(None)))
-			}
-			pub fn fill(self, val: $orig) -> $orig {
-				if self.0.borrow().is_some() {
-					panic!("wrapper is filled already");
-				}
-				{
-					self.0.borrow_mut().replace(val);
-				}
-				self.unwrap()
-			}
-		}
-		impl Default for $wrapper {
-			fn default() -> Self {
-				Self::new()
-			}
-		}
-	};
+use std::{cell::RefCell, rc::Rc};
+
+#[derive(Clone)]
+pub struct FutureWrapper<V>(pub Rc<RefCell<Option<V>>>);
+impl<T> FutureWrapper<T> {
+	pub fn new() -> Self {
+		Self(Rc::new(RefCell::new(None)))
+	}
+	pub fn fill(self, value: T) {
+		assert!(self.0.borrow().is_none(), "wrapper is filled already");
+		self.0.borrow_mut().replace(value);
+	}
+}
+impl<T: Clone> FutureWrapper<T> {
+	pub fn unwrap(self) -> T {
+		self.0.borrow().as_ref().cloned().unwrap()
+	}
+}
+
+impl<T> Default for FutureWrapper<T> {
+	fn default() -> Self {
+		Self::new()
+	}
 }
 
 #[macro_export]
modifiedcrates/jrsonnet-evaluator/src/evaluate.rsdiffbeforeafterboth
before · crates/jrsonnet-evaluator/src/evaluate.rs
1use crate::{2	context_creator, error::Error::*, future_wrapper, lazy_val, push, throw, with_state, Context,3	ContextCreator, FuncDesc, FuncVal, LazyBinding, LazyVal, ObjMember, ObjValue, Result, Val,4};5use closure::closure;6use jrsonnet_interner::IStr;7use jrsonnet_parser::{8	ArgsDesc, AssertStmt, BinaryOpType, BindSpec, CompSpec, Expr, ExprLocation, FieldMember,9	ForSpecData, IfSpecData, LiteralType, LocExpr, Member, ObjBody, ParamsDesc, UnaryOpType,10	Visibility,11};12use jrsonnet_types::ValType;13use rustc_hash::FxHashMap;14use std::{collections::HashMap, rc::Rc};1516pub fn evaluate_binding(b: &BindSpec, context_creator: ContextCreator) -> (IStr, LazyBinding) {17	let b = b.clone();18	if let Some(params) = &b.params {19		let params = params.clone();20		(21			b.name.clone(),22			LazyBinding::Bindable(Rc::new(move |this, super_obj| {23				Ok(lazy_val!(24					closure!(clone b, clone params, clone context_creator, || Ok(evaluate_method(25						context_creator.0(this.clone(), super_obj.clone())?,26						b.name.clone(),27						params.clone(),28						b.value.clone(),29					)))30				))31			})),32		)33	} else {34		(35			b.name.clone(),36			LazyBinding::Bindable(Rc::new(move |this, super_obj| {37				Ok(lazy_val!(closure!(clone context_creator, clone b, ||38						evaluate_named(39							context_creator.0(this.clone(), super_obj.clone())?,40							&b.value,41							b.name.clone()42						)43				)))44			})),45		)46	}47}4849pub fn evaluate_method(ctx: Context, name: IStr, params: ParamsDesc, body: LocExpr) -> Val {50	Val::Func(Rc::new(FuncVal::Normal(FuncDesc {51		name,52		ctx,53		params,54		body,55	})))56}5758pub fn evaluate_field_name(59	context: Context,60	field_name: &jrsonnet_parser::FieldName,61) -> Result<Option<IStr>> {62	Ok(match field_name {63		jrsonnet_parser::FieldName::Fixed(n) => Some(n.clone()),64		jrsonnet_parser::FieldName::Dyn(expr) => {65			let value = evaluate(context, expr)?;66			if matches!(value, Val::Null) {67				None68			} else {69				Some(value.try_cast_str("dynamic field name")?)70			}71		}72	})73}7475pub fn evaluate_unary_op(op: UnaryOpType, b: &Val) -> Result<Val> {76	Ok(match (op, b) {77		(UnaryOpType::Not, Val::Bool(v)) => Val::Bool(!v),78		(UnaryOpType::Minus, Val::Num(n)) => Val::Num(-*n),79		(UnaryOpType::BitNot, Val::Num(n)) => Val::Num(!(*n as i32) as f64),80		(op, o) => throw!(UnaryOperatorDoesNotOperateOnType(op, o.value_type())),81	})82}8384pub fn evaluate_add_op(a: &Val, b: &Val) -> Result<Val> {85	Ok(match (a, b) {86		(Val::Str(v1), Val::Str(v2)) => Val::Str(((**v1).to_owned() + v2).into()),8788		// Can't use generic json serialization way, because it depends on number to string concatenation (std.jsonnet:890)89		(Val::Num(n), Val::Str(o)) => Val::Str(format!("{}{}", n, o).into()),90		(Val::Str(o), Val::Num(n)) => Val::Str(format!("{}{}", o, n).into()),9192		(Val::Str(s), o) => Val::Str(format!("{}{}", s, o.clone().to_string()?).into()),93		(o, Val::Str(s)) => Val::Str(format!("{}{}", o.clone().to_string()?, s).into()),9495		(Val::Obj(v1), Val::Obj(v2)) => Val::Obj(v2.extend_from(v1.clone())),96		(Val::Arr(a), Val::Arr(b)) => {97			let mut out = Vec::with_capacity(a.len() + b.len());98			out.extend(a.iter_lazy());99			out.extend(b.iter_lazy());100			Val::Arr(out.into())101		}102		(Val::Num(v1), Val::Num(v2)) => Val::new_checked_num(v1 + v2)?,103		_ => throw!(BinaryOperatorDoesNotOperateOnValues(104			BinaryOpType::Add,105			a.value_type(),106			b.value_type(),107		)),108	})109}110111pub fn evaluate_binary_op_special(112	context: Context,113	a: &LocExpr,114	op: BinaryOpType,115	b: &LocExpr,116) -> Result<Val> {117	Ok(match (evaluate(context.clone(), a)?, op, b) {118		(Val::Bool(true), BinaryOpType::Or, _o) => Val::Bool(true),119		(Val::Bool(false), BinaryOpType::And, _o) => Val::Bool(false),120		(a, op, eb) => evaluate_binary_op_normal(&a, op, &evaluate(context, eb)?)?,121	})122}123124pub fn evaluate_binary_op_normal(a: &Val, op: BinaryOpType, b: &Val) -> Result<Val> {125	Ok(match (a, op, b) {126		(a, BinaryOpType::Add, b) => evaluate_add_op(a, b)?,127128		(Val::Str(v1), BinaryOpType::Mul, Val::Num(v2)) => Val::Str(v1.repeat(*v2 as usize).into()),129130		// Bool X Bool131		(Val::Bool(a), BinaryOpType::And, Val::Bool(b)) => Val::Bool(*a && *b),132		(Val::Bool(a), BinaryOpType::Or, Val::Bool(b)) => Val::Bool(*a || *b),133134		// Str X Str135		(Val::Str(v1), BinaryOpType::Lt, Val::Str(v2)) => Val::Bool(v1 < v2),136		(Val::Str(v1), BinaryOpType::Gt, Val::Str(v2)) => Val::Bool(v1 > v2),137		(Val::Str(v1), BinaryOpType::Lte, Val::Str(v2)) => Val::Bool(v1 <= v2),138		(Val::Str(v1), BinaryOpType::Gte, Val::Str(v2)) => Val::Bool(v1 >= v2),139140		// Num X Num141		(Val::Num(v1), BinaryOpType::Mul, Val::Num(v2)) => Val::new_checked_num(v1 * v2)?,142		(Val::Num(v1), BinaryOpType::Div, Val::Num(v2)) => {143			if *v2 <= f64::EPSILON {144				throw!(DivisionByZero)145			}146			Val::new_checked_num(v1 / v2)?147		}148149		(Val::Num(v1), BinaryOpType::Sub, Val::Num(v2)) => Val::new_checked_num(v1 - v2)?,150151		(Val::Num(v1), BinaryOpType::Lt, Val::Num(v2)) => Val::Bool(v1 < v2),152		(Val::Num(v1), BinaryOpType::Gt, Val::Num(v2)) => Val::Bool(v1 > v2),153		(Val::Num(v1), BinaryOpType::Lte, Val::Num(v2)) => Val::Bool(v1 <= v2),154		(Val::Num(v1), BinaryOpType::Gte, Val::Num(v2)) => Val::Bool(v1 >= v2),155156		(Val::Num(v1), BinaryOpType::BitAnd, Val::Num(v2)) => {157			Val::Num(((*v1 as i32) & (*v2 as i32)) as f64)158		}159		(Val::Num(v1), BinaryOpType::BitOr, Val::Num(v2)) => {160			Val::Num(((*v1 as i32) | (*v2 as i32)) as f64)161		}162		(Val::Num(v1), BinaryOpType::BitXor, Val::Num(v2)) => {163			Val::Num(((*v1 as i32) ^ (*v2 as i32)) as f64)164		}165		(Val::Num(v1), BinaryOpType::Lhs, Val::Num(v2)) => {166			if *v2 < 0.0 {167				throw!(RuntimeError("shift by negative exponent".into()))168			}169			Val::Num(((*v1 as i32) << (*v2 as i32)) as f64)170		}171		(Val::Num(v1), BinaryOpType::Rhs, Val::Num(v2)) => {172			if *v2 < 0.0 {173				throw!(RuntimeError("shift by negative exponent".into()))174			}175			Val::Num(((*v1 as i32) >> (*v2 as i32)) as f64)176		}177178		_ => throw!(BinaryOperatorDoesNotOperateOnValues(179			op,180			a.value_type(),181			b.value_type(),182		)),183	})184}185186future_wrapper!(HashMap<IStr, LazyBinding>, FutureNewBindings);187future_wrapper!(ObjValue, FutureObjValue);188189pub fn evaluate_comp<T>(190	context: Context,191	value: &impl Fn(Context) -> Result<T>,192	specs: &[CompSpec],193) -> Result<Option<Vec<T>>> {194	Ok(match specs.get(0) {195		None => Some(vec![value(context)?]),196		Some(CompSpec::IfSpec(IfSpecData(cond))) => {197			if evaluate(context.clone(), cond)?.try_cast_bool("if spec")? {198				evaluate_comp(context, value, &specs[1..])?199			} else {200				None201			}202		}203		Some(CompSpec::ForSpec(ForSpecData(var, expr))) => match evaluate(context.clone(), expr)? {204			Val::Arr(list) => {205				let mut out = Vec::new();206				for item in list.iter() {207					out.push(evaluate_comp(208						context.clone().with_var(var.clone(), item?.clone()),209						value,210						&specs[1..],211					)?);212				}213				Some(out.into_iter().flatten().flatten().collect())214			}215			_ => throw!(InComprehensionCanOnlyIterateOverArray),216		},217	})218}219220pub fn evaluate_member_list_object(context: Context, members: &[Member]) -> Result<ObjValue> {221	let new_bindings = FutureNewBindings::new();222	let future_this = FutureObjValue::new();223	let context_creator = context_creator!(224		closure!(clone context, clone new_bindings, |this: Option<ObjValue>, super_obj: Option<ObjValue>| {225			context.clone().extend_unbound(226				new_bindings.clone().unwrap(),227				context.dollar().clone().or_else(||this.clone()),228				Some(this.unwrap()),229				super_obj230			)231		})232	);233	{234		let mut bindings: HashMap<IStr, LazyBinding> = HashMap::new();235		for (n, b) in members236			.iter()237			.filter_map(|m| match m {238				Member::BindStmt(b) => Some(b.clone()),239				_ => None,240			})241			.map(|b| evaluate_binding(&b, context_creator.clone()))242		{243			bindings.insert(n, b);244		}245		new_bindings.fill(bindings);246	}247248	let mut new_members = FxHashMap::default();249	for member in members.iter() {250		match member {251			Member::Field(FieldMember {252				name,253				plus,254				params: None,255				visibility,256				value,257			}) => {258				let name = evaluate_field_name(context.clone(), name)?;259				if name.is_none() {260					continue;261				}262				let name = name.unwrap();263				new_members.insert(264					name.clone(),265					ObjMember {266						add: *plus,267						visibility: *visibility,268						invoke: LazyBinding::Bindable(Rc::new(269							closure!(clone name, clone value, clone context_creator, |this, super_obj| {270								Ok(LazyVal::new_resolved(evaluate(271									context_creator.0(this, super_obj)?,272									&value,273								)?))274							}),275						)),276						location: value.1.clone(),277					},278				);279			}280			Member::Field(FieldMember {281				name,282				params: Some(params),283				value,284				..285			}) => {286				let name = evaluate_field_name(context.clone(), name)?;287				if name.is_none() {288					continue;289				}290				let name = name.unwrap();291				new_members.insert(292					name.clone(),293					ObjMember {294						add: false,295						visibility: Visibility::Hidden,296						invoke: LazyBinding::Bindable(Rc::new(297							closure!(clone value, clone context_creator, clone params, clone name, |this, super_obj| {298								// TODO: Assert299								Ok(LazyVal::new_resolved(evaluate_method(300									context_creator.0(this, super_obj)?,301									name.clone(),302									params.clone(),303									value.clone(),304								)))305							}),306						)),307						location: value.1.clone(),308					},309				);310			}311			Member::BindStmt(_) => {}312			Member::AssertStmt(_) => {}313		}314	}315	Ok(future_this.fill(ObjValue::new(None, Rc::new(new_members))))316}317318pub fn evaluate_object(context: Context, object: &ObjBody) -> Result<ObjValue> {319	Ok(match object {320		ObjBody::MemberList(members) => evaluate_member_list_object(context, members)?,321		ObjBody::ObjComp(obj) => {322			let future_this = FutureObjValue::new();323			let mut new_members = FxHashMap::default();324			for (k, v) in evaluate_comp(325				context.clone(),326				&|ctx| {327					let new_bindings = FutureNewBindings::new();328					let context_creator = context_creator!(329						closure!(clone context, clone new_bindings, |this: Option<ObjValue>, super_obj: Option<ObjValue>| {330							context.clone().extend_unbound(331								new_bindings.clone().unwrap(),332								context.dollar().clone().or_else(||this.clone()),333								None,334								super_obj335							)336						})337					);338					let mut bindings: HashMap<IStr, LazyBinding> = HashMap::new();339					for (n, b) in obj340						.pre_locals341						.iter()342						.chain(obj.post_locals.iter())343						.map(|b| evaluate_binding(b, context_creator.clone()))344					{345						bindings.insert(n, b);346					}347					let bindings = new_bindings.fill(bindings);348					let ctx = ctx.extend_unbound(bindings, None, None, None)?;349					let key = evaluate(ctx.clone(), &obj.key)?;350					let value = LazyBinding::Bindable(Rc::new(351						closure!(clone ctx, clone obj.value, |this, _super_obj| {352							Ok(LazyVal::new_resolved(evaluate(ctx.clone().extend(FxHashMap::default(), None, this, None), &value)?))353						}),354					));355356					Ok((key, value))357				},358				&obj.compspecs,359			)?360			.unwrap()361			{362				match k {363					Val::Null => {}364					Val::Str(n) => {365						new_members.insert(366							n,367							ObjMember {368								add: false,369								visibility: Visibility::Normal,370								invoke: v,371								location: obj.value.1.clone(),372							},373						);374					}375					v => throw!(FieldMustBeStringGot(v.value_type())),376				}377			}378379			future_this.fill(ObjValue::new(None, Rc::new(new_members)))380		}381	})382}383384pub fn evaluate_apply(385	context: Context,386	value: &LocExpr,387	args: &ArgsDesc,388	loc: Option<&ExprLocation>,389	tailstrict: bool,390) -> Result<Val> {391	let value = evaluate(context.clone(), value)?;392	Ok(match value {393		Val::Func(f) => {394			let body = || f.evaluate(context, loc, args, tailstrict);395			if tailstrict {396				body()?397			} else {398				push(loc, || format!("function <{}> call", f.name()), body)?399			}400		}401		v => throw!(OnlyFunctionsCanBeCalledGot(v.value_type())),402	})403}404405pub fn evaluate_named(context: Context, lexpr: &LocExpr, name: IStr) -> Result<Val> {406	use Expr::*;407	let LocExpr(expr, _loc) = lexpr;408	Ok(match &**expr {409		Function(params, body) => evaluate_method(context, name, params.clone(), body.clone()),410		_ => evaluate(context, lexpr)?,411	})412}413414pub fn evaluate(context: Context, expr: &LocExpr) -> Result<Val> {415	use Expr::*;416	let LocExpr(expr, loc) = expr;417	Ok(match &**expr {418		Literal(LiteralType::This) => {419			Val::Obj(context.this().clone().ok_or(CantUseSelfOutsideOfObject)?)420		}421		Literal(LiteralType::Super) => Val::Obj(422			context423				.super_obj()424				.clone()425				.ok_or(NoSuperFound)?426				.with_this(context.this().clone().unwrap()),427		),428		Literal(LiteralType::Dollar) => {429			Val::Obj(context.dollar().clone().ok_or(NoTopLevelObjectFound)?)430		}431		Literal(LiteralType::True) => Val::Bool(true),432		Literal(LiteralType::False) => Val::Bool(false),433		Literal(LiteralType::Null) => Val::Null,434		Parened(e) => evaluate(context, e)?,435		Str(v) => Val::Str(v.clone()),436		Num(v) => Val::new_checked_num(*v)?,437		BinaryOp(v1, o, v2) => evaluate_binary_op_special(context, v1, *o, v2)?,438		UnaryOp(o, v) => evaluate_unary_op(*o, &evaluate(context, v)?)?,439		Var(name) => push(440			loc.as_ref(),441			|| format!("variable <{}>", name),442			|| context.binding(name.clone())?.evaluate(),443		)?,444		Index(value, index) => {445			match (evaluate(context.clone(), value)?, evaluate(context, index)?) {446				(Val::Obj(v), Val::Str(s)) => {447					let sn = s.clone();448					push(449						loc.as_ref(),450						|| format!("field <{}> access", sn),451						|| {452							if let Some(v) = v.get(s.clone())? {453								Ok(v)454							} else if v.get("__intrinsic_namespace__".into())?.is_some() {455								Ok(Val::Func(Rc::new(FuncVal::Intrinsic(s))))456							} else {457								throw!(NoSuchField(s))458							}459						},460					)?461				}462				(Val::Obj(_), n) => throw!(ValueIndexMustBeTypeGot(463					ValType::Obj,464					ValType::Str,465					n.value_type(),466				)),467468				(Val::Arr(v), Val::Num(n)) => {469					if n.fract() > f64::EPSILON {470						throw!(FractionalIndex)471					}472					v.get(n as usize)?473						.ok_or_else(|| ArrayBoundsError(n as usize, v.len()))?474				}475				(Val::Arr(_), Val::Str(n)) => throw!(AttemptedIndexAnArrayWithString(n)),476				(Val::Arr(_), n) => throw!(ValueIndexMustBeTypeGot(477					ValType::Arr,478					ValType::Num,479					n.value_type(),480				)),481482				(Val::Str(s), Val::Num(n)) => Val::Str(483					s.chars()484						.skip(n as usize)485						.take(1)486						.collect::<String>()487						.into(),488				),489				(Val::Str(_), n) => throw!(ValueIndexMustBeTypeGot(490					ValType::Str,491					ValType::Num,492					n.value_type(),493				)),494495				(v, _) => throw!(CantIndexInto(v.value_type())),496			}497		}498		LocalExpr(bindings, returned) => {499			let mut new_bindings: HashMap<IStr, LazyBinding> = HashMap::new();500			let future_context = Context::new_future();501502			let context_creator = context_creator!(503				closure!(clone future_context, |_, _| Ok(future_context.clone().unwrap()))504			);505506			for (k, v) in bindings507				.iter()508				.map(|b| evaluate_binding(b, context_creator.clone()))509			{510				new_bindings.insert(k, v);511			}512513			let context = context514				.extend_unbound(new_bindings, None, None, None)?515				.into_future(future_context);516			evaluate(context, &returned.clone())?517		}518		Arr(items) => {519			let mut out = Vec::with_capacity(items.len());520			for item in items {521				out.push(LazyVal::new(Box::new(522					closure!(clone context, clone item, || {523						evaluate(context.clone(), &item)524					}),525				)));526			}527			Val::Arr(out.into())528		}529		ArrComp(expr, comp_specs) => Val::Arr(530			// First comp_spec should be for_spec, so no "None" possible here531			evaluate_comp(context, &|ctx| evaluate(ctx, expr), comp_specs)?532				.unwrap()533				.into(),534		),535		Obj(body) => Val::Obj(evaluate_object(context, body)?),536		ObjExtend(s, t) => evaluate_add_op(537			&evaluate(context.clone(), s)?,538			&Val::Obj(evaluate_object(context, t)?),539		)?,540		Apply(value, args, tailstrict) => {541			evaluate_apply(context, value, args, loc.as_ref(), *tailstrict)?542		}543		Function(params, body) => {544			evaluate_method(context, "anonymous".into(), params.clone(), body.clone())545		}546		Intrinsic(name) => Val::Func(Rc::new(FuncVal::Intrinsic(name.clone()))),547		AssertExpr(AssertStmt(value, msg), returned) => {548			let assertion_result = push(549				value.1.as_ref(),550				|| "assertion condition".to_owned(),551				|| {552					evaluate(context.clone(), value)?553						.try_cast_bool("assertion condition should be of type `boolean`")554				},555			)?;556			if assertion_result {557				evaluate(context, returned)?558			} else {559				push(560					value.1.as_ref(),561					|| "assertion failure".to_owned(),562					|| {563						if let Some(msg) = msg {564							throw!(AssertionFailed(evaluate(context, msg)?.to_string()?));565						} else {566							throw!(AssertionFailed(Val::Null.to_string()?));567						}568					},569				)?570			}571		}572		ErrorStmt(e) => push(573			loc.as_ref(),574			|| "error statement".to_owned(),575			|| {576				throw!(RuntimeError(577					evaluate(context, e)?.try_cast_str("error text should be of type `string`")?,578				))579			},580		)?,581		IfElse {582			cond,583			cond_then,584			cond_else,585		} => {586			if push(587				loc.as_ref(),588				|| "if condition".to_owned(),589				|| evaluate(context.clone(), &cond.0)?.try_cast_bool("in if condition"),590			)? {591				evaluate(context, cond_then)?592			} else {593				match cond_else {594					Some(v) => evaluate(context, v)?,595					None => Val::Null,596				}597			}598		}599		Import(path) => {600			let mut tmp = loc601				.clone()602				.expect("imports cannot be used without loc_data")603				.0;604			let import_location = Rc::make_mut(&mut tmp);605			import_location.pop();606			push(607				loc.as_ref(),608				|| format!("import {:?}", path),609				|| with_state(|s| s.import_file(import_location, path)),610			)?611		}612		ImportStr(path) => {613			let mut tmp = loc614				.clone()615				.expect("imports cannot be used without loc_data")616				.0;617			let import_location = Rc::make_mut(&mut tmp);618			import_location.pop();619			Val::Str(with_state(|s| s.import_file_str(import_location, path))?)620		}621	})622}
after · crates/jrsonnet-evaluator/src/evaluate.rs
1use crate::{2	context_creator, error::Error::*, lazy_val, push, throw, with_state, Context, ContextCreator,3	FuncDesc, FuncVal, FutureWrapper, LazyBinding, LazyVal, ObjMember, ObjValue, Result, Val,4};5use closure::closure;6use jrsonnet_interner::IStr;7use jrsonnet_parser::{8	ArgsDesc, AssertStmt, BinaryOpType, BindSpec, CompSpec, Expr, ExprLocation, FieldMember,9	ForSpecData, IfSpecData, LiteralType, LocExpr, Member, ObjBody, ParamsDesc, UnaryOpType,10	Visibility,11};12use jrsonnet_types::ValType;13use rustc_hash::FxHashMap;14use std::{collections::HashMap, rc::Rc};1516pub fn evaluate_binding(b: &BindSpec, context_creator: ContextCreator) -> (IStr, LazyBinding) {17	let b = b.clone();18	if let Some(params) = &b.params {19		let params = params.clone();20		(21			b.name.clone(),22			LazyBinding::Bindable(Rc::new(move |this, super_obj| {23				Ok(lazy_val!(24					closure!(clone b, clone params, clone context_creator, || Ok(evaluate_method(25						context_creator.0(this.clone(), super_obj.clone())?,26						b.name.clone(),27						params.clone(),28						b.value.clone(),29					)))30				))31			})),32		)33	} else {34		(35			b.name.clone(),36			LazyBinding::Bindable(Rc::new(move |this, super_obj| {37				Ok(lazy_val!(closure!(clone context_creator, clone b, ||38						evaluate_named(39							context_creator.0(this.clone(), super_obj.clone())?,40							&b.value,41							b.name.clone()42						)43				)))44			})),45		)46	}47}4849pub fn evaluate_method(ctx: Context, name: IStr, params: ParamsDesc, body: LocExpr) -> Val {50	Val::Func(Rc::new(FuncVal::Normal(FuncDesc {51		name,52		ctx,53		params,54		body,55	})))56}5758pub fn evaluate_field_name(59	context: Context,60	field_name: &jrsonnet_parser::FieldName,61) -> Result<Option<IStr>> {62	Ok(match field_name {63		jrsonnet_parser::FieldName::Fixed(n) => Some(n.clone()),64		jrsonnet_parser::FieldName::Dyn(expr) => {65			let value = evaluate(context, expr)?;66			if matches!(value, Val::Null) {67				None68			} else {69				Some(value.try_cast_str("dynamic field name")?)70			}71		}72	})73}7475pub fn evaluate_unary_op(op: UnaryOpType, b: &Val) -> Result<Val> {76	Ok(match (op, b) {77		(UnaryOpType::Not, Val::Bool(v)) => Val::Bool(!v),78		(UnaryOpType::Minus, Val::Num(n)) => Val::Num(-*n),79		(UnaryOpType::BitNot, Val::Num(n)) => Val::Num(!(*n as i32) as f64),80		(op, o) => throw!(UnaryOperatorDoesNotOperateOnType(op, o.value_type())),81	})82}8384pub fn evaluate_add_op(a: &Val, b: &Val) -> Result<Val> {85	Ok(match (a, b) {86		(Val::Str(v1), Val::Str(v2)) => Val::Str(((**v1).to_owned() + v2).into()),8788		// Can't use generic json serialization way, because it depends on number to string concatenation (std.jsonnet:890)89		(Val::Num(n), Val::Str(o)) => Val::Str(format!("{}{}", n, o).into()),90		(Val::Str(o), Val::Num(n)) => Val::Str(format!("{}{}", o, n).into()),9192		(Val::Str(s), o) => Val::Str(format!("{}{}", s, o.clone().to_string()?).into()),93		(o, Val::Str(s)) => Val::Str(format!("{}{}", o.clone().to_string()?, s).into()),9495		(Val::Obj(v1), Val::Obj(v2)) => Val::Obj(v2.extend_from(v1.clone())),96		(Val::Arr(a), Val::Arr(b)) => {97			let mut out = Vec::with_capacity(a.len() + b.len());98			out.extend(a.iter_lazy());99			out.extend(b.iter_lazy());100			Val::Arr(out.into())101		}102		(Val::Num(v1), Val::Num(v2)) => Val::new_checked_num(v1 + v2)?,103		_ => throw!(BinaryOperatorDoesNotOperateOnValues(104			BinaryOpType::Add,105			a.value_type(),106			b.value_type(),107		)),108	})109}110111pub fn evaluate_binary_op_special(112	context: Context,113	a: &LocExpr,114	op: BinaryOpType,115	b: &LocExpr,116) -> Result<Val> {117	Ok(match (evaluate(context.clone(), a)?, op, b) {118		(Val::Bool(true), BinaryOpType::Or, _o) => Val::Bool(true),119		(Val::Bool(false), BinaryOpType::And, _o) => Val::Bool(false),120		(a, op, eb) => evaluate_binary_op_normal(&a, op, &evaluate(context, eb)?)?,121	})122}123124pub fn evaluate_binary_op_normal(a: &Val, op: BinaryOpType, b: &Val) -> Result<Val> {125	Ok(match (a, op, b) {126		(a, BinaryOpType::Add, b) => evaluate_add_op(a, b)?,127128		(Val::Str(v1), BinaryOpType::Mul, Val::Num(v2)) => Val::Str(v1.repeat(*v2 as usize).into()),129130		// Bool X Bool131		(Val::Bool(a), BinaryOpType::And, Val::Bool(b)) => Val::Bool(*a && *b),132		(Val::Bool(a), BinaryOpType::Or, Val::Bool(b)) => Val::Bool(*a || *b),133134		// Str X Str135		(Val::Str(v1), BinaryOpType::Lt, Val::Str(v2)) => Val::Bool(v1 < v2),136		(Val::Str(v1), BinaryOpType::Gt, Val::Str(v2)) => Val::Bool(v1 > v2),137		(Val::Str(v1), BinaryOpType::Lte, Val::Str(v2)) => Val::Bool(v1 <= v2),138		(Val::Str(v1), BinaryOpType::Gte, Val::Str(v2)) => Val::Bool(v1 >= v2),139140		// Num X Num141		(Val::Num(v1), BinaryOpType::Mul, Val::Num(v2)) => Val::new_checked_num(v1 * v2)?,142		(Val::Num(v1), BinaryOpType::Div, Val::Num(v2)) => {143			if *v2 <= f64::EPSILON {144				throw!(DivisionByZero)145			}146			Val::new_checked_num(v1 / v2)?147		}148149		(Val::Num(v1), BinaryOpType::Sub, Val::Num(v2)) => Val::new_checked_num(v1 - v2)?,150151		(Val::Num(v1), BinaryOpType::Lt, Val::Num(v2)) => Val::Bool(v1 < v2),152		(Val::Num(v1), BinaryOpType::Gt, Val::Num(v2)) => Val::Bool(v1 > v2),153		(Val::Num(v1), BinaryOpType::Lte, Val::Num(v2)) => Val::Bool(v1 <= v2),154		(Val::Num(v1), BinaryOpType::Gte, Val::Num(v2)) => Val::Bool(v1 >= v2),155156		(Val::Num(v1), BinaryOpType::BitAnd, Val::Num(v2)) => {157			Val::Num(((*v1 as i32) & (*v2 as i32)) as f64)158		}159		(Val::Num(v1), BinaryOpType::BitOr, Val::Num(v2)) => {160			Val::Num(((*v1 as i32) | (*v2 as i32)) as f64)161		}162		(Val::Num(v1), BinaryOpType::BitXor, Val::Num(v2)) => {163			Val::Num(((*v1 as i32) ^ (*v2 as i32)) as f64)164		}165		(Val::Num(v1), BinaryOpType::Lhs, Val::Num(v2)) => {166			if *v2 < 0.0 {167				throw!(RuntimeError("shift by negative exponent".into()))168			}169			Val::Num(((*v1 as i32) << (*v2 as i32)) as f64)170		}171		(Val::Num(v1), BinaryOpType::Rhs, Val::Num(v2)) => {172			if *v2 < 0.0 {173				throw!(RuntimeError("shift by negative exponent".into()))174			}175			Val::Num(((*v1 as i32) >> (*v2 as i32)) as f64)176		}177178		_ => throw!(BinaryOperatorDoesNotOperateOnValues(179			op,180			a.value_type(),181			b.value_type(),182		)),183	})184}185186pub fn evaluate_comp<T>(187	context: Context,188	value: &impl Fn(Context) -> Result<T>,189	specs: &[CompSpec],190) -> Result<Option<Vec<T>>> {191	Ok(match specs.get(0) {192		None => Some(vec![value(context)?]),193		Some(CompSpec::IfSpec(IfSpecData(cond))) => {194			if evaluate(context.clone(), cond)?.try_cast_bool("if spec")? {195				evaluate_comp(context, value, &specs[1..])?196			} else {197				None198			}199		}200		Some(CompSpec::ForSpec(ForSpecData(var, expr))) => match evaluate(context.clone(), expr)? {201			Val::Arr(list) => {202				let mut out = Vec::new();203				for item in list.iter() {204					out.push(evaluate_comp(205						context.clone().with_var(var.clone(), item?.clone()),206						value,207						&specs[1..],208					)?);209				}210				Some(out.into_iter().flatten().flatten().collect())211			}212			_ => throw!(InComprehensionCanOnlyIterateOverArray),213		},214	})215}216217pub fn evaluate_member_list_object(context: Context, members: &[Member]) -> Result<ObjValue> {218	let new_bindings = FutureWrapper::new();219	let future_this = FutureWrapper::new();220	let context_creator = context_creator!(221		closure!(clone context, clone new_bindings, |this: Option<ObjValue>, super_obj: Option<ObjValue>| {222			context.clone().extend_unbound(223				new_bindings.clone().unwrap(),224				context.dollar().clone().or_else(||this.clone()),225				Some(this.unwrap()),226				super_obj227			)228		})229	);230	{231		let mut bindings: HashMap<IStr, LazyBinding> = HashMap::new();232		for (n, b) in members233			.iter()234			.filter_map(|m| match m {235				Member::BindStmt(b) => Some(b.clone()),236				_ => None,237			})238			.map(|b| evaluate_binding(&b, context_creator.clone()))239		{240			bindings.insert(n, b);241		}242		new_bindings.fill(bindings);243	}244245	let mut new_members = FxHashMap::default();246	for member in members.iter() {247		match member {248			Member::Field(FieldMember {249				name,250				plus,251				params: None,252				visibility,253				value,254			}) => {255				let name = evaluate_field_name(context.clone(), name)?;256				if name.is_none() {257					continue;258				}259				let name = name.unwrap();260				new_members.insert(261					name.clone(),262					ObjMember {263						add: *plus,264						visibility: *visibility,265						invoke: LazyBinding::Bindable(Rc::new(266							closure!(clone name, clone value, clone context_creator, |this, super_obj| {267								Ok(LazyVal::new_resolved(evaluate(268									context_creator.0(this, super_obj)?,269									&value,270								)?))271							}),272						)),273						location: value.1.clone(),274					},275				);276			}277			Member::Field(FieldMember {278				name,279				params: Some(params),280				value,281				..282			}) => {283				let name = evaluate_field_name(context.clone(), name)?;284				if name.is_none() {285					continue;286				}287				let name = name.unwrap();288				new_members.insert(289					name.clone(),290					ObjMember {291						add: false,292						visibility: Visibility::Hidden,293						invoke: LazyBinding::Bindable(Rc::new(294							closure!(clone value, clone context_creator, clone params, clone name, |this, super_obj| {295								// TODO: Assert296								Ok(LazyVal::new_resolved(evaluate_method(297									context_creator.0(this, super_obj)?,298									name.clone(),299									params.clone(),300									value.clone(),301								)))302							}),303						)),304						location: value.1.clone(),305					},306				);307			}308			Member::BindStmt(_) => {}309			Member::AssertStmt(_) => {}310		}311	}312	let this = ObjValue::new(None, Rc::new(new_members));313	future_this.fill(this.clone());314	Ok(this)315}316317pub fn evaluate_object(context: Context, object: &ObjBody) -> Result<ObjValue> {318	Ok(match object {319		ObjBody::MemberList(members) => evaluate_member_list_object(context, members)?,320		ObjBody::ObjComp(obj) => {321			let future_this = FutureWrapper::new();322			let mut new_members = FxHashMap::default();323			for (k, v) in evaluate_comp(324				context.clone(),325				&|ctx| {326					let new_bindings = FutureWrapper::new();327					let context_creator = context_creator!(328						closure!(clone context, clone new_bindings, |this: Option<ObjValue>, super_obj: Option<ObjValue>| {329							context.clone().extend_unbound(330								new_bindings.clone().unwrap(),331								context.dollar().clone().or_else(||this.clone()),332								None,333								super_obj334							)335						})336					);337					let mut bindings: HashMap<IStr, LazyBinding> = HashMap::new();338					for (n, b) in obj339						.pre_locals340						.iter()341						.chain(obj.post_locals.iter())342						.map(|b| evaluate_binding(b, context_creator.clone()))343					{344						bindings.insert(n, b);345					}346					new_bindings.fill(bindings.clone());347					let ctx = ctx.extend_unbound(bindings, None, None, None)?;348					let key = evaluate(ctx.clone(), &obj.key)?;349					let value = LazyBinding::Bindable(Rc::new(350						closure!(clone ctx, clone obj.value, |this, _super_obj| {351							Ok(LazyVal::new_resolved(evaluate(ctx.clone().extend(FxHashMap::default(), None, this, None), &value)?))352						}),353					));354355					Ok((key, value))356				},357				&obj.compspecs,358			)?359			.unwrap()360			{361				match k {362					Val::Null => {}363					Val::Str(n) => {364						new_members.insert(365							n,366							ObjMember {367								add: false,368								visibility: Visibility::Normal,369								invoke: v,370								location: obj.value.1.clone(),371							},372						);373					}374					v => throw!(FieldMustBeStringGot(v.value_type())),375				}376			}377378			let this = ObjValue::new(None, Rc::new(new_members));379			future_this.fill(this.clone());380			this381		}382	})383}384385pub fn evaluate_apply(386	context: Context,387	value: &LocExpr,388	args: &ArgsDesc,389	loc: Option<&ExprLocation>,390	tailstrict: bool,391) -> Result<Val> {392	let value = evaluate(context.clone(), value)?;393	Ok(match value {394		Val::Func(f) => {395			let body = || f.evaluate(context, loc, args, tailstrict);396			if tailstrict {397				body()?398			} else {399				push(loc, || format!("function <{}> call", f.name()), body)?400			}401		}402		v => throw!(OnlyFunctionsCanBeCalledGot(v.value_type())),403	})404}405406pub fn evaluate_named(context: Context, lexpr: &LocExpr, name: IStr) -> Result<Val> {407	use Expr::*;408	let LocExpr(expr, _loc) = lexpr;409	Ok(match &**expr {410		Function(params, body) => evaluate_method(context, name, params.clone(), body.clone()),411		_ => evaluate(context, lexpr)?,412	})413}414415pub fn evaluate(context: Context, expr: &LocExpr) -> Result<Val> {416	use Expr::*;417	let LocExpr(expr, loc) = expr;418	Ok(match &**expr {419		Literal(LiteralType::This) => {420			Val::Obj(context.this().clone().ok_or(CantUseSelfOutsideOfObject)?)421		}422		Literal(LiteralType::Super) => Val::Obj(423			context424				.super_obj()425				.clone()426				.ok_or(NoSuperFound)?427				.with_this(context.this().clone().unwrap()),428		),429		Literal(LiteralType::Dollar) => {430			Val::Obj(context.dollar().clone().ok_or(NoTopLevelObjectFound)?)431		}432		Literal(LiteralType::True) => Val::Bool(true),433		Literal(LiteralType::False) => Val::Bool(false),434		Literal(LiteralType::Null) => Val::Null,435		Parened(e) => evaluate(context, e)?,436		Str(v) => Val::Str(v.clone()),437		Num(v) => Val::new_checked_num(*v)?,438		BinaryOp(v1, o, v2) => evaluate_binary_op_special(context, v1, *o, v2)?,439		UnaryOp(o, v) => evaluate_unary_op(*o, &evaluate(context, v)?)?,440		Var(name) => push(441			loc.as_ref(),442			|| format!("variable <{}>", name),443			|| context.binding(name.clone())?.evaluate(),444		)?,445		Index(value, index) => {446			match (evaluate(context.clone(), value)?, evaluate(context, index)?) {447				(Val::Obj(v), Val::Str(s)) => {448					let sn = s.clone();449					push(450						loc.as_ref(),451						|| format!("field <{}> access", sn),452						|| {453							if let Some(v) = v.get(s.clone())? {454								Ok(v)455							} else if v.get("__intrinsic_namespace__".into())?.is_some() {456								Ok(Val::Func(Rc::new(FuncVal::Intrinsic(s))))457							} else {458								throw!(NoSuchField(s))459							}460						},461					)?462				}463				(Val::Obj(_), n) => throw!(ValueIndexMustBeTypeGot(464					ValType::Obj,465					ValType::Str,466					n.value_type(),467				)),468469				(Val::Arr(v), Val::Num(n)) => {470					if n.fract() > f64::EPSILON {471						throw!(FractionalIndex)472					}473					v.get(n as usize)?474						.ok_or_else(|| ArrayBoundsError(n as usize, v.len()))?475				}476				(Val::Arr(_), Val::Str(n)) => throw!(AttemptedIndexAnArrayWithString(n)),477				(Val::Arr(_), n) => throw!(ValueIndexMustBeTypeGot(478					ValType::Arr,479					ValType::Num,480					n.value_type(),481				)),482483				(Val::Str(s), Val::Num(n)) => Val::Str(484					s.chars()485						.skip(n as usize)486						.take(1)487						.collect::<String>()488						.into(),489				),490				(Val::Str(_), n) => throw!(ValueIndexMustBeTypeGot(491					ValType::Str,492					ValType::Num,493					n.value_type(),494				)),495496				(v, _) => throw!(CantIndexInto(v.value_type())),497			}498		}499		LocalExpr(bindings, returned) => {500			let mut new_bindings: HashMap<IStr, LazyBinding> = HashMap::new();501			let future_context = Context::new_future();502503			let context_creator = context_creator!(504				closure!(clone future_context, |_, _| Ok(future_context.clone().unwrap()))505			);506507			for (k, v) in bindings508				.iter()509				.map(|b| evaluate_binding(b, context_creator.clone()))510			{511				new_bindings.insert(k, v);512			}513514			let context = context515				.extend_unbound(new_bindings, None, None, None)?516				.into_future(future_context);517			evaluate(context, &returned.clone())?518		}519		Arr(items) => {520			let mut out = Vec::with_capacity(items.len());521			for item in items {522				out.push(LazyVal::new(Box::new(523					closure!(clone context, clone item, || {524						evaluate(context.clone(), &item)525					}),526				)));527			}528			Val::Arr(out.into())529		}530		ArrComp(expr, comp_specs) => Val::Arr(531			// First comp_spec should be for_spec, so no "None" possible here532			evaluate_comp(context, &|ctx| evaluate(ctx, expr), comp_specs)?533				.unwrap()534				.into(),535		),536		Obj(body) => Val::Obj(evaluate_object(context, body)?),537		ObjExtend(s, t) => evaluate_add_op(538			&evaluate(context.clone(), s)?,539			&Val::Obj(evaluate_object(context, t)?),540		)?,541		Apply(value, args, tailstrict) => {542			evaluate_apply(context, value, args, loc.as_ref(), *tailstrict)?543		}544		Function(params, body) => {545			evaluate_method(context, "anonymous".into(), params.clone(), body.clone())546		}547		Intrinsic(name) => Val::Func(Rc::new(FuncVal::Intrinsic(name.clone()))),548		AssertExpr(AssertStmt(value, msg), returned) => {549			let assertion_result = push(550				value.1.as_ref(),551				|| "assertion condition".to_owned(),552				|| {553					evaluate(context.clone(), value)?554						.try_cast_bool("assertion condition should be of type `boolean`")555				},556			)?;557			if assertion_result {558				evaluate(context, returned)?559			} else {560				push(561					value.1.as_ref(),562					|| "assertion failure".to_owned(),563					|| {564						if let Some(msg) = msg {565							throw!(AssertionFailed(evaluate(context, msg)?.to_string()?));566						} else {567							throw!(AssertionFailed(Val::Null.to_string()?));568						}569					},570				)?571			}572		}573		ErrorStmt(e) => push(574			loc.as_ref(),575			|| "error statement".to_owned(),576			|| {577				throw!(RuntimeError(578					evaluate(context, e)?.try_cast_str("error text should be of type `string`")?,579				))580			},581		)?,582		IfElse {583			cond,584			cond_then,585			cond_else,586		} => {587			if push(588				loc.as_ref(),589				|| "if condition".to_owned(),590				|| evaluate(context.clone(), &cond.0)?.try_cast_bool("in if condition"),591			)? {592				evaluate(context, cond_then)?593			} else {594				match cond_else {595					Some(v) => evaluate(context, v)?,596					None => Val::Null,597				}598			}599		}600		Import(path) => {601			let mut tmp = loc602				.clone()603				.expect("imports cannot be used without loc_data")604				.0;605			let import_location = Rc::make_mut(&mut tmp);606			import_location.pop();607			push(608				loc.as_ref(),609				|| format!("import {:?}", path),610				|| with_state(|s| s.import_file(import_location, path)),611			)?612		}613		ImportStr(path) => {614			let mut tmp = loc615				.clone()616				.expect("imports cannot be used without loc_data")617				.0;618			let import_location = Rc::make_mut(&mut tmp);619			import_location.pop();620			Val::Str(with_state(|s| s.import_file_str(import_location, path))?)621		}622	})623}