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

difftreelog

source

crates/jrsonnet-evaluator/src/evaluate.rs17.4 KiBsourcehistory
1use crate::{2	error::Error::*, lazy_val, push, throw, with_state, Context, ContextCreator, FuncDesc, FuncVal,3	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, FxHasher};14use std::{collections::HashMap, hash::BuildHasherDefault, rc::Rc};1516pub fn evaluate_binding_in_future(17	b: &BindSpec,18	context_creator: FutureWrapper<Context>,19) -> LazyVal {20	let b = b.clone();21	if let Some(params) = &b.params {22		let params = params.clone();23		LazyVal::new(Box::new(move || {24			Ok(evaluate_method(25				context_creator.unwrap(),26				b.name.clone(),27				params.clone(),28				b.value.clone(),29			))30		}))31	} else {32		LazyVal::new(Box::new(move || {33			evaluate_named(context_creator.unwrap(), &b.value, b.name.clone())34		}))35	}36}3738pub fn evaluate_binding(b: &BindSpec, context_creator: ContextCreator) -> (IStr, LazyBinding) {39	let b = b.clone();40	if let Some(params) = &b.params {41		let params = params.clone();42		(43			b.name.clone(),44			LazyBinding::Bindable(Rc::new(move |this, super_obj| {45				Ok(lazy_val!(46					closure!(clone b, clone params, clone context_creator, || Ok(evaluate_method(47						context_creator.create(this.clone(), super_obj.clone())?,48						b.name.clone(),49						params.clone(),50						b.value.clone(),51					)))52				))53			})),54		)55	} else {56		(57			b.name.clone(),58			LazyBinding::Bindable(Rc::new(move |this, super_obj| {59				Ok(lazy_val!(closure!(clone context_creator, clone b, ||60					evaluate_named(61						context_creator.create(this.clone(), super_obj.clone())?,62						&b.value,63						b.name.clone()64					)65				)))66			})),67		)68	}69}7071pub fn evaluate_method(ctx: Context, name: IStr, params: ParamsDesc, body: LocExpr) -> Val {72	Val::Func(Rc::new(FuncVal::Normal(FuncDesc {73		name,74		ctx,75		params,76		body,77	})))78}7980pub fn evaluate_field_name(81	context: Context,82	field_name: &jrsonnet_parser::FieldName,83) -> Result<Option<IStr>> {84	Ok(match field_name {85		jrsonnet_parser::FieldName::Fixed(n) => Some(n.clone()),86		jrsonnet_parser::FieldName::Dyn(expr) => {87			let value = evaluate(context, expr)?;88			if matches!(value, Val::Null) {89				None90			} else {91				Some(value.try_cast_str("dynamic field name")?)92			}93		}94	})95}9697pub fn evaluate_unary_op(op: UnaryOpType, b: &Val) -> Result<Val> {98	Ok(match (op, b) {99		(UnaryOpType::Not, Val::Bool(v)) => Val::Bool(!v),100		(UnaryOpType::Minus, Val::Num(n)) => Val::Num(-*n),101		(UnaryOpType::BitNot, Val::Num(n)) => Val::Num(!(*n as i32) as f64),102		(op, o) => throw!(UnaryOperatorDoesNotOperateOnType(op, o.value_type())),103	})104}105106pub fn evaluate_add_op(a: &Val, b: &Val) -> Result<Val> {107	Ok(match (a, b) {108		(Val::Str(v1), Val::Str(v2)) => Val::Str(((**v1).to_owned() + v2).into()),109110		// Can't use generic json serialization way, because it depends on number to string concatenation (std.jsonnet:890)111		(Val::Num(n), Val::Str(o)) => Val::Str(format!("{}{}", n, o).into()),112		(Val::Str(o), Val::Num(n)) => Val::Str(format!("{}{}", o, n).into()),113114		(Val::Str(s), o) => Val::Str(format!("{}{}", s, o.clone().to_string()?).into()),115		(o, Val::Str(s)) => Val::Str(format!("{}{}", o.clone().to_string()?, s).into()),116117		(Val::Obj(v1), Val::Obj(v2)) => Val::Obj(v2.extend_from(v1.clone())),118		(Val::Arr(a), Val::Arr(b)) => {119			let mut out = Vec::with_capacity(a.len() + b.len());120			out.extend(a.iter_lazy());121			out.extend(b.iter_lazy());122			Val::Arr(out.into())123		}124		(Val::Num(v1), Val::Num(v2)) => Val::new_checked_num(v1 + v2)?,125		_ => throw!(BinaryOperatorDoesNotOperateOnValues(126			BinaryOpType::Add,127			a.value_type(),128			b.value_type(),129		)),130	})131}132133pub fn evaluate_binary_op_special(134	context: Context,135	a: &LocExpr,136	op: BinaryOpType,137	b: &LocExpr,138) -> Result<Val> {139	Ok(match (evaluate(context.clone(), a)?, op, b) {140		(Val::Bool(true), BinaryOpType::Or, _o) => Val::Bool(true),141		(Val::Bool(false), BinaryOpType::And, _o) => Val::Bool(false),142		(a, op, eb) => evaluate_binary_op_normal(&a, op, &evaluate(context, eb)?)?,143	})144}145146pub fn evaluate_binary_op_normal(a: &Val, op: BinaryOpType, b: &Val) -> Result<Val> {147	Ok(match (a, op, b) {148		(a, BinaryOpType::Add, b) => evaluate_add_op(a, b)?,149150		(Val::Str(v1), BinaryOpType::Mul, Val::Num(v2)) => Val::Str(v1.repeat(*v2 as usize).into()),151152		// Bool X Bool153		(Val::Bool(a), BinaryOpType::And, Val::Bool(b)) => Val::Bool(*a && *b),154		(Val::Bool(a), BinaryOpType::Or, Val::Bool(b)) => Val::Bool(*a || *b),155156		// Str X Str157		(Val::Str(v1), BinaryOpType::Lt, Val::Str(v2)) => Val::Bool(v1 < v2),158		(Val::Str(v1), BinaryOpType::Gt, Val::Str(v2)) => Val::Bool(v1 > v2),159		(Val::Str(v1), BinaryOpType::Lte, Val::Str(v2)) => Val::Bool(v1 <= v2),160		(Val::Str(v1), BinaryOpType::Gte, Val::Str(v2)) => Val::Bool(v1 >= v2),161162		// Num X Num163		(Val::Num(v1), BinaryOpType::Mul, Val::Num(v2)) => Val::new_checked_num(v1 * v2)?,164		(Val::Num(v1), BinaryOpType::Div, Val::Num(v2)) => {165			if *v2 <= f64::EPSILON {166				throw!(DivisionByZero)167			}168			Val::new_checked_num(v1 / v2)?169		}170171		(Val::Num(v1), BinaryOpType::Sub, Val::Num(v2)) => Val::new_checked_num(v1 - v2)?,172173		(Val::Num(v1), BinaryOpType::Lt, Val::Num(v2)) => Val::Bool(v1 < v2),174		(Val::Num(v1), BinaryOpType::Gt, Val::Num(v2)) => Val::Bool(v1 > v2),175		(Val::Num(v1), BinaryOpType::Lte, Val::Num(v2)) => Val::Bool(v1 <= v2),176		(Val::Num(v1), BinaryOpType::Gte, Val::Num(v2)) => Val::Bool(v1 >= v2),177178		(Val::Num(v1), BinaryOpType::BitAnd, Val::Num(v2)) => {179			Val::Num(((*v1 as i32) & (*v2 as i32)) as f64)180		}181		(Val::Num(v1), BinaryOpType::BitOr, Val::Num(v2)) => {182			Val::Num(((*v1 as i32) | (*v2 as i32)) as f64)183		}184		(Val::Num(v1), BinaryOpType::BitXor, Val::Num(v2)) => {185			Val::Num(((*v1 as i32) ^ (*v2 as i32)) as f64)186		}187		(Val::Num(v1), BinaryOpType::Lhs, Val::Num(v2)) => {188			if *v2 < 0.0 {189				throw!(RuntimeError("shift by negative exponent".into()))190			}191			Val::Num(((*v1 as i32) << (*v2 as i32)) as f64)192		}193		(Val::Num(v1), BinaryOpType::Rhs, Val::Num(v2)) => {194			if *v2 < 0.0 {195				throw!(RuntimeError("shift by negative exponent".into()))196			}197			Val::Num(((*v1 as i32) >> (*v2 as i32)) as f64)198		}199200		_ => throw!(BinaryOperatorDoesNotOperateOnValues(201			op,202			a.value_type(),203			b.value_type(),204		)),205	})206}207208pub fn evaluate_comp<T>(209	context: Context,210	value: &impl Fn(Context) -> Result<T>,211	specs: &[CompSpec],212) -> Result<Option<Vec<T>>> {213	Ok(match specs.get(0) {214		None => Some(vec![value(context)?]),215		Some(CompSpec::IfSpec(IfSpecData(cond))) => {216			if evaluate(context.clone(), cond)?.try_cast_bool("if spec")? {217				evaluate_comp(context, value, &specs[1..])?218			} else {219				None220			}221		}222		Some(CompSpec::ForSpec(ForSpecData(var, expr))) => match evaluate(context.clone(), expr)? {223			Val::Arr(list) => {224				let mut out = Vec::new();225				for item in list.iter() {226					out.push(evaluate_comp(227						context.clone().with_var(var.clone(), item?.clone()),228						value,229						&specs[1..],230					)?);231				}232				Some(out.into_iter().flatten().flatten().collect())233			}234			_ => throw!(InComprehensionCanOnlyIterateOverArray),235		},236	})237}238239pub fn evaluate_member_list_object(context: Context, members: &[Member]) -> Result<ObjValue> {240	let new_bindings = FutureWrapper::new();241	let future_this = FutureWrapper::new();242	let context_creator = ContextCreator(context.clone(), new_bindings.clone());243	{244		let mut bindings: FxHashMap<IStr, LazyBinding> =245			FxHashMap::with_capacity_and_hasher(members.len(), BuildHasherDefault::default());246		for (n, b) in members247			.iter()248			.filter_map(|m| match m {249				Member::BindStmt(b) => Some(b.clone()),250				_ => None,251			})252			.map(|b| evaluate_binding(&b, context_creator.clone()))253		{254			bindings.insert(n, b);255		}256		new_bindings.fill(bindings);257	}258259	let mut new_members = FxHashMap::default();260	for member in members.iter() {261		match member {262			Member::Field(FieldMember {263				name,264				plus,265				params: None,266				visibility,267				value,268			}) => {269				let name = evaluate_field_name(context.clone(), name)?;270				if name.is_none() {271					continue;272				}273				let name = name.unwrap();274				new_members.insert(275					name.clone(),276					ObjMember {277						add: *plus,278						visibility: *visibility,279						invoke: LazyBinding::Bindable(Rc::new(280							closure!(clone name, clone value, clone context_creator, |this, super_obj| {281								Ok(LazyVal::new_resolved(evaluate(282									context_creator.create(this, super_obj)?,283									&value,284								)?))285							}),286						)),287						location: value.1.clone(),288					},289				);290			}291			Member::Field(FieldMember {292				name,293				params: Some(params),294				value,295				..296			}) => {297				let name = evaluate_field_name(context.clone(), name)?;298				if name.is_none() {299					continue;300				}301				let name = name.unwrap();302				new_members.insert(303					name.clone(),304					ObjMember {305						add: false,306						visibility: Visibility::Hidden,307						invoke: LazyBinding::Bindable(Rc::new(308							closure!(clone value, clone context_creator, clone params, clone name, |this, super_obj| {309								// TODO: Assert310								Ok(LazyVal::new_resolved(evaluate_method(311									context_creator.create(this, super_obj)?,312									name.clone(),313									params.clone(),314									value.clone(),315								)))316							}),317						)),318						location: value.1.clone(),319					},320				);321			}322			Member::BindStmt(_) => {}323			Member::AssertStmt(_) => {}324		}325	}326	let this = ObjValue::new(None, Rc::new(new_members));327	future_this.fill(this.clone());328	Ok(this)329}330331pub fn evaluate_object(context: Context, object: &ObjBody) -> Result<ObjValue> {332	Ok(match object {333		ObjBody::MemberList(members) => evaluate_member_list_object(context, members)?,334		ObjBody::ObjComp(obj) => {335			let future_this = FutureWrapper::new();336			let mut new_members = FxHashMap::default();337			for (k, v) in evaluate_comp(338				context.clone(),339				&|ctx| {340					let new_bindings = FutureWrapper::new();341					let context_creator = ContextCreator(context.clone(), new_bindings.clone());342					let mut bindings: FxHashMap<IStr, LazyBinding> = FxHashMap::with_capacity_and_hasher(obj.pre_locals.len() + obj.post_locals.len(), BuildHasherDefault::default());343					for (n, b) in obj344						.pre_locals345						.iter()346						.chain(obj.post_locals.iter())347						.map(|b| evaluate_binding(b, context_creator.clone()))348					{349						bindings.insert(n, b);350					}351					new_bindings.fill(bindings.clone());352					let ctx = ctx.extend_unbound(bindings, None, None, None)?;353					let key = evaluate(ctx.clone(), &obj.key)?;354					let value = LazyBinding::Bindable(Rc::new(355						closure!(clone ctx, clone obj.value, |this, _super_obj| {356							Ok(LazyVal::new_resolved(evaluate(ctx.clone().extend(FxHashMap::default(), None, this, None), &value)?))357						}),358					));359360					Ok((key, value))361				},362				&obj.compspecs,363			)?364			.unwrap()365			{366				match k {367					Val::Null => {}368					Val::Str(n) => {369						new_members.insert(370							n,371							ObjMember {372								add: false,373								visibility: Visibility::Normal,374								invoke: v,375								location: obj.value.1.clone(),376							},377						);378					}379					v => throw!(FieldMustBeStringGot(v.value_type())),380				}381			}382383			let this = ObjValue::new(None, Rc::new(new_members));384			future_this.fill(this.clone());385			this386		}387	})388}389390pub fn evaluate_apply(391	context: Context,392	value: &LocExpr,393	args: &ArgsDesc,394	loc: Option<&ExprLocation>,395	tailstrict: bool,396) -> Result<Val> {397	let value = evaluate(context.clone(), value)?;398	Ok(match value {399		Val::Func(f) => {400			let body = || f.evaluate(context, loc, args, tailstrict);401			if tailstrict {402				body()?403			} else {404				push(loc, || format!("function <{}> call", f.name()), body)?405			}406		}407		v => throw!(OnlyFunctionsCanBeCalledGot(v.value_type())),408	})409}410411pub fn evaluate_named(context: Context, lexpr: &LocExpr, name: IStr) -> Result<Val> {412	use Expr::*;413	let LocExpr(expr, _loc) = lexpr;414	Ok(match &**expr {415		Function(params, body) => evaluate_method(context, name, params.clone(), body.clone()),416		_ => evaluate(context, lexpr)?,417	})418}419420pub fn evaluate(context: Context, expr: &LocExpr) -> Result<Val> {421	use Expr::*;422	let LocExpr(expr, loc) = expr;423	Ok(match &**expr {424		Literal(LiteralType::This) => {425			Val::Obj(context.this().clone().ok_or(CantUseSelfOutsideOfObject)?)426		}427		Literal(LiteralType::Super) => Val::Obj(428			context429				.super_obj()430				.clone()431				.ok_or(NoSuperFound)?432				.with_this(context.this().clone().unwrap()),433		),434		Literal(LiteralType::Dollar) => {435			Val::Obj(context.dollar().clone().ok_or(NoTopLevelObjectFound)?)436		}437		Literal(LiteralType::True) => Val::Bool(true),438		Literal(LiteralType::False) => Val::Bool(false),439		Literal(LiteralType::Null) => Val::Null,440		Parened(e) => evaluate(context, e)?,441		Str(v) => Val::Str(v.clone()),442		Num(v) => Val::new_checked_num(*v)?,443		BinaryOp(v1, o, v2) => evaluate_binary_op_special(context, v1, *o, v2)?,444		UnaryOp(o, v) => evaluate_unary_op(*o, &evaluate(context, v)?)?,445		Var(name) => push(446			loc.as_ref(),447			|| format!("variable <{}>", name),448			|| context.binding(name.clone())?.evaluate(),449		)?,450		Index(value, index) => {451			match (evaluate(context.clone(), value)?, evaluate(context, index)?) {452				(Val::Obj(v), Val::Str(s)) => {453					let sn = s.clone();454					push(455						loc.as_ref(),456						|| format!("field <{}> access", sn),457						|| {458							if let Some(v) = v.get(s.clone())? {459								Ok(v)460							} else if v.get("__intrinsic_namespace__".into())?.is_some() {461								Ok(Val::Func(Rc::new(FuncVal::Intrinsic(s))))462							} else {463								throw!(NoSuchField(s))464							}465						},466					)?467				}468				(Val::Obj(_), n) => throw!(ValueIndexMustBeTypeGot(469					ValType::Obj,470					ValType::Str,471					n.value_type(),472				)),473474				(Val::Arr(v), Val::Num(n)) => {475					if n.fract() > f64::EPSILON {476						throw!(FractionalIndex)477					}478					v.get(n as usize)?479						.ok_or_else(|| ArrayBoundsError(n as usize, v.len()))?480				}481				(Val::Arr(_), Val::Str(n)) => throw!(AttemptedIndexAnArrayWithString(n)),482				(Val::Arr(_), n) => throw!(ValueIndexMustBeTypeGot(483					ValType::Arr,484					ValType::Num,485					n.value_type(),486				)),487488				(Val::Str(s), Val::Num(n)) => Val::Str(489					s.chars()490						.skip(n as usize)491						.take(1)492						.collect::<String>()493						.into(),494				),495				(Val::Str(_), n) => throw!(ValueIndexMustBeTypeGot(496					ValType::Str,497					ValType::Num,498					n.value_type(),499				)),500501				(v, _) => throw!(CantIndexInto(v.value_type())),502			}503		}504		LocalExpr(bindings, returned) => {505			let mut new_bindings: FxHashMap<IStr, LazyVal> = HashMap::with_capacity_and_hasher(506				bindings.len(),507				BuildHasherDefault::<FxHasher>::default(),508			);509			let future_context = Context::new_future();510			for b in bindings {511				new_bindings.insert(512					b.name.clone(),513					evaluate_binding_in_future(b, future_context.clone()),514				);515			}516			let context = context517				.extend_bound(new_bindings)518				.into_future(future_context);519			evaluate(context, &returned.clone())?520		}521		Arr(items) => {522			let mut out = Vec::with_capacity(items.len());523			for item in items {524				out.push(LazyVal::new(Box::new(525					closure!(clone context, clone item, || {526						evaluate(context.clone(), &item)527					}),528				)));529			}530			Val::Arr(out.into())531		}532		ArrComp(expr, comp_specs) => Val::Arr(533			// First comp_spec should be for_spec, so no "None" possible here534			evaluate_comp(context, &|ctx| evaluate(ctx, expr), comp_specs)?535				.unwrap()536				.into(),537		),538		Obj(body) => Val::Obj(evaluate_object(context, body)?),539		ObjExtend(s, t) => evaluate_add_op(540			&evaluate(context.clone(), s)?,541			&Val::Obj(evaluate_object(context, t)?),542		)?,543		Apply(value, args, tailstrict) => {544			evaluate_apply(context, value, args, loc.as_ref(), *tailstrict)?545		}546		Function(params, body) => {547			evaluate_method(context, "anonymous".into(), params.clone(), body.clone())548		}549		Intrinsic(name) => Val::Func(Rc::new(FuncVal::Intrinsic(name.clone()))),550		AssertExpr(AssertStmt(value, msg), returned) => {551			let assertion_result = push(552				value.1.as_ref(),553				|| "assertion condition".to_owned(),554				|| {555					evaluate(context.clone(), value)?556						.try_cast_bool("assertion condition should be of type `boolean`")557				},558			)?;559			if assertion_result {560				evaluate(context, returned)?561			} else {562				push(563					value.1.as_ref(),564					|| "assertion failure".to_owned(),565					|| {566						if let Some(msg) = msg {567							throw!(AssertionFailed(evaluate(context, msg)?.to_string()?));568						} else {569							throw!(AssertionFailed(Val::Null.to_string()?));570						}571					},572				)?573			}574		}575		ErrorStmt(e) => push(576			loc.as_ref(),577			|| "error statement".to_owned(),578			|| {579				throw!(RuntimeError(580					evaluate(context, e)?.try_cast_str("error text should be of type `string`")?,581				))582			},583		)?,584		IfElse {585			cond,586			cond_then,587			cond_else,588		} => {589			if push(590				loc.as_ref(),591				|| "if condition".to_owned(),592				|| evaluate(context.clone(), &cond.0)?.try_cast_bool("in if condition"),593			)? {594				evaluate(context, cond_then)?595			} else {596				match cond_else {597					Some(v) => evaluate(context, v)?,598					None => Val::Null,599				}600			}601		}602		Import(path) => {603			let mut tmp = loc604				.clone()605				.expect("imports cannot be used without loc_data")606				.0;607			let import_location = Rc::make_mut(&mut tmp);608			import_location.pop();609			push(610				loc.as_ref(),611				|| format!("import {:?}", path),612				|| with_state(|s| s.import_file(import_location, path)),613			)?614		}615		ImportStr(path) => {616			let mut tmp = loc617				.clone()618				.expect("imports cannot be used without loc_data")619				.0;620			let import_location = Rc::make_mut(&mut tmp);621			import_location.pop();622			Val::Str(with_state(|s| s.import_file_str(import_location, path))?)623		}624	})625}