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

difftreelog

source

crates/jrsonnet-evaluator/src/val.rs14.3 KiBsourcehistory
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}