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

difftreelog

feat FuncDesc helper for default context

Yaroslav Bolyukin2022-04-17parent: #efea837.patch.diff
in: master

2 files changed

modifiedcrates/jrsonnet-evaluator/src/function.rsdiffbeforeafterboth
--- a/crates/jrsonnet-evaluator/src/function.rs
+++ b/crates/jrsonnet-evaluator/src/function.rs
@@ -23,6 +23,18 @@
 	}
 }
 
+#[derive(Trace)]
+struct EvaluateNamedLazyVal {
+	future_context: FutureWrapper<Context>,
+	name: IStr,
+	value: LocExpr,
+}
+impl LazyValValue for EvaluateNamedLazyVal {
+	fn get(self: Box<Self>) -> Result<Val> {
+		evaluate_named(self.future_context.unwrap(), &self.value, self.name)
+	}
+}
+
 pub trait ArgLike {
 	fn evaluate_arg(&self, ctx: Context, tailstrict: bool) -> Result<LazyVal>;
 }
@@ -309,25 +321,14 @@
 	if filled_args < params.len() {
 		// Some args are unset, but maybe we have defaults for them
 		// Default values should be created in newly created context
-		let future_context = FutureWrapper::<Context>::new();
+		let future_context = Context::new_future();
 		let mut defaults = GcHashMap::with_capacity(params.len() - filled_args);
 
 		for param in params.iter().filter(|p| p.1.is_some()) {
 			if passed_args.contains_key(&param.0.clone()) {
 				continue;
 			}
-			#[derive(Trace)]
-			struct LazyNamedBinding {
-				future_context: FutureWrapper<Context>,
-				name: IStr,
-				value: LocExpr,
-			}
-			impl LazyValValue for LazyNamedBinding {
-				fn get(self: Box<Self>) -> Result<Val> {
-					evaluate_named(self.future_context.unwrap(), &self.value, self.name)
-				}
-			}
-			LazyVal::new(TraceBox(Box::new(LazyNamedBinding {
+			LazyVal::new(TraceBox(Box::new(EvaluateNamedLazyVal {
 				future_context: future_context.clone(),
 				name: param.0.clone(),
 				value: param.1.clone().unwrap(),
@@ -335,7 +336,7 @@
 
 			defaults.insert(
 				param.0.clone(),
-				LazyVal::new(TraceBox(Box::new(LazyNamedBinding {
+				LazyVal::new(TraceBox(Box::new(EvaluateNamedLazyVal {
 					future_context: future_context.clone(),
 					name: param.0.clone(),
 					value: param.1.clone().unwrap(),
@@ -464,3 +465,39 @@
 	}
 	Ok(passed_args)
 }
+
+/// Creates Context, which has all argument default values applied
+/// and with unbound values causing error to be returned
+pub fn parse_default_function_call(body_ctx: Context, params: &ParamsDesc) -> Context {
+	let ctx = Context::new_future();
+
+	let mut bindings = GcHashMap::new();
+
+	#[derive(Trace)]
+	struct DependsOnUnbound(IStr);
+	impl LazyValValue for DependsOnUnbound {
+		fn get(self: Box<Self>) -> Result<Val> {
+			Err(FunctionParameterNotBoundInCall(self.0.clone()).into())
+		}
+	}
+
+	for param in params.iter() {
+		if let Some(v) = &param.1 {
+			bindings.insert(
+				param.0.clone(),
+				LazyVal::new(TraceBox(Box::new(EvaluateNamedLazyVal {
+					future_context: ctx.clone(),
+					name: param.0.clone(),
+					value: v.clone(),
+				}))),
+			);
+		} else {
+			bindings.insert(
+				param.0.clone(),
+				LazyVal::new(TraceBox(Box::new(DependsOnUnbound(param.0.clone())))),
+			);
+		}
+	}
+
+	body_ctx.extend(bindings, None, None, None).into_future(ctx)
+}
modifiedcrates/jrsonnet-evaluator/src/val.rsdiffbeforeafterboth
before · crates/jrsonnet-evaluator/src/val.rs
1use crate::{2	builtin::manifest::{3		manifest_json_ex, manifest_yaml_ex, ManifestJsonOptions, ManifestType, ManifestYamlOptions,4	},5	cc_ptr_eq,6	error::{Error::*, LocError},7	evaluate,8	function::{parse_function_call, ArgsLike, Builtin, StaticBuiltin},9	gc::TraceBox,10	throw, Context, ObjValue, Result,11};12use gcmodule::{Cc, Trace};13use jrsonnet_interner::IStr;14use jrsonnet_parser::{ExprLocation, LocExpr, ParamsDesc};15use jrsonnet_types::ValType;16use std::{cell::RefCell, fmt::Debug, rc::Rc};1718pub trait LazyValValue: Trace {19	fn get(self: Box<Self>) -> Result<Val>;20}2122#[derive(Trace)]23enum LazyValInternals {24	Computed(Val),25	Errored(LocError),26	Waiting(TraceBox<dyn LazyValValue>),27	Pending,28}2930#[derive(Clone, Trace)]31pub struct LazyVal(Cc<RefCell<LazyValInternals>>);32impl LazyVal {33	pub fn new(f: TraceBox<dyn LazyValValue>) -> Self {34		Self(Cc::new(RefCell::new(LazyValInternals::Waiting(f))))35	}36	pub fn new_resolved(val: Val) -> Self {37		Self(Cc::new(RefCell::new(LazyValInternals::Computed(val))))38	}39	pub fn force(&self) -> Result<()> {40		self.evaluate()?;41		Ok(())42	}43	pub fn evaluate(&self) -> Result<Val> {44		match &*self.0.borrow() {45			LazyValInternals::Computed(v) => return Ok(v.clone()),46			LazyValInternals::Errored(e) => return Err(e.clone()),47			LazyValInternals::Pending => return Err(RecursiveLazyValueEvaluation.into()),48			_ => (),49		};50		let value = if let LazyValInternals::Waiting(value) =51			std::mem::replace(&mut *self.0.borrow_mut(), LazyValInternals::Pending)52		{53			value54		} else {55			unreachable!()56		};57		let new_value = match value.0.get() {58			Ok(v) => v,59			Err(e) => {60				*self.0.borrow_mut() = LazyValInternals::Errored(e.clone());61				return Err(e);62			}63		};64		*self.0.borrow_mut() = LazyValInternals::Computed(new_value.clone());65		Ok(new_value)66	}67}6869impl Debug for LazyVal {70	fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {71		write!(f, "Lazy")72	}73}74impl PartialEq for LazyVal {75	fn eq(&self, other: &Self) -> bool {76		cc_ptr_eq(&self.0, &other.0)77	}78}7980#[derive(Debug, PartialEq, Trace)]81pub struct FuncDesc {82	pub name: IStr,83	pub ctx: Context,84	pub params: ParamsDesc,85	pub body: LocExpr,86}8788#[derive(Trace, Clone)]89pub enum FuncVal {90	/// Plain function implemented in jsonnet91	Normal(Cc<FuncDesc>),92	/// Standard library function93	StaticBuiltin(#[skip_trace] &'static dyn StaticBuiltin),94	/// User-provided function95	Builtin(Cc<TraceBox<dyn Builtin>>),96}9798impl Debug for FuncVal {99	fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {100		match self {101			Self::Normal(arg0) => f.debug_tuple("Normal").field(arg0).finish(),102			Self::StaticBuiltin(arg0) => {103				f.debug_tuple("StaticBuiltin").field(&arg0.name()).finish()104			}105			Self::Builtin(arg0) => f.debug_tuple("Builtin").field(&arg0.name()).finish(),106		}107	}108}109110impl PartialEq for FuncVal {111	fn eq(&self, other: &Self) -> bool {112		match (self, other) {113			(Self::Normal(a), Self::Normal(b)) => a == b,114			(Self::StaticBuiltin(an), Self::StaticBuiltin(bn)) => std::ptr::eq(*an, *bn),115			(..) => false,116		}117	}118}119impl FuncVal {120	pub fn args_len(&self) -> usize {121		match self {122			Self::Normal(n) => n.params.iter().filter(|p| p.1.is_none()).count(),123			Self::StaticBuiltin(i) => i.params().iter().filter(|p| !p.has_default).count(),124			Self::Builtin(i) => i.params().iter().filter(|p| !p.has_default).count(),125		}126	}127	pub fn name(&self) -> IStr {128		match self {129			Self::Normal(normal) => normal.name.clone(),130			Self::StaticBuiltin(builtin) => builtin.name().into(),131			Self::Builtin(builtin) => builtin.name().into(),132		}133	}134	pub fn evaluate(135		&self,136		call_ctx: Context,137		loc: Option<&ExprLocation>,138		args: &dyn ArgsLike,139		tailstrict: bool,140	) -> Result<Val> {141		match self {142			Self::Normal(func) => {143				let ctx = parse_function_call(144					call_ctx,145					func.ctx.clone(),146					&func.params,147					args,148					tailstrict,149				)?;150				evaluate(ctx, &func.body)151			}152			Self::StaticBuiltin(name) => name.call(call_ctx, loc, args),153			Self::Builtin(b) => b.call(call_ctx, loc, args),154		}155	}156	pub fn evaluate_simple(&self, args: &dyn ArgsLike) -> Result<Val> {157		self.evaluate(Context::default(), None, args, true)158	}159}160161#[derive(Clone)]162pub enum ManifestFormat {163	YamlStream(Box<ManifestFormat>),164	Yaml(usize),165	Json(usize),166	ToString,167	String,168}169170#[derive(Debug, Clone, Trace)]171#[force_tracking]172pub enum ArrValue {173	Lazy(Cc<Vec<LazyVal>>),174	Eager(Cc<Vec<Val>>),175	Extended(Box<(Self, Self)>),176}177impl ArrValue {178	pub fn new_eager() -> Self {179		Self::Eager(Cc::new(Vec::new()))180	}181182	pub fn len(&self) -> usize {183		match self {184			Self::Lazy(l) => l.len(),185			Self::Eager(e) => e.len(),186			Self::Extended(v) => v.0.len() + v.1.len(),187		}188	}189190	pub fn is_empty(&self) -> bool {191		self.len() == 0192	}193194	pub fn get(&self, index: usize) -> Result<Option<Val>> {195		match self {196			Self::Lazy(vec) => {197				if let Some(v) = vec.get(index) {198					Ok(Some(v.evaluate()?))199				} else {200					Ok(None)201				}202			}203			Self::Eager(vec) => Ok(vec.get(index).cloned()),204			Self::Extended(v) => {205				let a_len = v.0.len();206				if a_len > index {207					v.0.get(index)208				} else {209					v.1.get(index - a_len)210				}211			}212		}213	}214215	pub fn get_lazy(&self, index: usize) -> Option<LazyVal> {216		match self {217			Self::Lazy(vec) => vec.get(index).cloned(),218			Self::Eager(vec) => vec.get(index).cloned().map(LazyVal::new_resolved),219			Self::Extended(v) => {220				let a_len = v.0.len();221				if a_len > index {222					v.0.get_lazy(index)223				} else {224					v.1.get_lazy(index - a_len)225				}226			}227		}228	}229230	pub fn evaluated(&self) -> Result<Cc<Vec<Val>>> {231		Ok(match self {232			Self::Lazy(vec) => {233				let mut out = Vec::with_capacity(vec.len());234				for item in vec.iter() {235					out.push(item.evaluate()?);236				}237				Cc::new(out)238			}239			Self::Eager(vec) => vec.clone(),240			Self::Extended(_v) => {241				let mut out = Vec::with_capacity(self.len());242				for item in self.iter() {243					out.push(item?);244				}245				Cc::new(out)246			}247		})248	}249250	pub fn iter(&self) -> impl DoubleEndedIterator<Item = Result<Val>> + '_ {251		(0..self.len()).map(move |idx| match self {252			Self::Lazy(l) => l[idx].evaluate(),253			Self::Eager(e) => Ok(e[idx].clone()),254			Self::Extended(_) => self.get(idx).map(|e| e.unwrap()),255		})256	}257258	pub fn iter_lazy(&self) -> impl DoubleEndedIterator<Item = LazyVal> + '_ {259		(0..self.len()).map(move |idx| match self {260			Self::Lazy(l) => l[idx].clone(),261			Self::Eager(e) => LazyVal::new_resolved(e[idx].clone()),262			Self::Extended(_) => self.get_lazy(idx).unwrap(),263		})264	}265266	pub fn reversed(self) -> Self {267		match self {268			Self::Lazy(vec) => {269				let mut out = (&vec as &Vec<_>).clone();270				out.reverse();271				Self::Lazy(Cc::new(out))272			}273			Self::Eager(vec) => {274				let mut out = (&vec as &Vec<_>).clone();275				out.reverse();276				Self::Eager(Cc::new(out))277			}278			Self::Extended(b) => Self::Extended(Box::new((b.1.reversed(), b.0.reversed()))),279		}280	}281282	pub fn map(self, mapper: impl Fn(Val) -> Result<Val>) -> Result<Self> {283		let mut out = Vec::with_capacity(self.len());284285		for value in self.iter() {286			out.push(mapper(value?)?);287		}288289		Ok(Self::Eager(Cc::new(out)))290	}291292	pub fn filter(self, filter: impl Fn(&Val) -> Result<bool>) -> Result<Self> {293		let mut out = Vec::with_capacity(self.len());294295		for value in self.iter() {296			let value = value?;297			if filter(&value)? {298				out.push(value);299			}300		}301302		Ok(Self::Eager(Cc::new(out)))303	}304305	pub fn ptr_eq(a: &Self, b: &Self) -> bool {306		match (a, b) {307			(Self::Lazy(a), Self::Lazy(b)) => cc_ptr_eq(a, b),308			(Self::Eager(a), Self::Eager(b)) => cc_ptr_eq(a, b),309			_ => false,310		}311	}312}313314impl From<Vec<LazyVal>> for ArrValue {315	fn from(v: Vec<LazyVal>) -> Self {316		Self::Lazy(Cc::new(v))317	}318}319320impl From<Vec<Val>> for ArrValue {321	fn from(v: Vec<Val>) -> Self {322		Self::Eager(Cc::new(v))323	}324}325326pub enum IndexableVal {327	Str(IStr),328	Arr(ArrValue),329}330331#[derive(Debug, Clone, Trace)]332pub enum Val {333	Bool(bool),334	Null,335	Str(IStr),336	Num(f64),337	Arr(ArrValue),338	Obj(ObjValue),339	Func(FuncVal),340}341342impl Val {343	pub fn as_bool(&self) -> Option<bool> {344		match self {345			Val::Bool(v) => Some(*v),346			_ => None,347		}348	}349	pub fn as_null(&self) -> Option<()> {350		match self {351			Val::Null => Some(()),352			_ => None,353		}354	}355	pub fn as_str(&self) -> Option<IStr> {356		match self {357			Val::Str(s) => Some(s.clone()),358			_ => None,359		}360	}361	pub fn as_num(&self) -> Option<f64> {362		match self {363			Val::Num(n) => Some(*n),364			_ => None,365		}366	}367	pub fn as_arr(&self) -> Option<ArrValue> {368		match self {369			Val::Arr(a) => Some(a.clone()),370			_ => None,371		}372	}373	pub fn as_obj(&self) -> Option<ObjValue> {374		match self {375			Val::Obj(o) => Some(o.clone()),376			_ => None,377		}378	}379	pub fn as_func(&self) -> Option<FuncVal> {380		match self {381			Val::Func(f) => Some(f.clone()),382			_ => None,383		}384	}385386	/// Creates `Val::Num` after checking for numeric overflow.387	/// As numbers are `f64`, we can just check for their finity.388	pub fn new_checked_num(num: f64) -> Result<Self> {389		if num.is_finite() {390			Ok(Self::Num(num))391		} else {392			throw!(RuntimeError("overflow".into()))393		}394	}395396	pub fn try_cast_nullable_num(self, context: &'static str) -> Result<Option<f64>> {397		Ok(match self {398			Val::Null => None,399			Val::Num(num) => Some(num),400			_ => throw!(TypeMismatch(401				context,402				vec![ValType::Null, ValType::Num],403				self.value_type()404			)),405		})406	}407	pub const fn value_type(&self) -> ValType {408		match self {409			Self::Str(..) => ValType::Str,410			Self::Num(..) => ValType::Num,411			Self::Arr(..) => ValType::Arr,412			Self::Obj(..) => ValType::Obj,413			Self::Bool(_) => ValType::Bool,414			Self::Null => ValType::Null,415			Self::Func(..) => ValType::Func,416		}417	}418419	pub fn to_string(&self) -> Result<IStr> {420		Ok(match self {421			Self::Bool(true) => "true".into(),422			Self::Bool(false) => "false".into(),423			Self::Null => "null".into(),424			Self::Str(s) => s.clone(),425			v => manifest_json_ex(426				v,427				&ManifestJsonOptions {428					padding: "",429					mtype: ManifestType::ToString,430					newline: "\n",431					key_val_sep: ": ",432				},433			)?434			.into(),435		})436	}437438	/// Expects value to be object, outputs (key, manifested value) pairs439	pub fn manifest_multi(&self, ty: &ManifestFormat) -> Result<Vec<(IStr, IStr)>> {440		let obj = match self {441			Self::Obj(obj) => obj,442			_ => throw!(MultiManifestOutputIsNotAObject),443		};444		let keys = obj.fields();445		let mut out = Vec::with_capacity(keys.len());446		for key in keys {447			let value = obj448				.get(key.clone())?449				.expect("item in object")450				.manifest(ty)?;451			out.push((key, value));452		}453		Ok(out)454	}455456	/// Expects value to be array, outputs manifested values457	pub fn manifest_stream(&self, ty: &ManifestFormat) -> Result<Vec<IStr>> {458		let arr = match self {459			Self::Arr(a) => a,460			_ => throw!(StreamManifestOutputIsNotAArray),461		};462		let mut out = Vec::with_capacity(arr.len());463		for i in arr.iter() {464			out.push(i?.manifest(ty)?);465		}466		Ok(out)467	}468469	pub fn manifest(&self, ty: &ManifestFormat) -> Result<IStr> {470		Ok(match ty {471			ManifestFormat::YamlStream(format) => {472				let arr = match self {473					Self::Arr(a) => a,474					_ => throw!(StreamManifestOutputIsNotAArray),475				};476				let mut out = String::new();477478				match format as &ManifestFormat {479					ManifestFormat::YamlStream(_) => throw!(StreamManifestOutputCannotBeRecursed),480					ManifestFormat::String => throw!(StreamManifestCannotNestString),481					_ => {}482				};483484				if !arr.is_empty() {485					for v in arr.iter() {486						out.push_str("---\n");487						out.push_str(&v?.manifest(format)?);488						out.push('\n');489					}490					out.push_str("...");491				}492493				out.into()494			}495			ManifestFormat::Yaml(padding) => self.to_yaml(*padding)?,496			ManifestFormat::Json(padding) => self.to_json(*padding)?,497			ManifestFormat::ToString => self.to_string()?,498			ManifestFormat::String => match self {499				Self::Str(s) => s.clone(),500				_ => throw!(StringManifestOutputIsNotAString),501			},502		})503	}504505	/// For manifestification506	pub fn to_json(&self, padding: usize) -> Result<IStr> {507		manifest_json_ex(508			self,509			&ManifestJsonOptions {510				padding: &" ".repeat(padding),511				mtype: if padding == 0 {512					ManifestType::Minify513				} else {514					ManifestType::Manifest515				},516				newline: "\n",517				key_val_sep: ": ",518			},519		)520		.map(|s| s.into())521	}522523	/// Calls `std.manifestJson`524	pub fn to_std_json(&self, padding: usize) -> Result<Rc<str>> {525		manifest_json_ex(526			self,527			&ManifestJsonOptions {528				padding: &" ".repeat(padding),529				mtype: ManifestType::Std,530				newline: "\n",531				key_val_sep: ": ",532			},533		)534		.map(|s| s.into())535	}536537	pub fn to_yaml(&self, padding: usize) -> Result<IStr> {538		let padding = &" ".repeat(padding);539		manifest_yaml_ex(540			self,541			&ManifestYamlOptions {542				padding,543				arr_element_padding: padding,544				quote_keys: false,545			},546		)547		.map(|s| s.into())548	}549	pub fn into_indexable(self) -> Result<IndexableVal> {550		Ok(match self {551			Val::Str(s) => IndexableVal::Str(s),552			Val::Arr(arr) => IndexableVal::Arr(arr),553			_ => throw!(ValueIsNotIndexable(self.value_type())),554		})555	}556}557558const fn is_function_like(val: &Val) -> bool {559	matches!(val, Val::Func(_))560}561562/// Native implementation of `std.primitiveEquals`563pub fn primitive_equals(val_a: &Val, val_b: &Val) -> Result<bool> {564	Ok(match (val_a, val_b) {565		(Val::Bool(a), Val::Bool(b)) => a == b,566		(Val::Null, Val::Null) => true,567		(Val::Str(a), Val::Str(b)) => a == b,568		(Val::Num(a), Val::Num(b)) => (a - b).abs() <= f64::EPSILON,569		(Val::Arr(_), Val::Arr(_)) => throw!(RuntimeError(570			"primitiveEquals operates on primitive types, got array".into(),571		)),572		(Val::Obj(_), Val::Obj(_)) => throw!(RuntimeError(573			"primitiveEquals operates on primitive types, got object".into(),574		)),575		(a, b) if is_function_like(a) && is_function_like(b) => {576			throw!(RuntimeError("cannot test equality of functions".into()))577		}578		(_, _) => false,579	})580}581582/// Native implementation of `std.equals`583pub fn equals(val_a: &Val, val_b: &Val) -> Result<bool> {584	if val_a.value_type() != val_b.value_type() {585		return Ok(false);586	}587	match (val_a, val_b) {588		(Val::Arr(a), Val::Arr(b)) => {589			if ArrValue::ptr_eq(a, b) {590				return Ok(true);591			}592			if a.len() != b.len() {593				return Ok(false);594			}595			for (a, b) in a.iter().zip(b.iter()) {596				if !equals(&a?, &b?)? {597					return Ok(false);598				}599			}600			Ok(true)601		}602		(Val::Obj(a), Val::Obj(b)) => {603			if ObjValue::ptr_eq(a, b) {604				return Ok(true);605			}606			let fields = a.fields();607			if fields != b.fields() {608				return Ok(false);609			}610			for field in fields {611				if !equals(&a.get(field.clone())?.unwrap(), &b.get(field)?.unwrap())? {612					return Ok(false);613				}614			}615			Ok(true)616		}617		(a, b) => Ok(primitive_equals(a, b)?),618	}619}
after · crates/jrsonnet-evaluator/src/val.rs
1use crate::{2	builtin::manifest::{3		manifest_json_ex, manifest_yaml_ex, ManifestJsonOptions, ManifestType, ManifestYamlOptions,4	},5	cc_ptr_eq,6	error::{Error::*, LocError},7	evaluate,8	function::{9		parse_default_function_call, parse_function_call, ArgsLike, Builtin, StaticBuiltin,10	},11	gc::TraceBox,12	throw, Context, ObjValue, Result,13};14use gcmodule::{Cc, Trace};15use jrsonnet_interner::IStr;16use jrsonnet_parser::{ExprLocation, LocExpr, ParamsDesc};17use jrsonnet_types::ValType;18use std::{cell::RefCell, fmt::Debug, rc::Rc};1920pub trait LazyValValue: Trace {21	fn get(self: Box<Self>) -> Result<Val>;22}2324#[derive(Trace)]25enum LazyValInternals {26	Computed(Val),27	Errored(LocError),28	Waiting(TraceBox<dyn LazyValValue>),29	Pending,30}3132#[derive(Clone, Trace)]33pub struct LazyVal(Cc<RefCell<LazyValInternals>>);34impl LazyVal {35	pub fn new(f: TraceBox<dyn LazyValValue>) -> Self {36		Self(Cc::new(RefCell::new(LazyValInternals::Waiting(f))))37	}38	pub fn new_resolved(val: Val) -> Self {39		Self(Cc::new(RefCell::new(LazyValInternals::Computed(val))))40	}41	pub fn force(&self) -> Result<()> {42		self.evaluate()?;43		Ok(())44	}45	pub fn evaluate(&self) -> Result<Val> {46		match &*self.0.borrow() {47			LazyValInternals::Computed(v) => return Ok(v.clone()),48			LazyValInternals::Errored(e) => return Err(e.clone()),49			LazyValInternals::Pending => return Err(RecursiveLazyValueEvaluation.into()),50			_ => (),51		};52		let value = if let LazyValInternals::Waiting(value) =53			std::mem::replace(&mut *self.0.borrow_mut(), LazyValInternals::Pending)54		{55			value56		} else {57			unreachable!()58		};59		let new_value = match value.0.get() {60			Ok(v) => v,61			Err(e) => {62				*self.0.borrow_mut() = LazyValInternals::Errored(e.clone());63				return Err(e);64			}65		};66		*self.0.borrow_mut() = LazyValInternals::Computed(new_value.clone());67		Ok(new_value)68	}69}7071impl Debug for LazyVal {72	fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {73		write!(f, "Lazy")74	}75}76impl PartialEq for LazyVal {77	fn eq(&self, other: &Self) -> bool {78		cc_ptr_eq(&self.0, &other.0)79	}80}8182#[derive(Debug, PartialEq, Trace)]83pub struct FuncDesc {84	pub name: IStr,85	pub ctx: Context,86	pub params: ParamsDesc,87	pub body: LocExpr,88}89impl FuncDesc {90	/// Create body context, but fill arguments without defaults with lazy error91	pub fn default_body_context(&self) -> Context {92		parse_default_function_call(self.ctx.clone(), &self.params)93	}9495	/// Create context, with which body code will run96	pub fn call_body_context(97		&self,98		call_ctx: Context,99		args: &dyn ArgsLike,100		tailstrict: bool,101	) -> Result<Context> {102		parse_function_call(call_ctx, self.ctx.clone(), &self.params, args, tailstrict)103	}104}105106#[derive(Trace, Clone)]107pub enum FuncVal {108	/// Plain function implemented in jsonnet109	Normal(Cc<FuncDesc>),110	/// Standard library function111	StaticBuiltin(#[skip_trace] &'static dyn StaticBuiltin),112	/// User-provided function113	Builtin(Cc<TraceBox<dyn Builtin>>),114}115116impl Debug for FuncVal {117	fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {118		match self {119			Self::Normal(arg0) => f.debug_tuple("Normal").field(arg0).finish(),120			Self::StaticBuiltin(arg0) => {121				f.debug_tuple("StaticBuiltin").field(&arg0.name()).finish()122			}123			Self::Builtin(arg0) => f.debug_tuple("Builtin").field(&arg0.name()).finish(),124		}125	}126}127128impl PartialEq for FuncVal {129	fn eq(&self, other: &Self) -> bool {130		match (self, other) {131			(Self::Normal(a), Self::Normal(b)) => a == b,132			(Self::StaticBuiltin(an), Self::StaticBuiltin(bn)) => std::ptr::eq(*an, *bn),133			(..) => false,134		}135	}136}137impl FuncVal {138	pub fn args_len(&self) -> usize {139		match self {140			Self::Normal(n) => n.params.iter().filter(|p| p.1.is_none()).count(),141			Self::StaticBuiltin(i) => i.params().iter().filter(|p| !p.has_default).count(),142			Self::Builtin(i) => i.params().iter().filter(|p| !p.has_default).count(),143		}144	}145	pub fn name(&self) -> IStr {146		match self {147			Self::Normal(normal) => normal.name.clone(),148			Self::StaticBuiltin(builtin) => builtin.name().into(),149			Self::Builtin(builtin) => builtin.name().into(),150		}151	}152	pub fn evaluate(153		&self,154		call_ctx: Context,155		loc: Option<&ExprLocation>,156		args: &dyn ArgsLike,157		tailstrict: bool,158	) -> Result<Val> {159		match self {160			Self::Normal(func) => {161				let body_ctx = func.call_body_context(call_ctx, args, tailstrict)?;162				evaluate(body_ctx, &func.body)163			}164			Self::StaticBuiltin(b) => b.call(call_ctx, loc, args),165			Self::Builtin(b) => b.call(call_ctx, loc, args),166		}167	}168	pub fn evaluate_simple(&self, args: &dyn ArgsLike) -> Result<Val> {169		self.evaluate(Context::default(), None, args, true)170	}171}172173#[derive(Clone)]174pub enum ManifestFormat {175	YamlStream(Box<ManifestFormat>),176	Yaml(usize),177	Json(usize),178	ToString,179	String,180}181182#[derive(Debug, Clone, Trace)]183#[force_tracking]184pub enum ArrValue {185	Lazy(Cc<Vec<LazyVal>>),186	Eager(Cc<Vec<Val>>),187	Extended(Box<(Self, Self)>),188}189impl ArrValue {190	pub fn new_eager() -> Self {191		Self::Eager(Cc::new(Vec::new()))192	}193194	pub fn len(&self) -> usize {195		match self {196			Self::Lazy(l) => l.len(),197			Self::Eager(e) => e.len(),198			Self::Extended(v) => v.0.len() + v.1.len(),199		}200	}201202	pub fn is_empty(&self) -> bool {203		self.len() == 0204	}205206	pub fn get(&self, index: usize) -> Result<Option<Val>> {207		match self {208			Self::Lazy(vec) => {209				if let Some(v) = vec.get(index) {210					Ok(Some(v.evaluate()?))211				} else {212					Ok(None)213				}214			}215			Self::Eager(vec) => Ok(vec.get(index).cloned()),216			Self::Extended(v) => {217				let a_len = v.0.len();218				if a_len > index {219					v.0.get(index)220				} else {221					v.1.get(index - a_len)222				}223			}224		}225	}226227	pub fn get_lazy(&self, index: usize) -> Option<LazyVal> {228		match self {229			Self::Lazy(vec) => vec.get(index).cloned(),230			Self::Eager(vec) => vec.get(index).cloned().map(LazyVal::new_resolved),231			Self::Extended(v) => {232				let a_len = v.0.len();233				if a_len > index {234					v.0.get_lazy(index)235				} else {236					v.1.get_lazy(index - a_len)237				}238			}239		}240	}241242	pub fn evaluated(&self) -> Result<Cc<Vec<Val>>> {243		Ok(match self {244			Self::Lazy(vec) => {245				let mut out = Vec::with_capacity(vec.len());246				for item in vec.iter() {247					out.push(item.evaluate()?);248				}249				Cc::new(out)250			}251			Self::Eager(vec) => vec.clone(),252			Self::Extended(_v) => {253				let mut out = Vec::with_capacity(self.len());254				for item in self.iter() {255					out.push(item?);256				}257				Cc::new(out)258			}259		})260	}261262	pub fn iter(&self) -> impl DoubleEndedIterator<Item = Result<Val>> + '_ {263		(0..self.len()).map(move |idx| match self {264			Self::Lazy(l) => l[idx].evaluate(),265			Self::Eager(e) => Ok(e[idx].clone()),266			Self::Extended(_) => self.get(idx).map(|e| e.unwrap()),267		})268	}269270	pub fn iter_lazy(&self) -> impl DoubleEndedIterator<Item = LazyVal> + '_ {271		(0..self.len()).map(move |idx| match self {272			Self::Lazy(l) => l[idx].clone(),273			Self::Eager(e) => LazyVal::new_resolved(e[idx].clone()),274			Self::Extended(_) => self.get_lazy(idx).unwrap(),275		})276	}277278	pub fn reversed(self) -> Self {279		match self {280			Self::Lazy(vec) => {281				let mut out = (&vec as &Vec<_>).clone();282				out.reverse();283				Self::Lazy(Cc::new(out))284			}285			Self::Eager(vec) => {286				let mut out = (&vec as &Vec<_>).clone();287				out.reverse();288				Self::Eager(Cc::new(out))289			}290			Self::Extended(b) => Self::Extended(Box::new((b.1.reversed(), b.0.reversed()))),291		}292	}293294	pub fn map(self, mapper: impl Fn(Val) -> Result<Val>) -> Result<Self> {295		let mut out = Vec::with_capacity(self.len());296297		for value in self.iter() {298			out.push(mapper(value?)?);299		}300301		Ok(Self::Eager(Cc::new(out)))302	}303304	pub fn filter(self, filter: impl Fn(&Val) -> Result<bool>) -> Result<Self> {305		let mut out = Vec::with_capacity(self.len());306307		for value in self.iter() {308			let value = value?;309			if filter(&value)? {310				out.push(value);311			}312		}313314		Ok(Self::Eager(Cc::new(out)))315	}316317	pub fn ptr_eq(a: &Self, b: &Self) -> bool {318		match (a, b) {319			(Self::Lazy(a), Self::Lazy(b)) => cc_ptr_eq(a, b),320			(Self::Eager(a), Self::Eager(b)) => cc_ptr_eq(a, b),321			_ => false,322		}323	}324}325326impl From<Vec<LazyVal>> for ArrValue {327	fn from(v: Vec<LazyVal>) -> Self {328		Self::Lazy(Cc::new(v))329	}330}331332impl From<Vec<Val>> for ArrValue {333	fn from(v: Vec<Val>) -> Self {334		Self::Eager(Cc::new(v))335	}336}337338pub enum IndexableVal {339	Str(IStr),340	Arr(ArrValue),341}342343#[derive(Debug, Clone, Trace)]344pub enum Val {345	Bool(bool),346	Null,347	Str(IStr),348	Num(f64),349	Arr(ArrValue),350	Obj(ObjValue),351	Func(FuncVal),352}353354impl Val {355	pub fn as_bool(&self) -> Option<bool> {356		match self {357			Val::Bool(v) => Some(*v),358			_ => None,359		}360	}361	pub fn as_null(&self) -> Option<()> {362		match self {363			Val::Null => Some(()),364			_ => None,365		}366	}367	pub fn as_str(&self) -> Option<IStr> {368		match self {369			Val::Str(s) => Some(s.clone()),370			_ => None,371		}372	}373	pub fn as_num(&self) -> Option<f64> {374		match self {375			Val::Num(n) => Some(*n),376			_ => None,377		}378	}379	pub fn as_arr(&self) -> Option<ArrValue> {380		match self {381			Val::Arr(a) => Some(a.clone()),382			_ => None,383		}384	}385	pub fn as_obj(&self) -> Option<ObjValue> {386		match self {387			Val::Obj(o) => Some(o.clone()),388			_ => None,389		}390	}391	pub fn as_func(&self) -> Option<FuncVal> {392		match self {393			Val::Func(f) => Some(f.clone()),394			_ => None,395		}396	}397398	/// Creates `Val::Num` after checking for numeric overflow.399	/// As numbers are `f64`, we can just check for their finity.400	pub fn new_checked_num(num: f64) -> Result<Self> {401		if num.is_finite() {402			Ok(Self::Num(num))403		} else {404			throw!(RuntimeError("overflow".into()))405		}406	}407408	pub fn try_cast_nullable_num(self, context: &'static str) -> Result<Option<f64>> {409		Ok(match self {410			Val::Null => None,411			Val::Num(num) => Some(num),412			_ => throw!(TypeMismatch(413				context,414				vec![ValType::Null, ValType::Num],415				self.value_type()416			)),417		})418	}419	pub const fn value_type(&self) -> ValType {420		match self {421			Self::Str(..) => ValType::Str,422			Self::Num(..) => ValType::Num,423			Self::Arr(..) => ValType::Arr,424			Self::Obj(..) => ValType::Obj,425			Self::Bool(_) => ValType::Bool,426			Self::Null => ValType::Null,427			Self::Func(..) => ValType::Func,428		}429	}430431	pub fn to_string(&self) -> Result<IStr> {432		Ok(match self {433			Self::Bool(true) => "true".into(),434			Self::Bool(false) => "false".into(),435			Self::Null => "null".into(),436			Self::Str(s) => s.clone(),437			v => manifest_json_ex(438				v,439				&ManifestJsonOptions {440					padding: "",441					mtype: ManifestType::ToString,442					newline: "\n",443					key_val_sep: ": ",444				},445			)?446			.into(),447		})448	}449450	/// Expects value to be object, outputs (key, manifested value) pairs451	pub fn manifest_multi(&self, ty: &ManifestFormat) -> Result<Vec<(IStr, IStr)>> {452		let obj = match self {453			Self::Obj(obj) => obj,454			_ => throw!(MultiManifestOutputIsNotAObject),455		};456		let keys = obj.fields();457		let mut out = Vec::with_capacity(keys.len());458		for key in keys {459			let value = obj460				.get(key.clone())?461				.expect("item in object")462				.manifest(ty)?;463			out.push((key, value));464		}465		Ok(out)466	}467468	/// Expects value to be array, outputs manifested values469	pub fn manifest_stream(&self, ty: &ManifestFormat) -> Result<Vec<IStr>> {470		let arr = match self {471			Self::Arr(a) => a,472			_ => throw!(StreamManifestOutputIsNotAArray),473		};474		let mut out = Vec::with_capacity(arr.len());475		for i in arr.iter() {476			out.push(i?.manifest(ty)?);477		}478		Ok(out)479	}480481	pub fn manifest(&self, ty: &ManifestFormat) -> Result<IStr> {482		Ok(match ty {483			ManifestFormat::YamlStream(format) => {484				let arr = match self {485					Self::Arr(a) => a,486					_ => throw!(StreamManifestOutputIsNotAArray),487				};488				let mut out = String::new();489490				match format as &ManifestFormat {491					ManifestFormat::YamlStream(_) => throw!(StreamManifestOutputCannotBeRecursed),492					ManifestFormat::String => throw!(StreamManifestCannotNestString),493					_ => {}494				};495496				if !arr.is_empty() {497					for v in arr.iter() {498						out.push_str("---\n");499						out.push_str(&v?.manifest(format)?);500						out.push('\n');501					}502					out.push_str("...");503				}504505				out.into()506			}507			ManifestFormat::Yaml(padding) => self.to_yaml(*padding)?,508			ManifestFormat::Json(padding) => self.to_json(*padding)?,509			ManifestFormat::ToString => self.to_string()?,510			ManifestFormat::String => match self {511				Self::Str(s) => s.clone(),512				_ => throw!(StringManifestOutputIsNotAString),513			},514		})515	}516517	/// For manifestification518	pub fn to_json(&self, padding: usize) -> Result<IStr> {519		manifest_json_ex(520			self,521			&ManifestJsonOptions {522				padding: &" ".repeat(padding),523				mtype: if padding == 0 {524					ManifestType::Minify525				} else {526					ManifestType::Manifest527				},528				newline: "\n",529				key_val_sep: ": ",530			},531		)532		.map(|s| s.into())533	}534535	/// Calls `std.manifestJson`536	pub fn to_std_json(&self, padding: usize) -> Result<Rc<str>> {537		manifest_json_ex(538			self,539			&ManifestJsonOptions {540				padding: &" ".repeat(padding),541				mtype: ManifestType::Std,542				newline: "\n",543				key_val_sep: ": ",544			},545		)546		.map(|s| s.into())547	}548549	pub fn to_yaml(&self, padding: usize) -> Result<IStr> {550		let padding = &" ".repeat(padding);551		manifest_yaml_ex(552			self,553			&ManifestYamlOptions {554				padding,555				arr_element_padding: padding,556				quote_keys: false,557			},558		)559		.map(|s| s.into())560	}561	pub fn into_indexable(self) -> Result<IndexableVal> {562		Ok(match self {563			Val::Str(s) => IndexableVal::Str(s),564			Val::Arr(arr) => IndexableVal::Arr(arr),565			_ => throw!(ValueIsNotIndexable(self.value_type())),566		})567	}568}569570const fn is_function_like(val: &Val) -> bool {571	matches!(val, Val::Func(_))572}573574/// Native implementation of `std.primitiveEquals`575pub fn primitive_equals(val_a: &Val, val_b: &Val) -> Result<bool> {576	Ok(match (val_a, val_b) {577		(Val::Bool(a), Val::Bool(b)) => a == b,578		(Val::Null, Val::Null) => true,579		(Val::Str(a), Val::Str(b)) => a == b,580		(Val::Num(a), Val::Num(b)) => (a - b).abs() <= f64::EPSILON,581		(Val::Arr(_), Val::Arr(_)) => throw!(RuntimeError(582			"primitiveEquals operates on primitive types, got array".into(),583		)),584		(Val::Obj(_), Val::Obj(_)) => throw!(RuntimeError(585			"primitiveEquals operates on primitive types, got object".into(),586		)),587		(a, b) if is_function_like(a) && is_function_like(b) => {588			throw!(RuntimeError("cannot test equality of functions".into()))589		}590		(_, _) => false,591	})592}593594/// Native implementation of `std.equals`595pub fn equals(val_a: &Val, val_b: &Val) -> Result<bool> {596	if val_a.value_type() != val_b.value_type() {597		return Ok(false);598	}599	match (val_a, val_b) {600		(Val::Arr(a), Val::Arr(b)) => {601			if ArrValue::ptr_eq(a, b) {602				return Ok(true);603			}604			if a.len() != b.len() {605				return Ok(false);606			}607			for (a, b) in a.iter().zip(b.iter()) {608				if !equals(&a?, &b?)? {609					return Ok(false);610				}611			}612			Ok(true)613		}614		(Val::Obj(a), Val::Obj(b)) => {615			if ObjValue::ptr_eq(a, b) {616				return Ok(true);617			}618			let fields = a.fields();619			if fields != b.fields() {620				return Ok(false);621			}622			for field in fields {623				if !equals(&a.get(field.clone())?.unwrap(), &b.get(field)?.unwrap())? {624					return Ok(false);625				}626			}627			Ok(true)628		}629		(a, b) => Ok(primitive_equals(a, b)?),630	}631}