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

difftreelog

source

crates/jrsonnet-evaluator/src/evaluate/mod.rs16.8 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	stdlib::{std_slice, BUILTINS},17	tb, throw,18	typed::Typed,19	val::{ArrValue, CachedUnbound, Thunk, ThunkValue},20	Context, GcHashMap, ObjValue, ObjValueBuilder, ObjectAssertion, Pending, Result, State,21	Unbound, Val,22};23pub mod destructure;24pub mod operator;2526pub fn evaluate_method(ctx: Context, name: IStr, params: ParamsDesc, body: LocExpr) -> Val {27	Val::Func(FuncVal::Normal(Cc::new(FuncDesc {28		name,29		ctx,30		params,31		body,32	})))33}3435pub fn evaluate_field_name(s: State, ctx: Context, field_name: &FieldName) -> Result<Option<IStr>> {36	Ok(match field_name {37		FieldName::Fixed(n) => Some(n.clone()),38		FieldName::Dyn(expr) => s.push(39			CallLocation::new(&expr.1),40			|| "evaluating field name".to_string(),41			|| {42				let value = evaluate(s.clone(), ctx, expr)?;43				if matches!(value, Val::Null) {44					Ok(None)45				} else {46					Ok(Some(IStr::from_untyped(value, s.clone())?))47				}48			},49		)?,50	})51}5253pub fn evaluate_comp(54	s: State,55	ctx: Context,56	specs: &[CompSpec],57	callback: &mut impl FnMut(Context) -> Result<()>,58) -> Result<()> {59	match specs.get(0) {60		None => callback(ctx)?,61		Some(CompSpec::IfSpec(IfSpecData(cond))) => {62			if bool::from_untyped(evaluate(s.clone(), ctx.clone(), cond)?, s.clone())? {63				evaluate_comp(s, ctx, &specs[1..], callback)?;64			}65		}66		Some(CompSpec::ForSpec(ForSpecData(var, expr))) => {67			match evaluate(s.clone(), ctx.clone(), expr)? {68				Val::Arr(list) => {69					for item in list.iter(s.clone()) {70						evaluate_comp(71							s.clone(),72							ctx.clone().with_var(var.clone(), item?.clone()),73							&specs[1..],74							callback,75						)?;76					}77				}78				_ => throw!(InComprehensionCanOnlyIterateOverArray),79			}80		}81	}82	Ok(())83}8485trait CloneableUnbound<T>: Unbound<Bound = T> + Clone {}8687fn evaluate_object_locals(88	fctx: Pending<Context>,89	locals: Rc<Vec<BindSpec>>,90) -> impl CloneableUnbound<Context> {91	#[derive(Trace, Clone)]92	struct UnboundLocals {93		fctx: Pending<Context>,94		locals: Rc<Vec<BindSpec>>,95	}96	impl CloneableUnbound<Context> for UnboundLocals {}97	impl Unbound for UnboundLocals {98		type Bound = Context;99100		fn bind(101			&self,102			_s: State,103			sup: Option<ObjValue>,104			this: Option<ObjValue>,105		) -> Result<Context> {106			let fctx = Context::new_future();107			let mut new_bindings = GcHashMap::new();108			for b in self.locals.iter() {109				evaluate_dest(b, fctx.clone(), &mut new_bindings)?;110			}111112			let ctx = self.fctx.unwrap();113			let new_dollar = ctx.dollar().clone().or_else(|| this.clone());114115			let ctx = ctx116				.extend(new_bindings, new_dollar, sup, this)117				.into_future(fctx);118119			Ok(ctx)120		}121	}122123	UnboundLocals { fctx, locals }124}125126#[allow(clippy::too_many_lines)]127pub fn evaluate_member_list_object(s: State, ctx: Context, members: &[Member]) -> Result<ObjValue> {128	let mut builder = ObjValueBuilder::new();129	let locals = Rc::new(130		members131			.iter()132			.filter_map(|m| match m {133				Member::BindStmt(bind) => Some(bind.clone()),134				_ => None,135			})136			.collect::<Vec<_>>(),137	);138139	let fctx = Context::new_future();140141	// We have single context for all fields, so we can cache binds142	let uctx = CachedUnbound::new(evaluate_object_locals(fctx.clone(), locals));143144	for member in members.iter() {145		match member {146			Member::Field(FieldMember {147				name,148				plus,149				params: None,150				visibility,151				value,152			}) => {153				#[derive(Trace)]154				struct UnboundValue<B: Trace> {155					uctx: B,156					value: LocExpr,157					name: IStr,158				}159				impl<B: Unbound<Bound = Context>> Unbound for UnboundValue<B> {160					type Bound = Thunk<Val>;161					fn bind(162						&self,163						s: State,164						sup: Option<ObjValue>,165						this: Option<ObjValue>,166					) -> Result<Thunk<Val>> {167						Ok(Thunk::evaluated(evaluate_named(168							s.clone(),169							self.uctx.bind(s, sup, this)?,170							&self.value,171							self.name.clone(),172						)?))173					}174				}175176				let name = evaluate_field_name(s.clone(), ctx.clone(), name)?;177				let name = if let Some(name) = name {178					name179				} else {180					continue;181				};182183				builder184					.member(name.clone())185					.with_add(*plus)186					.with_visibility(*visibility)187					.with_location(value.1.clone())188					.bindable(189						s.clone(),190						tb!(UnboundValue {191							uctx: uctx.clone(),192							value: value.clone(),193							name: name.clone()194						}),195					)?;196			}197			Member::Field(FieldMember {198				name,199				params: Some(params),200				value,201				..202			}) => {203				#[derive(Trace)]204				struct UnboundMethod<B: Trace> {205					uctx: B,206					value: LocExpr,207					params: ParamsDesc,208					name: IStr,209				}210				impl<B: Unbound<Bound = Context>> Unbound for UnboundMethod<B> {211					type Bound = Thunk<Val>;212					fn bind(213						&self,214						s: State,215						sup: Option<ObjValue>,216						this: Option<ObjValue>,217					) -> Result<Thunk<Val>> {218						Ok(Thunk::evaluated(evaluate_method(219							self.uctx.bind(s, sup, this)?,220							self.name.clone(),221							self.params.clone(),222							self.value.clone(),223						)))224					}225				}226227				let name = if let Some(name) = evaluate_field_name(s.clone(), ctx.clone(), name)? {228					name229				} else {230					continue;231				};232233				builder234					.member(name.clone())235					.hide()236					.with_location(value.1.clone())237					.bindable(238						s.clone(),239						tb!(UnboundMethod {240							uctx: uctx.clone(),241							value: value.clone(),242							params: params.clone(),243							name: name.clone()244						}),245					)?;246			}247			Member::BindStmt(_) => {}248			Member::AssertStmt(stmt) => {249				#[derive(Trace)]250				struct ObjectAssert<B: Trace> {251					uctx: B,252					assert: AssertStmt,253				}254				impl<B: Unbound<Bound = Context>> ObjectAssertion for ObjectAssert<B> {255					fn run(256						&self,257						s: State,258						sup: Option<ObjValue>,259						this: Option<ObjValue>,260					) -> Result<()> {261						let ctx = self.uctx.bind(s.clone(), sup, this)?;262						evaluate_assert(s, ctx, &self.assert)263					}264				}265				builder.assert(tb!(ObjectAssert {266					uctx: uctx.clone(),267					assert: stmt.clone(),268				}));269			}270		}271	}272	let this = builder.build();273	let _ctx = ctx274		.extend(GcHashMap::new(), None, None, Some(this.clone()))275		.into_future(fctx);276	Ok(this)277}278279pub fn evaluate_object(s: State, ctx: Context, object: &ObjBody) -> Result<ObjValue> {280	Ok(match object {281		ObjBody::MemberList(members) => evaluate_member_list_object(s, ctx, members)?,282		ObjBody::ObjComp(obj) => {283			let mut builder = ObjValueBuilder::new();284			let locals = Rc::new(285				obj.pre_locals286					.iter()287					.chain(obj.post_locals.iter())288					.cloned()289					.collect::<Vec<_>>(),290			);291			let mut ctxs = vec![];292			evaluate_comp(s.clone(), ctx, &obj.compspecs, &mut |ctx| {293				let key = evaluate(s.clone(), ctx.clone(), &obj.key)?;294				let fctx = Context::new_future();295				ctxs.push((ctx, fctx.clone()));296				let uctx = evaluate_object_locals(fctx, locals.clone());297298				match key {299					Val::Null => {}300					Val::Str(n) => {301						#[derive(Trace)]302						struct UnboundValue<B: Trace> {303							uctx: B,304							value: LocExpr,305						}306						impl<B: Unbound<Bound = Context>> Unbound for UnboundValue<B> {307							type Bound = Thunk<Val>;308							fn bind(309								&self,310								s: State,311								sup: Option<ObjValue>,312								this: Option<ObjValue>,313							) -> Result<Thunk<Val>> {314								Ok(Thunk::evaluated(evaluate(315									s.clone(),316									self.uctx.bind(s, sup, this.clone())?.extend(317										GcHashMap::new(),318										None,319										None,320										this,321									),322									&self.value,323								)?))324							}325						}326						builder327							.member(n)328							.with_location(obj.value.1.clone())329							.with_add(obj.plus)330							.bindable(331								s.clone(),332								tb!(UnboundValue {333									uctx,334									value: obj.value.clone(),335								}),336							)?;337					}338					v => throw!(FieldMustBeStringGot(v.value_type())),339				}340341				Ok(())342			})?;343344			let this = builder.build();345			for (ctx, fctx) in ctxs {346				let _ctx = ctx347					.extend(GcHashMap::new(), None, None, Some(this.clone()))348					.into_future(fctx);349			}350			this351		}352	})353}354355pub fn evaluate_apply(356	s: State,357	ctx: Context,358	value: &LocExpr,359	args: &ArgsDesc,360	loc: CallLocation,361	tailstrict: bool,362) -> Result<Val> {363	let value = evaluate(s.clone(), ctx.clone(), value)?;364	Ok(match value {365		Val::Func(f) => {366			let body = || f.evaluate(s.clone(), ctx, loc, args, tailstrict);367			if tailstrict {368				body()?369			} else {370				s.push(loc, || format!("function <{}> call", f.name()), body)?371			}372		}373		v => throw!(OnlyFunctionsCanBeCalledGot(v.value_type())),374	})375}376377pub fn evaluate_assert(s: State, ctx: Context, assertion: &AssertStmt) -> Result<()> {378	let value = &assertion.0;379	let msg = &assertion.1;380	let assertion_result = s.push(381		CallLocation::new(&value.1),382		|| "assertion condition".to_owned(),383		|| bool::from_untyped(evaluate(s.clone(), ctx.clone(), value)?, s.clone()),384	)?;385	if !assertion_result {386		s.push(387			CallLocation::new(&value.1),388			|| "assertion failure".to_owned(),389			|| {390				if let Some(msg) = msg {391					throw!(AssertionFailed(392						evaluate(s.clone(), ctx, msg)?.to_string(s.clone())?393					));394				}395				throw!(AssertionFailed(Val::Null.to_string(s.clone())?));396			},397		)?;398	}399	Ok(())400}401402pub fn evaluate_named(s: State, ctx: Context, expr: &LocExpr, name: IStr) -> Result<Val> {403	use Expr::*;404	let LocExpr(raw_expr, _loc) = expr;405	Ok(match &**raw_expr {406		Function(params, body) => evaluate_method(ctx, name, params.clone(), body.clone()),407		_ => evaluate(s, ctx, expr)?,408	})409}410411#[allow(clippy::too_many_lines)]412pub fn evaluate(s: State, ctx: Context, expr: &LocExpr) -> Result<Val> {413	use Expr::*;414	let LocExpr(expr, loc) = expr;415	// let bp = with_state(|s| s.0.stop_at.borrow().clone());416	Ok(match &**expr {417		Literal(LiteralType::This) => {418			Val::Obj(ctx.this().clone().ok_or(CantUseSelfOutsideOfObject)?)419		}420		Literal(LiteralType::Super) => Val::Obj(421			ctx.super_obj().clone().ok_or(NoSuperFound)?.with_this(422				ctx.this()423					.clone()424					.expect("if super exists - then this should to"),425			),426		),427		Literal(LiteralType::Dollar) => {428			Val::Obj(ctx.dollar().clone().ok_or(NoTopLevelObjectFound)?)429		}430		Literal(LiteralType::True) => Val::Bool(true),431		Literal(LiteralType::False) => Val::Bool(false),432		Literal(LiteralType::Null) => Val::Null,433		Parened(e) => evaluate(s, ctx, e)?,434		Str(v) => Val::Str(v.clone()),435		Num(v) => Val::new_checked_num(*v)?,436		BinaryOp(v1, o, v2) => evaluate_binary_op_special(s, ctx, v1, *o, v2)?,437		UnaryOp(o, v) => evaluate_unary_op(*o, &evaluate(s, ctx, v)?)?,438		Var(name) => s.push(439			CallLocation::new(loc),440			|| format!("variable <{}> access", name),441			|| ctx.binding(name.clone())?.evaluate(s.clone()),442		)?,443		Index(value, index) => {444			match (445				evaluate(s.clone(), ctx.clone(), value)?,446				evaluate(s.clone(), ctx, index)?,447			) {448				(Val::Obj(v), Val::Str(key)) => s.push(449					CallLocation::new(loc),450					|| format!("field <{}> access", key),451					|| match v.get(s.clone(), key.clone()) {452						Ok(Some(v)) => Ok(v),453						#[cfg(not(feature = "friendly-errors"))]454						Ok(None) => throw!(NoSuchField(key.clone(), vec![])),455						#[cfg(feature = "friendly-errors")]456						Ok(None) => {457							let mut heap = Vec::new();458							for field in v.fields_ex(459								true,460								#[cfg(feature = "exp-preserve-order")]461								false,462							) {463								let conf = strsim::jaro_winkler(&field as &str, &key as &str);464								if conf < 0.8 {465									continue;466								}467								heap.push((conf, field));468							}469							heap.sort_by(|a, b| b.0.partial_cmp(&a.0).unwrap_or(Ordering::Equal));470471							throw!(NoSuchField(472								key.clone(),473								heap.into_iter().map(|(_, v)| v).collect()474							))475						}476						Err(e) if matches!(e.error(), MagicThisFileUsed) => {477							Ok(Val::Str(loc.0.full_path().into()))478						}479						Err(e) => Err(e),480					},481				)?,482				(Val::Obj(_), n) => throw!(ValueIndexMustBeTypeGot(483					ValType::Obj,484					ValType::Str,485					n.value_type(),486				)),487488				(Val::Arr(v), Val::Num(n)) => {489					if n.fract() > f64::EPSILON {490						throw!(FractionalIndex)491					}492					v.get(s, n as usize)?493						.ok_or_else(|| ArrayBoundsError(n as usize, v.len()))?494				}495				(Val::Arr(_), Val::Str(n)) => throw!(AttemptedIndexAnArrayWithString(n)),496				(Val::Arr(_), n) => throw!(ValueIndexMustBeTypeGot(497					ValType::Arr,498					ValType::Num,499					n.value_type(),500				)),501502				(Val::Str(s), Val::Num(n)) => Val::Str({503					let v: IStr = s504						.chars()505						.skip(n as usize)506						.take(1)507						.collect::<String>()508						.into();509					if v.is_empty() {510						let size = s.chars().count();511						throw!(StringBoundsError(n as usize, size))512					}513					v514				}),515				(Val::Str(_), n) => throw!(ValueIndexMustBeTypeGot(516					ValType::Str,517					ValType::Num,518					n.value_type(),519				)),520521				(v, _) => throw!(CantIndexInto(v.value_type())),522			}523		}524		LocalExpr(bindings, returned) => {525			let mut new_bindings: GcHashMap<IStr, Thunk<Val>> =526				GcHashMap::with_capacity(bindings.len());527			let fctx = Context::new_future();528			for b in bindings {529				evaluate_dest(b, fctx.clone(), &mut new_bindings)?;530			}531			let ctx = ctx.extend(new_bindings, None, None, None).into_future(fctx);532			evaluate(s, ctx, &returned.clone())?533		}534		Arr(items) => {535			let mut out = Vec::with_capacity(items.len());536			for item in items {537				// TODO: Implement ArrValue::Lazy with same context for every element?538				#[derive(Trace)]539				struct ArrayElement {540					ctx: Context,541					item: LocExpr,542				}543				impl ThunkValue for ArrayElement {544					type Output = Val;545					fn get(self: Box<Self>, s: State) -> Result<Val> {546						evaluate(s, self.ctx, &self.item)547					}548				}549				out.push(Thunk::new(tb!(ArrayElement {550					ctx: ctx.clone(),551					item: item.clone(),552				})));553			}554			Val::Arr(out.into())555		}556		ArrComp(expr, comp_specs) => {557			let mut out = Vec::new();558			evaluate_comp(s.clone(), ctx, comp_specs, &mut |ctx| {559				out.push(evaluate(s.clone(), ctx, expr)?);560				Ok(())561			})?;562			Val::Arr(ArrValue::Eager(Cc::new(out)))563		}564		Obj(body) => Val::Obj(evaluate_object(s, ctx, body)?),565		ObjExtend(a, b) => evaluate_add_op(566			s.clone(),567			&evaluate(s.clone(), ctx.clone(), a)?,568			&Val::Obj(evaluate_object(s, ctx, b)?),569		)?,570		Apply(value, args, tailstrict) => {571			evaluate_apply(s, ctx, value, args, CallLocation::new(loc), *tailstrict)?572		}573		Function(params, body) => {574			evaluate_method(ctx, "anonymous".into(), params.clone(), body.clone())575		}576		Intrinsic(name) => Val::Func(FuncVal::StaticBuiltin(577			BUILTINS578				.with(|b| b.get(name).copied())579				.ok_or_else(|| IntrinsicNotFound(name.clone()))?,580		)),581		IntrinsicThisFile => return Err(MagicThisFileUsed.into()),582		IntrinsicId => Val::Func(FuncVal::identity()),583		AssertExpr(assert, returned) => {584			evaluate_assert(s.clone(), ctx.clone(), assert)?;585			evaluate(s, ctx, returned)?586		}587		ErrorStmt(e) => s.push(588			CallLocation::new(loc),589			|| "error statement".to_owned(),590			|| {591				throw!(RuntimeError(592					evaluate(s.clone(), ctx, e)?.to_string(s.clone())?,593				))594			},595		)?,596		IfElse {597			cond,598			cond_then,599			cond_else,600		} => {601			if s.push(602				CallLocation::new(loc),603				|| "if condition".to_owned(),604				|| bool::from_untyped(evaluate(s.clone(), ctx.clone(), &cond.0)?, s.clone()),605			)? {606				evaluate(s, ctx, cond_then)?607			} else {608				match cond_else {609					Some(v) => evaluate(s, ctx, v)?,610					None => Val::Null,611				}612			}613		}614		Slice(value, desc) => {615			fn parse_idx<T: Typed>(616				loc: CallLocation,617				s: State,618				ctx: &Context,619				expr: &Option<LocExpr>,620				desc: &'static str,621			) -> Result<Option<T>> {622				if let Some(value) = expr {623					Ok(Some(s.push(624						loc,625						|| format!("slice {}", desc),626						|| T::from_untyped(evaluate(s.clone(), ctx.clone(), value)?, s.clone()),627					)?))628				} else {629					Ok(None)630				}631			}632633			let indexable = evaluate(s.clone(), ctx.clone(), value)?;634			let loc = CallLocation::new(loc);635636			let start = parse_idx(loc, s.clone(), &ctx, &desc.start, "start")?;637			let end = parse_idx(loc, s.clone(), &ctx, &desc.end, "end")?;638			let step = parse_idx(loc, s, &ctx, &desc.step, "step")?;639640			std_slice(indexable.into_indexable()?, start, end, step)?641		}642		i @ (Import(path) | ImportStr(path) | ImportBin(path)) => {643			let tmp = loc.clone().0;644			let import_location = tmp645				.path()646				.map(|p| {647					let mut p = p.to_owned();648					p.pop();649					p650				})651				.unwrap_or_default();652			let resolved_path = s.resolve_file(&import_location, path as &str)?;653			match i {654				Import(_) => s.push(655					CallLocation::new(loc),656					|| format!("import {:?}", path.clone()),657					|| s.import(resolved_path.clone()),658				)?,659				ImportStr(_) => Val::Str(s.import_str(resolved_path)?),660				ImportBin(_) => Val::Arr(ArrValue::Bytes(s.import_bin(resolved_path)?)),661				_ => unreachable!(),662			}663		}664	})665}