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

difftreelog

source

crates/jrsonnet-evaluator/src/evaluate/mod.rs15.0 KiBsourcehistory
1use std::rc::Rc;23use jrsonnet_gcmodule::{Cc, Trace};4use jrsonnet_interner::IStr;5use jrsonnet_ir::ImportKind;6use jrsonnet_types::ValType;78use self::{9	compspec::{evaluate_arr_comp, evaluate_obj_comp},10	destructure::{evaluate_locals, evaluate_locals_unbound},11	operator::evaluate_binary_op_special,12};13use crate::{14	analyze::{15		LArgsDesc, LAssertStmt, LExpr, LFieldMember, LFieldName, LFunction, LIndexPart, LObjBody,16		LObjMembers,17	},18	bail,19	error::{suggest_object_fields, ErrorKind::*},20	evaluate::operator::evaluate_unary_op,21	function::{prepared::PreparedFuncVal, CallLocation, FuncDesc, FuncVal},22	in_frame, runtime_error,23	typed::FromUntyped as _,24	val::{CachedUnbound, Thunk},25	with_state, Context, Error, ObjValue, ObjValueBuilder, ObjectAssertion, Result, ResultExt as _,26	SupThis, Unbound, Val,27};2829pub mod compspec;30pub mod destructure;31pub mod operator;3233// This is the amount of bytes that need to be left on the stack before increasing the size.34// It must be at least as large as the stack required by any code that does not call35// `ensure_sufficient_stack`.36const RED_ZONE: usize = 100 * 1024;3738// Only the first stack that is pushed, grows exponentially (2^n * STACK_PER_RECURSION) from then39// on. This flag has performance relevant characteristics. Don't set it too high.40const STACK_PER_RECURSION: usize = 1024 * 1024;4142/// Grows the stack on demand to prevent stack overflow. Call this in strategic locations43/// to "break up" recursive calls. E.g. almost any call to `visit_expr` or equivalent can benefit44/// from this.45///46/// Should not be sprinkled around carelessly, as it causes a little bit of overhead.47#[inline]48pub fn ensure_sufficient_stack<R>(f: impl FnOnce() -> R) -> R {49	stacker::maybe_grow(RED_ZONE, STACK_PER_RECURSION, f)50}5152pub fn evaluate_trivial(expr: &LExpr) -> Option<Val> {53	// TODO: Eager trivial array54	Some(match expr {55		LExpr::Str(s) => Val::string(s.clone()),56		LExpr::Num(n) => Val::Num(*n),57		LExpr::Bool(false) => Val::Bool(false),58		LExpr::Bool(true) => Val::Bool(true),59		LExpr::Null => Val::Null,60		_ => return None,61	})62}6364/// Evaluate a method definition.65pub fn evaluate_method(ctx: Context, name: IStr, func: &Rc<LFunction>) -> Val {66	Val::Func(FuncVal::Normal(Cc::new(FuncDesc {67		name,68		ctx,69		func: func.clone(),70	})))71}7273pub fn evaluate_field_name(ctx: Context, field_name: &LFieldName) -> Result<Option<IStr>> {74	Ok(match field_name {75		LFieldName::Fixed(n) => Some(n.clone()),76		LFieldName::Dyn(expr) => in_frame(77			// TODO: Spanned<LFieldName>78			CallLocation::native(),79			|| "evaluating field name".to_string(),80			|| {81				let v = evaluate(ctx.clone(), expr)?;82				Ok(if matches!(v, Val::Null) {83					None84				} else {85					Some(IStr::from_untyped(v)?)86				})87			},88		)?,89	})90}9192pub fn evaluate_thunk(ctx: Context, expr: Rc<LExpr>, tailstrict: bool) -> Result<Thunk<Val>> {93	Ok(if tailstrict {94		Thunk::evaluated(evaluate(ctx, &expr)?)95	} else {96		Thunk!(move || { evaluate(ctx, &expr) })97	})98}99100mod names {101	use crate::names;102103	names! {104		anonymous: "anonymous",105	}106}107108pub fn evaluate_named(name: &IStr, ctx: Context, expr: &LExpr) -> Result<Val> {109	if let LExpr::Function(f) = &expr {110		return Ok(evaluate_method(111			ctx,112			f.name.clone().unwrap_or_else(|| name.clone()),113			f,114		));115	}116	evaluate(ctx, expr)117}118119pub fn evaluate(ctx: Context, expr: &LExpr) -> Result<Val> {120	Ok(match expr {121		LExpr::Null => Val::Null,122		LExpr::Bool(b) => Val::Bool(*b),123		LExpr::Str(s) => Val::string(s.clone()),124		LExpr::Num(n) => Val::Num(*n),125		LExpr::Local(id) => {126			let Some(thunk) = ctx.binding(*id) else {127				bail!("should not happen: unbound local {id:?}");128			};129			thunk.evaluate()?130		}131		LExpr::BadLocal(name) => panic!("unresolvable reference: {name}"),132		LExpr::Arr(items) => Val::Arr(crate::arr::ArrValue::expr(ctx, items.clone())),133		LExpr::UnaryOp(op, value) => {134			let value = evaluate(ctx, value)?;135			evaluate_unary_op(*op, &value)?136		}137		LExpr::BinaryOp { lhs, op, rhs } => evaluate_binary_op_special(ctx, lhs, *op, rhs)?,138		LExpr::LocalExpr { binds, body } => {139			let ctx = evaluate_locals(ctx, binds);140			evaluate(ctx, body)?141		}142		LExpr::IfElse {143			cond,144			cond_then,145			cond_else,146		} => {147			let cond_val = evaluate(ctx.clone(), cond)?;148			let Val::Bool(b) = cond_val else {149				bail!(TypeMismatch(150					"if condition",151					vec![ValType::Bool],152					cond_val.value_type()153				))154			};155			if b {156				evaluate(ctx, cond_then)?157			} else if let Some(e) = cond_else {158				evaluate(ctx, e)?159			} else {160				Val::Null161			}162		}163		LExpr::Error(s, e) => in_frame(164			CallLocation::new(s),165			|| "error statement".to_owned(),166			|| bail!(RuntimeError(evaluate(ctx, e)?.to_string()?,)),167		)?,168		LExpr::AssertExpr { assert, rest } => {169			evaluate_assert(ctx.clone(), assert)?;170			evaluate(ctx, rest)?171		}172173		LExpr::Function(func) => evaluate_method(174			ctx,175			func.name.clone().unwrap_or_else(names::anonymous),176			func,177		),178		LExpr::Apply {179			applicable,180			args,181			tailstrict,182		} => evaluate_apply(183			ctx,184			applicable,185			args,186			CallLocation::new(&args.span),187			*tailstrict,188		)?,189		LExpr::Index { indexable, parts } => evaluate_index(ctx, indexable, parts)?,190		LExpr::Obj(body) => evaluate_obj_body(None, ctx, body)?,191		LExpr::ObjExtend(lhs, body) => {192			let lhs_val = evaluate(ctx.clone(), lhs)?;193			let Val::Obj(lhs_obj) = lhs_val else {194				bail!(TypeMismatch(195					"object extend lhs",196					vec![ValType::Obj],197					lhs_val.value_type(),198				))199			};200			evaluate_obj_body(Some(lhs_obj), ctx, body)?201		}202		LExpr::ArrComp(comp) => evaluate_arr_comp(ctx, comp)?,203		LExpr::Slice(slice) => {204			use crate::typed::BoundedUsize;205			let val = evaluate(ctx.clone(), &slice.value)?;206			let indexable = val.into_indexable()?;207			let start = slice208				.start209				.as_ref()210				.map(|e| evaluate(ctx.clone(), e))211				.transpose()?212				.map(|v| -> Result<i32> {213					v.as_num()214						.ok_or_else(|| {215							TypeMismatch("slice start", vec![ValType::Num], v.value_type()).into()216						})217						.map(|n| n as i32)218				})219				.transpose()?;220			let end = slice221				.end222				.as_ref()223				.map(|e| evaluate(ctx.clone(), e))224				.transpose()?225				.map(|v| -> Result<i32> {226					v.as_num()227						.ok_or_else(|| {228							TypeMismatch("slice end", vec![ValType::Num], v.value_type()).into()229						})230						.map(|n| n as i32)231				})232				.transpose()?;233			let step = slice234				.step235				.as_ref()236				.map(|e| evaluate(ctx, e))237				.transpose()?238				.map(|v| -> Result<BoundedUsize<1, { i32::MAX as usize }>> {239					let n = v.as_num().ok_or_else(|| -> crate::Error {240						TypeMismatch("slice step", vec![ValType::Num], v.value_type()).into()241					})?;242					BoundedUsize::new(n as usize)243						.ok_or_else(|| runtime_error!("slice step must be >= 1"))244				})245				.transpose()?;246			Val::from(indexable.slice(start, end, step)?)247		}248		LExpr::Super => Val::Obj(ctx.try_sup_this()?.standalone_super()?),249		LExpr::Import {250			kind,251			kind_span,252			path,253		} => with_state(|state| {254			let resolved = state.resolve_from(kind_span.0.source_path(), &path.clone())?;255			Ok::<_, Error>(match kind.value {256				ImportKind::Normal => in_frame(257					CallLocation::new(&kind.span),258					|| "import".to_string(),259					|| state.import_resolved(resolved),260				)?,261				ImportKind::Str => Val::string(state.import_resolved_str(resolved)?),262				ImportKind::Bin => Val::arr(state.import_resolved_bin(resolved)?),263			})264		})?,265	})266}267268fn evaluate_apply(269	ctx: Context,270	applicable: &LExpr,271	args: &LArgsDesc,272	loc: CallLocation<'_>,273	tailstrict: bool,274) -> Result<Val> {275	let func_val = evaluate(ctx.clone(), applicable)?;276	let Val::Func(func) = func_val else {277		bail!(OnlyFunctionsCanBeCalledGot(func_val.value_type()))278	};279280	let name = func.name();281	let unnamed = args282		.unnamed283		.iter()284		.cloned()285		.map(|e| evaluate_thunk(ctx.clone(), e, tailstrict))286		.collect::<Result<Vec<_>>>()?;287288	let named = args289		.values290		.iter()291		.cloned()292		.map(|e| evaluate_thunk(ctx.clone(), e, tailstrict))293		.collect::<Result<Vec<_>>>()?;294	let prepare = PreparedFuncVal::new(func, unnamed.len(), &args.names)295		.with_description_src(loc, || format!("function <{name}> preparation"))?;296	in_frame(297		loc,298		|| format!("function <{name}> call"),299		|| prepare.call(CallLocation::native(), &unnamed, &named),300	)301}302303fn evaluate_index(ctx: Context, indexable: &LExpr, parts: &[LIndexPart]) -> Result<Val> {304	let mut value = if let LExpr::Super = indexable {305		let sup_this = ctx.try_sup_this()?;306		// First part must be evaluated to get the super field name307		if parts.is_empty() {308			bail!(RuntimeError("super requires an index".into()))309		}310		let key_val = evaluate(ctx.clone(), &parts[0].value)?;311		let Val::Str(key) = &key_val else {312			bail!(ValueIndexMustBeTypeGot(313				ValType::Obj,314				ValType::Str,315				key_val.value_type(),316			))317		};318		let field = key.clone().into_flat();319		if let Some(v) = sup_this.get_super(field.clone())? {320			// Continue with remaining parts321			let mut value = v;322			for part in &parts[1..] {323				value = index_val(ctx.clone(), CallLocation::new(&part.span), value, part)?;324			}325			return Ok(value);326		}327		let suggestions = suggest_object_fields(sup_this.this(), field.clone());328		bail!(NoSuchField(field, suggestions))329	} else {330		evaluate(ctx.clone(), indexable)?331	};332333	for part in parts {334		value = index_val(ctx.clone(), CallLocation::new(&part.span), value, part)?;335	}336	Ok(value)337}338339fn index_val(ctx: Context, loc: CallLocation<'_>, value: Val, part: &LIndexPart) -> Result<Val> {340	let key_val = evaluate(ctx, &part.value)?;341	Ok(match (&value, &key_val) {342		(Val::Obj(obj), Val::Str(key)) => {343			let field = key.clone().into_flat();344			if let Some(v) = obj345				.get(field.clone())346				.with_description_src(loc, || format!("field <{field}> access"))?347			{348				v349			} else {350				bail!(NoSuchField(351					field.clone(),352					suggest_object_fields(obj, field)353				))354			}355		}356		(Val::Arr(arr), Val::Num(idx)) => {357			let n = idx.get();358			if n.fract() > f64::EPSILON {359				bail!(FractionalIndex)360			}361			if n < 0.0 {362				bail!(ArrayBoundsError(363					n as isize, // truncation is fine for error display364					arr.len()365				));366			}367			#[expect(368				clippy::cast_possible_truncation,369				clippy::cast_sign_loss,370				reason = "n is checked positive"371			)]372			let i = n as u32;373			arr.get(i)374				.with_description_src(loc, || format!("element <{i}> access"))?375				.ok_or_else(|| ArrayBoundsError(i as isize, arr.len()))?376		}377		(Val::Str(s), Val::Num(idx)) => {378			let n = idx.get();379			if n.fract() > f64::EPSILON {380				bail!(FractionalIndex)381			}382			let flat = s.clone().into_flat();383			if n < 0.0 {384				bail!(ArrayBoundsError(385					n as isize, // truncation is fine for error display386					flat.chars().count() as u32387				));388			}389			#[expect(390				clippy::cast_possible_truncation,391				clippy::cast_sign_loss,392				reason = "n is checked positive, overflow will truncate as expected"393			)]394			let i = n as usize;395			let Some(char) = flat.chars().nth(i) else {396				bail!(StringBoundsError(i, flat.chars().count()))397			};398			Val::string(char)399		}400		_ => bail!(ValueIndexMustBeTypeGot(401			value.value_type(),402			ValType::Str,403			key_val.value_type()404		)),405	})406}407408fn evaluate_obj_body(super_obj: Option<ObjValue>, ctx: Context, body: &LObjBody) -> Result<Val> {409	match body {410		LObjBody::MemberList(members) => evaluate_obj_members(super_obj, ctx, members),411		LObjBody::ObjComp(comp) => evaluate_obj_comp(super_obj, ctx, comp),412	}413}414415pub fn evaluate_field_member_unbound<B: Unbound<Bound = Context> + Clone>(416	builder: &mut ObjValueBuilder,417	ctx: Context,418	uctx: B,419	field: &LFieldMember,420) -> Result<()> {421	#[derive(Trace)]422	struct UnboundValue<B: Trace> {423		uctx: B,424		value: Rc<LExpr>,425		name: IStr,426	}427	impl<B: Unbound<Bound = Context>> Unbound for UnboundValue<B> {428		type Bound = Val;429		fn bind(&self, sup_this: SupThis) -> Result<Val> {430			evaluate(self.uctx.bind(sup_this)?, &self.value)431		}432	}433434	let LFieldMember {435		name,436		plus,437		visibility,438		value,439	} = field;440	let Some(name) = evaluate_field_name(ctx, name)? else {441		return Ok(());442	};443444	builder445		.field(name.clone())446		.with_add(*plus)447		.with_visibility(*visibility)448		.bindable(UnboundValue {449			uctx,450			value: value.clone(),451			name,452		})453}454pub fn evaluate_field_member_static(455	builder: &mut ObjValueBuilder,456	field_ctx: Context,457	value_ctx: Context,458	field: &LFieldMember,459) -> Result<()> {460	let LFieldMember {461		name,462		plus,463		visibility,464		value,465	} = field;466	let Some(name) = evaluate_field_name(field_ctx, name)? else {467		return Ok(());468	};469470	let value = value.clone();471	builder472		.field(name)473		.with_add(*plus)474		.with_visibility(*visibility)475		.try_thunk(Thunk!(move || { evaluate(value_ctx, &value) }))?;476	Ok(())477}478479fn evaluate_obj_members(480	super_obj: Option<ObjValue>,481	ctx: Context,482	members: &LObjMembers,483) -> Result<Val> {484	let mut builder = ObjValueBuilder::with_capacity(members.fields.len());485	if let Some(sup) = super_obj {486		builder.with_super(sup);487	}488489	let needs_unbound = members.this.is_some() || members.uses_super;490491	if needs_unbound {492		let uctx = CachedUnbound::new(evaluate_locals_unbound(493			ctx.clone(),494			members.locals.clone(),495			members.this,496		));497		for field in &members.fields {498			evaluate_field_member_unbound(&mut builder, ctx.clone(), uctx.clone(), field)?;499		}500		if !members.asserts.is_empty() {501			builder.assert(evaluate_object_assertions_unbound(502				uctx,503				members.asserts.clone(),504			));505		}506	} else {507		let field_ctx = ctx;508		let value_ctx = evaluate_locals(field_ctx.clone(), &members.locals);509		for field in &members.fields {510			evaluate_field_member_static(511				&mut builder,512				field_ctx.clone(),513				value_ctx.clone(),514				field,515			)?;516		}517		if !members.asserts.is_empty() {518			builder.assert(evaluate_object_assertions_static(519				value_ctx,520				members.asserts.clone(),521			));522		}523	}524525	Ok(Val::Obj(builder.build()))526}527528pub fn evaluate_assert(ctx: Context, assertion: &LAssertStmt) -> Result<()> {529	let LAssertStmt { cond, message } = assertion;530	let assertion_result = in_frame(531		CallLocation::native(),532		|| "assertion condition".to_owned(),533		|| bool::from_untyped(evaluate(ctx.clone(), cond)?),534	)?;535	if !assertion_result {536		in_frame(537			CallLocation::new(&cond.span),538			|| "assertion failure".to_owned(),539			|| {540				if let Some(msg) = message {541					bail!(AssertionFailed(evaluate(ctx, msg)?.to_string()?));542				}543				bail!(AssertionFailed(Val::Null.to_string()?));544			},545		)?;546	}547	Ok(())548}549550fn evaluate_object_assertions_unbound<B: Unbound<Bound = Context>>(551	uctx: B,552	asserts: Rc<Vec<LAssertStmt>>,553) -> impl ObjectAssertion {554	#[derive(Trace)]555	struct ObjectAssert<B: Trace> {556		uctx: B,557		asserts: Rc<Vec<LAssertStmt>>,558	}559	impl<B: Unbound<Bound = Context>> ObjectAssertion for ObjectAssert<B> {560		fn run(&self, sup_this: SupThis) -> Result<()> {561			let ctx = self.uctx.bind(sup_this)?;562			for assert in &*self.asserts {563				evaluate_assert(ctx.clone(), assert)?;564			}565			Ok(())566		}567	}568	ObjectAssert { uctx, asserts }569}570fn evaluate_object_assertions_static(571	ctx: Context,572	asserts: Rc<Vec<LAssertStmt>>,573) -> impl ObjectAssertion {574	#[derive(Trace)]575	struct ObjectAssert {576		ctx: Context,577		asserts: Rc<Vec<LAssertStmt>>,578	}579	impl ObjectAssertion for ObjectAssert {580		fn run(&self, _sup_this: SupThis) -> Result<()> {581			for assert in &*self.asserts {582				evaluate_assert(self.ctx.clone(), assert)?;583			}584			Ok(())585		}586	}587	ObjectAssert { ctx, asserts }588}