git.delta.rocks / jrsonnet / refs/commits / 32f6ee5b9541

difftreelog

source

crates/jrsonnet-evaluator/src/evaluate/mod.rs16.2 KiBsourcehistory
1use std::rc::Rc;23use 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> {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> {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> {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> {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						Ok(None) => throw!(NoSuchField(key.clone())),454						Err(e) if matches!(e.error(), MagicThisFileUsed) => {455							Ok(Val::Str(loc.0.to_string_lossy().into()))456						}457						Err(e) => Err(e),458					},459				)?,460				(Val::Obj(_), n) => throw!(ValueIndexMustBeTypeGot(461					ValType::Obj,462					ValType::Str,463					n.value_type(),464				)),465466				(Val::Arr(v), Val::Num(n)) => {467					if n.fract() > f64::EPSILON {468						throw!(FractionalIndex)469					}470					v.get(s, n as usize)?471						.ok_or_else(|| ArrayBoundsError(n as usize, v.len()))?472				}473				(Val::Arr(_), Val::Str(n)) => throw!(AttemptedIndexAnArrayWithString(n)),474				(Val::Arr(_), n) => throw!(ValueIndexMustBeTypeGot(475					ValType::Arr,476					ValType::Num,477					n.value_type(),478				)),479480				(Val::Str(s), Val::Num(n)) => Val::Str({481					let v: IStr = s482						.chars()483						.skip(n as usize)484						.take(1)485						.collect::<String>()486						.into();487					if v.is_empty() {488						let size = s.chars().count();489						throw!(StringBoundsError(n as usize, size))490					}491					v492				}),493				(Val::Str(_), n) => throw!(ValueIndexMustBeTypeGot(494					ValType::Str,495					ValType::Num,496					n.value_type(),497				)),498499				(v, _) => throw!(CantIndexInto(v.value_type())),500			}501		}502		LocalExpr(bindings, returned) => {503			let mut new_bindings: GcHashMap<IStr, Thunk<Val>> =504				GcHashMap::with_capacity(bindings.len());505			let fctx = Context::new_future();506			for b in bindings {507				evaluate_dest(b, fctx.clone(), &mut new_bindings)?;508			}509			let ctx = ctx.extend(new_bindings, None, None, None).into_future(fctx);510			evaluate(s, ctx, &returned.clone())?511		}512		Arr(items) => {513			let mut out = Vec::with_capacity(items.len());514			for item in items {515				// TODO: Implement ArrValue::Lazy with same context for every element?516				#[derive(Trace)]517				struct ArrayElement {518					ctx: Context,519					item: LocExpr,520				}521				impl ThunkValue for ArrayElement {522					type Output = Val;523					fn get(self: Box<Self>, s: State) -> Result<Val> {524						evaluate(s, self.ctx, &self.item)525					}526				}527				out.push(Thunk::new(tb!(ArrayElement {528					ctx: ctx.clone(),529					item: item.clone(),530				})));531			}532			Val::Arr(out.into())533		}534		ArrComp(expr, comp_specs) => {535			let mut out = Vec::new();536			evaluate_comp(s.clone(), ctx, comp_specs, &mut |ctx| {537				out.push(evaluate(s.clone(), ctx, expr)?);538				Ok(())539			})?;540			Val::Arr(ArrValue::Eager(Cc::new(out)))541		}542		Obj(body) => Val::Obj(evaluate_object(s, ctx, body)?),543		ObjExtend(a, b) => evaluate_add_op(544			s.clone(),545			&evaluate(s.clone(), ctx.clone(), a)?,546			&Val::Obj(evaluate_object(s, ctx, b)?),547		)?,548		Apply(value, args, tailstrict) => {549			evaluate_apply(s, ctx, value, args, CallLocation::new(loc), *tailstrict)?550		}551		Function(params, body) => {552			evaluate_method(ctx, "anonymous".into(), params.clone(), body.clone())553		}554		Intrinsic(name) => Val::Func(FuncVal::StaticBuiltin(555			BUILTINS556				.with(|b| b.get(name).copied())557				.ok_or_else(|| IntrinsicNotFound(name.clone()))?,558		)),559		IntrinsicThisFile => return Err(MagicThisFileUsed.into()),560		IntrinsicId => Val::Func(FuncVal::identity()),561		AssertExpr(assert, returned) => {562			evaluate_assert(s.clone(), ctx.clone(), assert)?;563			evaluate(s, ctx, returned)?564		}565		ErrorStmt(e) => s.push(566			CallLocation::new(loc),567			|| "error statement".to_owned(),568			|| {569				throw!(RuntimeError(570					evaluate(s.clone(), ctx, e)?.to_string(s.clone())?,571				))572			},573		)?,574		IfElse {575			cond,576			cond_then,577			cond_else,578		} => {579			if s.push(580				CallLocation::new(loc),581				|| "if condition".to_owned(),582				|| bool::from_untyped(evaluate(s.clone(), ctx.clone(), &cond.0)?, s.clone()),583			)? {584				evaluate(s, ctx, cond_then)?585			} else {586				match cond_else {587					Some(v) => evaluate(s, ctx, v)?,588					None => Val::Null,589				}590			}591		}592		Slice(value, desc) => {593			fn parse_idx<T: Typed>(594				loc: CallLocation,595				s: State,596				ctx: &Context,597				expr: &Option<LocExpr>,598				desc: &'static str,599			) -> Result<Option<T>> {600				if let Some(value) = expr {601					Ok(Some(s.push(602						loc,603						|| format!("slice {}", desc),604						|| T::from_untyped(evaluate(s.clone(), ctx.clone(), value)?, s.clone()),605					)?))606				} else {607					Ok(None)608				}609			}610611			let indexable = evaluate(s.clone(), ctx.clone(), value)?;612			let loc = CallLocation::new(loc);613614			let start = parse_idx(loc, s.clone(), &ctx, &desc.start, "start")?;615			let end = parse_idx(loc, s.clone(), &ctx, &desc.end, "end")?;616			let step = parse_idx(loc, s, &ctx, &desc.step, "step")?;617618			std_slice(indexable.into_indexable()?, start, end, step)?619		}620		Import(path) => {621			let tmp = loc.clone().0;622			let mut import_location = tmp.to_path_buf();623			import_location.pop();624			s.push(625				CallLocation::new(loc),626				|| format!("import {:?}", path),627				|| s.import_file(&import_location, path),628			)?629		}630		ImportStr(path) => {631			let tmp = loc.clone().0;632			let mut import_location = tmp.to_path_buf();633			import_location.pop();634			Val::Str(s.import_file_str(&import_location, path)?)635		}636		ImportBin(path) => {637			let tmp = loc.clone().0;638			let mut import_location = tmp.to_path_buf();639			import_location.pop();640			let bytes = s.import_file_bin(&import_location, path)?;641			Val::Arr(ArrValue::Bytes(bytes))642		}643	})644}