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

difftreelog

source

crates/jrsonnet-evaluator/src/evaluate.rs17.6 KiBsourcehistory
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.with_super(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			Ok(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 = HashMap::new();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 = HashMap::new();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							Ok(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::Dollar) => {422			Val::Obj(context.dollar().clone().ok_or(NoTopLevelObjectFound)?)423		}424		Literal(LiteralType::True) => Val::Bool(true),425		Literal(LiteralType::False) => Val::Bool(false),426		Literal(LiteralType::Null) => Val::Null,427		Parened(e) => evaluate(context, e)?,428		Str(v) => Val::Str(v.clone()),429		Num(v) => Val::new_checked_num(*v)?,430		BinaryOp(v1, o, v2) => evaluate_binary_op_special(context, v1, *o, v2)?,431		UnaryOp(o, v) => evaluate_unary_op(*o, &evaluate(context, v)?)?,432		Var(name) => push(433			loc.as_ref(),434			|| format!("variable <{}>", name),435			|| Ok(context.binding(name.clone())?.evaluate()?),436		)?,437		Index(LocExpr(v, _), index) if matches!(&**v, Expr::Literal(LiteralType::Super)) => {438			let name = evaluate(context.clone(), index)?.try_cast_str("object index")?;439			context440				.super_obj()441				.clone()442				.expect("no super found")443				.get_raw(name, Some(&context.this().clone().expect("no this found")))?444				.expect("value not found")445		}446		Index(value, index) => {447			match (evaluate(context.clone(), value)?, evaluate(context, index)?) {448				(Val::Obj(v), Val::Str(s)) => {449					let sn = s.clone();450					push(451						loc.as_ref(),452						|| format!("field <{}> access", sn),453						|| {454							if let Some(v) = v.get(s.clone())? {455								Ok(v)456							} else if v.get("__intrinsic_namespace__".into())?.is_some() {457								Ok(Val::Func(Rc::new(FuncVal::Intrinsic(s))))458							} else {459								throw!(NoSuchField(s))460							}461						},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(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					s.chars()486						.skip(n as usize)487						.take(1)488						.collect::<String>()489						.into(),490				),491				(Val::Str(_), n) => throw!(ValueIndexMustBeTypeGot(492					ValType::Str,493					ValType::Num,494					n.value_type(),495				)),496497				(v, _) => throw!(CantIndexInto(v.value_type())),498			}499		}500		LocalExpr(bindings, returned) => {501			let mut new_bindings: HashMap<IStr, LazyBinding> = HashMap::new();502			let future_context = Context::new_future();503504			let context_creator = context_creator!(505				closure!(clone future_context, |_, _| Ok(future_context.clone().unwrap()))506			);507508			for (k, v) in bindings509				.iter()510				.map(|b| evaluate_binding(b, context_creator.clone()))511			{512				new_bindings.insert(k, v);513			}514515			let context = context516				.extend_unbound(new_bindings, None, None, None)?517				.into_future(future_context);518			evaluate(context, &returned.clone())?519		}520		Arr(items) => {521			let mut out = Vec::with_capacity(items.len());522			for item in items {523				out.push(LazyVal::new(Box::new(524					closure!(clone context, clone item, || {525						evaluate(context.clone(), &item)526					}),527				)));528			}529			Val::Arr(out.into())530		}531		ArrComp(expr, comp_specs) => Val::Arr(532			// First comp_spec should be for_spec, so no "None" possible here533			evaluate_comp(context, &|ctx| evaluate(ctx, expr), comp_specs)?534				.unwrap()535				.into(),536		),537		Obj(body) => Val::Obj(evaluate_object(context, body)?),538		ObjExtend(s, t) => evaluate_add_op(539			&evaluate(context.clone(), s)?,540			&Val::Obj(evaluate_object(context, t)?),541		)?,542		Apply(value, args, tailstrict) => {543			evaluate_apply(context, value, args, loc.as_ref(), *tailstrict)?544		}545		Function(params, body) => {546			evaluate_method(context, "anonymous".into(), params.clone(), body.clone())547		}548		Intrinsic(name) => Val::Func(Rc::new(FuncVal::Intrinsic(name.clone()))),549		AssertExpr(AssertStmt(value, msg), returned) => {550			let assertion_result = push(551				value.1.as_ref(),552				|| "assertion condition".to_owned(),553				|| {554					evaluate(context.clone(), value)?555						.try_cast_bool("assertion condition should be of type `boolean`")556				},557			)?;558			if assertion_result {559				evaluate(context, returned)?560			} else {561				push(562					value.1.as_ref(),563					|| "assertion failure".to_owned(),564					|| {565						if let Some(msg) = msg {566							throw!(AssertionFailed(evaluate(context, msg)?.to_string()?));567						} else {568							throw!(AssertionFailed(Val::Null.to_string()?));569						}570					},571				)?572			}573		}574		ErrorStmt(e) => push(575			loc.as_ref(),576			|| "error statement".to_owned(),577			|| {578				throw!(RuntimeError(579					evaluate(context, e)?.try_cast_str("error text should be of type `string`")?,580				))581			},582		)?,583		IfElse {584			cond,585			cond_then,586			cond_else,587		} => {588			if push(589				loc.as_ref(),590				|| "if condition".to_owned(),591				|| evaluate(context.clone(), &cond.0)?.try_cast_bool("in if condition"),592			)? {593				evaluate(context, cond_then)?594			} else {595				match cond_else {596					Some(v) => evaluate(context, v)?,597					None => Val::Null,598				}599			}600		}601		Import(path) => {602			let mut tmp = loc603				.clone()604				.expect("imports cannot be used without loc_data")605				.0;606			let import_location = Rc::make_mut(&mut tmp);607			import_location.pop();608			push(609				loc.as_ref(),610				|| format!("import {:?}", path),611				|| with_state(|s| s.import_file(import_location, path)),612			)?613		}614		ImportStr(path) => {615			let mut tmp = loc616				.clone()617				.expect("imports cannot be used without loc_data")618				.0;619			let import_location = Rc::make_mut(&mut tmp);620			import_location.pop();621			Val::Str(with_state(|s| s.import_file_str(import_location, path))?)622		}623		Literal(LiteralType::Super) => throw!(StandaloneSuper),624	})625}