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

difftreelog

source

crates/jrsonnet-evaluator/src/evaluate/mod.rs16.3 KiBsourcehistory
1use std::{cmp::Ordering, rc::Rc};23use jrsonnet_gcmodule::{Cc, Trace};4use jrsonnet_interner::IStr;5use jrsonnet_parser::{6	ArgsDesc, AssertStmt, BindSpec, CompSpec, Expr, FieldMember, FieldName, ForSpecData,7	IfSpecData, LiteralType, LocExpr, Member, ObjBody, ParamsDesc,8};9use jrsonnet_types::ValType;1011use crate::{12	destructure::evaluate_dest,13	error::Error::*,14	evaluate::operator::{evaluate_add_op, evaluate_binary_op_special, evaluate_unary_op},15	function::{CallLocation, FuncDesc, FuncVal},16	tb, throw,17	typed::Typed,18	val::{ArrValue, CachedUnbound, IndexableVal, Thunk, ThunkValue},19	Context, GcHashMap, ObjValue, ObjValueBuilder, ObjectAssertion, Pending, Result, State,20	Unbound, Val,21};22pub mod destructure;23pub mod operator;2425pub fn evaluate_method(ctx: Context, name: IStr, params: ParamsDesc, body: LocExpr) -> Val {26	Val::Func(FuncVal::Normal(Cc::new(FuncDesc {27		name,28		ctx,29		params,30		body,31	})))32}3334pub fn evaluate_field_name(s: State, ctx: Context, field_name: &FieldName) -> Result<Option<IStr>> {35	Ok(match field_name {36		FieldName::Fixed(n) => Some(n.clone()),37		FieldName::Dyn(expr) => s.push(38			CallLocation::new(&expr.1),39			|| "evaluating field name".to_string(),40			|| {41				let value = evaluate(s.clone(), ctx, expr)?;42				if matches!(value, Val::Null) {43					Ok(None)44				} else {45					Ok(Some(IStr::from_untyped(value, s.clone())?))46				}47			},48		)?,49	})50}5152pub fn evaluate_comp(53	s: State,54	ctx: Context,55	specs: &[CompSpec],56	callback: &mut impl FnMut(Context) -> Result<()>,57) -> Result<()> {58	match specs.get(0) {59		None => callback(ctx)?,60		Some(CompSpec::IfSpec(IfSpecData(cond))) => {61			if bool::from_untyped(evaluate(s.clone(), ctx.clone(), cond)?, s.clone())? {62				evaluate_comp(s, ctx, &specs[1..], callback)?;63			}64		}65		Some(CompSpec::ForSpec(ForSpecData(var, expr))) => {66			match evaluate(s.clone(), ctx.clone(), expr)? {67				Val::Arr(list) => {68					for item in list.iter(s.clone()) {69						evaluate_comp(70							s.clone(),71							ctx.clone().with_var(var.clone(), item?.clone()),72							&specs[1..],73							callback,74						)?;75					}76				}77				_ => throw!(InComprehensionCanOnlyIterateOverArray),78			}79		}80	}81	Ok(())82}8384trait CloneableUnbound<T>: Unbound<Bound = T> + Clone {}8586fn evaluate_object_locals(87	fctx: Pending<Context>,88	locals: Rc<Vec<BindSpec>>,89) -> impl CloneableUnbound<Context> {90	#[derive(Trace, Clone)]91	struct UnboundLocals {92		fctx: Pending<Context>,93		locals: Rc<Vec<BindSpec>>,94	}95	impl CloneableUnbound<Context> for UnboundLocals {}96	impl Unbound for UnboundLocals {97		type Bound = Context;9899		fn bind(100			&self,101			_s: State,102			sup: Option<ObjValue>,103			this: Option<ObjValue>,104		) -> Result<Context> {105			let fctx = Context::new_future();106			let mut new_bindings = GcHashMap::new();107			for b in self.locals.iter() {108				evaluate_dest(b, fctx.clone(), &mut new_bindings)?;109			}110111			let ctx = self.fctx.unwrap();112			let new_dollar = ctx.dollar().clone().or_else(|| this.clone());113114			let ctx = ctx115				.extend(new_bindings, new_dollar, sup, this)116				.into_future(fctx);117118			Ok(ctx)119		}120	}121122	UnboundLocals { fctx, locals }123}124125#[allow(clippy::too_many_lines)]126pub fn evaluate_member_list_object(s: State, ctx: Context, members: &[Member]) -> Result<ObjValue> {127	let mut builder = ObjValueBuilder::new();128	let locals = Rc::new(129		members130			.iter()131			.filter_map(|m| match m {132				Member::BindStmt(bind) => Some(bind.clone()),133				_ => None,134			})135			.collect::<Vec<_>>(),136	);137138	let fctx = Context::new_future();139140	// We have single context for all fields, so we can cache binds141	let uctx = CachedUnbound::new(evaluate_object_locals(fctx.clone(), locals));142143	for member in members.iter() {144		match member {145			Member::Field(FieldMember {146				name,147				plus,148				params: None,149				visibility,150				value,151			}) => {152				#[derive(Trace)]153				struct UnboundValue<B: Trace> {154					uctx: B,155					value: LocExpr,156					name: IStr,157				}158				impl<B: Unbound<Bound = Context>> Unbound for UnboundValue<B> {159					type Bound = Thunk<Val>;160					fn bind(161						&self,162						s: State,163						sup: Option<ObjValue>,164						this: Option<ObjValue>,165					) -> Result<Thunk<Val>> {166						Ok(Thunk::evaluated(evaluate_named(167							s.clone(),168							self.uctx.bind(s, sup, this)?,169							&self.value,170							self.name.clone(),171						)?))172					}173				}174175				let name = evaluate_field_name(s.clone(), ctx.clone(), name)?;176				let name = if let Some(name) = name {177					name178				} else {179					continue;180				};181182				builder183					.member(name.clone())184					.with_add(*plus)185					.with_visibility(*visibility)186					.with_location(value.1.clone())187					.bindable(188						s.clone(),189						tb!(UnboundValue {190							uctx: uctx.clone(),191							value: value.clone(),192							name: name.clone()193						}),194					)?;195			}196			Member::Field(FieldMember {197				name,198				params: Some(params),199				value,200				..201			}) => {202				#[derive(Trace)]203				struct UnboundMethod<B: Trace> {204					uctx: B,205					value: LocExpr,206					params: ParamsDesc,207					name: IStr,208				}209				impl<B: Unbound<Bound = Context>> Unbound for UnboundMethod<B> {210					type Bound = Thunk<Val>;211					fn bind(212						&self,213						s: State,214						sup: Option<ObjValue>,215						this: Option<ObjValue>,216					) -> Result<Thunk<Val>> {217						Ok(Thunk::evaluated(evaluate_method(218							self.uctx.bind(s, sup, this)?,219							self.name.clone(),220							self.params.clone(),221							self.value.clone(),222						)))223					}224				}225226				let name = if let Some(name) = evaluate_field_name(s.clone(), ctx.clone(), name)? {227					name228				} else {229					continue;230				};231232				builder233					.member(name.clone())234					.hide()235					.with_location(value.1.clone())236					.bindable(237						s.clone(),238						tb!(UnboundMethod {239							uctx: uctx.clone(),240							value: value.clone(),241							params: params.clone(),242							name: name.clone()243						}),244					)?;245			}246			Member::BindStmt(_) => {}247			Member::AssertStmt(stmt) => {248				#[derive(Trace)]249				struct ObjectAssert<B: Trace> {250					uctx: B,251					assert: AssertStmt,252				}253				impl<B: Unbound<Bound = Context>> ObjectAssertion for ObjectAssert<B> {254					fn run(255						&self,256						s: State,257						sup: Option<ObjValue>,258						this: Option<ObjValue>,259					) -> Result<()> {260						let ctx = self.uctx.bind(s.clone(), sup, this)?;261						evaluate_assert(s, ctx, &self.assert)262					}263				}264				builder.assert(tb!(ObjectAssert {265					uctx: uctx.clone(),266					assert: stmt.clone(),267				}));268			}269		}270	}271	let this = builder.build();272	fctx.fill(ctx.extend(GcHashMap::new(), None, None, Some(this.clone())));273	Ok(this)274}275276pub fn evaluate_object(s: State, ctx: Context, object: &ObjBody) -> Result<ObjValue> {277	Ok(match object {278		ObjBody::MemberList(members) => evaluate_member_list_object(s, ctx, members)?,279		ObjBody::ObjComp(obj) => {280			let mut builder = ObjValueBuilder::new();281			let locals = Rc::new(282				obj.pre_locals283					.iter()284					.chain(obj.post_locals.iter())285					.cloned()286					.collect::<Vec<_>>(),287			);288			let mut ctxs = vec![];289			evaluate_comp(s.clone(), ctx, &obj.compspecs, &mut |ctx| {290				let key = evaluate(s.clone(), ctx.clone(), &obj.key)?;291				let fctx = Context::new_future();292				ctxs.push((ctx, fctx.clone()));293				let uctx = evaluate_object_locals(fctx, locals.clone());294295				match key {296					Val::Null => {}297					Val::Str(n) => {298						#[derive(Trace)]299						struct UnboundValue<B: Trace> {300							uctx: B,301							value: LocExpr,302						}303						impl<B: Unbound<Bound = Context>> Unbound for UnboundValue<B> {304							type Bound = Thunk<Val>;305							fn bind(306								&self,307								s: State,308								sup: Option<ObjValue>,309								this: Option<ObjValue>,310							) -> Result<Thunk<Val>> {311								Ok(Thunk::evaluated(evaluate(312									s.clone(),313									self.uctx.bind(s, sup, this.clone())?.extend(314										GcHashMap::new(),315										None,316										None,317										this,318									),319									&self.value,320								)?))321							}322						}323						builder324							.member(n)325							.with_location(obj.value.1.clone())326							.with_add(obj.plus)327							.bindable(328								s.clone(),329								tb!(UnboundValue {330									uctx,331									value: obj.value.clone(),332								}),333							)?;334					}335					v => throw!(FieldMustBeStringGot(v.value_type())),336				}337338				Ok(())339			})?;340341			let this = builder.build();342			for (ctx, fctx) in ctxs {343				let _ctx = ctx344					.extend(GcHashMap::new(), None, None, Some(this.clone()))345					.into_future(fctx);346			}347			this348		}349	})350}351352pub fn evaluate_apply(353	s: State,354	ctx: Context,355	value: &LocExpr,356	args: &ArgsDesc,357	loc: CallLocation<'_>,358	tailstrict: bool,359) -> Result<Val> {360	let value = evaluate(s.clone(), ctx.clone(), value)?;361	Ok(match value {362		Val::Func(f) => {363			let body = || f.evaluate(s.clone(), ctx, loc, args, tailstrict);364			if tailstrict {365				body()?366			} else {367				s.push(loc, || format!("function <{}> call", f.name()), body)?368			}369		}370		v => throw!(OnlyFunctionsCanBeCalledGot(v.value_type())),371	})372}373374pub fn evaluate_assert(s: State, ctx: Context, assertion: &AssertStmt) -> Result<()> {375	let value = &assertion.0;376	let msg = &assertion.1;377	let assertion_result = s.push(378		CallLocation::new(&value.1),379		|| "assertion condition".to_owned(),380		|| bool::from_untyped(evaluate(s.clone(), ctx.clone(), value)?, s.clone()),381	)?;382	if !assertion_result {383		s.push(384			CallLocation::new(&value.1),385			|| "assertion failure".to_owned(),386			|| {387				if let Some(msg) = msg {388					throw!(AssertionFailed(389						evaluate(s.clone(), ctx, msg)?.to_string(s.clone())?390					));391				}392				throw!(AssertionFailed(Val::Null.to_string(s.clone())?));393			},394		)?;395	}396	Ok(())397}398399pub fn evaluate_named(s: State, ctx: Context, expr: &LocExpr, name: IStr) -> Result<Val> {400	use Expr::*;401	let LocExpr(raw_expr, _loc) = expr;402	Ok(match &**raw_expr {403		Function(params, body) => evaluate_method(ctx, name, params.clone(), body.clone()),404		_ => evaluate(s, ctx, expr)?,405	})406}407408#[allow(clippy::too_many_lines)]409pub fn evaluate(s: State, ctx: Context, expr: &LocExpr) -> Result<Val> {410	use Expr::*;411	let LocExpr(expr, loc) = expr;412	// let bp = with_state(|s| s.0.stop_at.borrow().clone());413	Ok(match &**expr {414		Literal(LiteralType::This) => {415			Val::Obj(ctx.this().clone().ok_or(CantUseSelfOutsideOfObject)?)416		}417		Literal(LiteralType::Super) => Val::Obj(418			ctx.super_obj().clone().ok_or(NoSuperFound)?.with_this(419				ctx.this()420					.clone()421					.expect("if super exists - then this should to"),422			),423		),424		Literal(LiteralType::Dollar) => {425			Val::Obj(ctx.dollar().clone().ok_or(NoTopLevelObjectFound)?)426		}427		Literal(LiteralType::True) => Val::Bool(true),428		Literal(LiteralType::False) => Val::Bool(false),429		Literal(LiteralType::Null) => Val::Null,430		Parened(e) => evaluate(s, ctx, e)?,431		Str(v) => Val::Str(v.clone()),432		Num(v) => Val::new_checked_num(*v)?,433		BinaryOp(v1, o, v2) => evaluate_binary_op_special(s, ctx, v1, *o, v2)?,434		UnaryOp(o, v) => evaluate_unary_op(*o, &evaluate(s, ctx, v)?)?,435		Var(name) => s.push(436			CallLocation::new(loc),437			|| format!("variable <{name}> access"),438			|| ctx.binding(name.clone())?.evaluate(s.clone()),439		)?,440		Index(value, index) => {441			match (442				evaluate(s.clone(), ctx.clone(), value)?,443				evaluate(s.clone(), ctx, index)?,444			) {445				(Val::Obj(v), Val::Str(key)) => s.push(446					CallLocation::new(loc),447					|| format!("field <{key}> access"),448					|| match v.get(s.clone(), key.clone()) {449						Ok(Some(v)) => Ok(v),450						#[cfg(not(feature = "friendly-errors"))]451						Ok(None) => throw!(NoSuchField(key.clone(), vec![])),452						#[cfg(feature = "friendly-errors")]453						Ok(None) => {454							let mut heap = Vec::new();455							for field in v.fields_ex(456								true,457								#[cfg(feature = "exp-preserve-order")]458								false,459							) {460								let conf = strsim::jaro_winkler(&field as &str, &key as &str);461								if conf < 0.8 {462									continue;463								}464								heap.push((conf, field));465							}466							heap.sort_by(|a, b| b.0.partial_cmp(&a.0).unwrap_or(Ordering::Equal));467468							throw!(NoSuchField(469								key.clone(),470								heap.into_iter().map(|(_, v)| v).collect()471							))472						}473						Err(e) => Err(e),474					},475				)?,476				(Val::Obj(_), n) => throw!(ValueIndexMustBeTypeGot(477					ValType::Obj,478					ValType::Str,479					n.value_type(),480				)),481482				(Val::Arr(v), Val::Num(n)) => {483					if n.fract() > f64::EPSILON {484						throw!(FractionalIndex)485					}486					v.get(s, n as usize)?487						.ok_or_else(|| ArrayBoundsError(n as usize, v.len()))?488				}489				(Val::Arr(_), Val::Str(n)) => throw!(AttemptedIndexAnArrayWithString(n)),490				(Val::Arr(_), n) => throw!(ValueIndexMustBeTypeGot(491					ValType::Arr,492					ValType::Num,493					n.value_type(),494				)),495496				(Val::Str(s), Val::Num(n)) => Val::Str({497					let v: IStr = s498						.chars()499						.skip(n as usize)500						.take(1)501						.collect::<String>()502						.into();503					if v.is_empty() {504						let size = s.chars().count();505						throw!(StringBoundsError(n as usize, size))506					}507					v508				}),509				(Val::Str(_), n) => throw!(ValueIndexMustBeTypeGot(510					ValType::Str,511					ValType::Num,512					n.value_type(),513				)),514515				(v, _) => throw!(CantIndexInto(v.value_type())),516			}517		}518		LocalExpr(bindings, returned) => {519			let mut new_bindings: GcHashMap<IStr, Thunk<Val>> =520				GcHashMap::with_capacity(bindings.len());521			let fctx = Context::new_future();522			for b in bindings {523				evaluate_dest(b, fctx.clone(), &mut new_bindings)?;524			}525			let ctx = ctx.extend(new_bindings, None, None, None).into_future(fctx);526			evaluate(s, ctx, &returned.clone())?527		}528		Arr(items) => {529			let mut out = Vec::with_capacity(items.len());530			for item in items {531				// TODO: Implement ArrValue::Lazy with same context for every element?532				#[derive(Trace)]533				struct ArrayElement {534					ctx: Context,535					item: LocExpr,536				}537				impl ThunkValue for ArrayElement {538					type Output = Val;539					fn get(self: Box<Self>, s: State) -> Result<Val> {540						evaluate(s, self.ctx, &self.item)541					}542				}543				out.push(Thunk::new(tb!(ArrayElement {544					ctx: ctx.clone(),545					item: item.clone(),546				})));547			}548			Val::Arr(out.into())549		}550		ArrComp(expr, comp_specs) => {551			let mut out = Vec::new();552			evaluate_comp(s.clone(), ctx, comp_specs, &mut |ctx| {553				out.push(evaluate(s.clone(), ctx, expr)?);554				Ok(())555			})?;556			Val::Arr(ArrValue::Eager(Cc::new(out)))557		}558		Obj(body) => Val::Obj(evaluate_object(s, ctx, body)?),559		ObjExtend(a, b) => evaluate_add_op(560			s.clone(),561			&evaluate(s.clone(), ctx.clone(), a)?,562			&Val::Obj(evaluate_object(s, ctx, b)?),563		)?,564		Apply(value, args, tailstrict) => {565			evaluate_apply(s, ctx, value, args, CallLocation::new(loc), *tailstrict)?566		}567		Function(params, body) => {568			evaluate_method(ctx, "anonymous".into(), params.clone(), body.clone())569		}570		AssertExpr(assert, returned) => {571			evaluate_assert(s.clone(), ctx.clone(), assert)?;572			evaluate(s, ctx, returned)?573		}574		ErrorStmt(e) => s.push(575			CallLocation::new(loc),576			|| "error statement".to_owned(),577			|| {578				throw!(RuntimeError(579					evaluate(s.clone(), ctx, e)?.to_string(s.clone())?,580				))581			},582		)?,583		IfElse {584			cond,585			cond_then,586			cond_else,587		} => {588			if s.push(589				CallLocation::new(loc),590				|| "if condition".to_owned(),591				|| bool::from_untyped(evaluate(s.clone(), ctx.clone(), &cond.0)?, s.clone()),592			)? {593				evaluate(s, ctx, cond_then)?594			} else {595				match cond_else {596					Some(v) => evaluate(s, ctx, v)?,597					None => Val::Null,598				}599			}600		}601		Slice(value, desc) => {602			fn parse_idx<T: Typed>(603				loc: CallLocation<'_>,604				s: State,605				ctx: &Context,606				expr: &Option<LocExpr>,607				desc: &'static str,608			) -> Result<Option<T>> {609				if let Some(value) = expr {610					Ok(Some(s.push(611						loc,612						|| format!("slice {desc}"),613						|| T::from_untyped(evaluate(s.clone(), ctx.clone(), value)?, s.clone()),614					)?))615				} else {616					Ok(None)617				}618			}619620			let indexable = evaluate(s.clone(), ctx.clone(), value)?;621			let loc = CallLocation::new(loc);622623			let start = parse_idx(loc, s.clone(), &ctx, &desc.start, "start")?;624			let end = parse_idx(loc, s.clone(), &ctx, &desc.end, "end")?;625			let step = parse_idx(loc, s.clone(), &ctx, &desc.step, "step")?;626627			IndexableVal::into_untyped(indexable.into_indexable()?.slice(start, end, step)?, s)?628		}629		i @ (Import(path) | ImportStr(path) | ImportBin(path)) => {630			let tmp = loc.clone().0;631			let resolved_path = s.resolve_from(tmp.source_path(), path as &str)?;632			match i {633				Import(_) => s.push(634					CallLocation::new(loc),635					|| format!("import {:?}", path.clone()),636					|| s.import_resolved(resolved_path),637				)?,638				ImportStr(_) => Val::Str(s.import_resolved_str(resolved_path)?),639				ImportBin(_) => Val::Arr(ArrValue::Bytes(s.import_resolved_bin(resolved_path)?)),640				_ => unreachable!(),641			}642		}643	})644}