git.delta.rocks / jrsonnet / refs/commits / 788037fe57fe

difftreelog

source

crates/jrsonnet-evaluator/src/val.rs12.2 KiBsourcehistory
1use crate::{2	builtin::{3		call_builtin,4		manifest::{manifest_json_ex, ManifestJsonOptions, ManifestType},5	},6	error::Error::*,7	evaluate,8	function::{parse_function_call, parse_function_call_map, place_args},9	native::NativeCallback,10	throw, with_state, Context, ObjValue, Result,11};12use jrsonnet_parser::{el, Arg, ArgsDesc, Expr, ExprLocation, LocExpr, ParamsDesc};13use std::{14	cell::RefCell,15	collections::HashMap,16	fmt::{Debug, Display},17	rc::Rc,18};1920enum LazyValInternals {21	Computed(Val),22	Waiting(Box<dyn Fn() -> Result<Val>>),23}24#[derive(Clone)]25pub struct LazyVal(Rc<RefCell<LazyValInternals>>);26impl LazyVal {27	pub fn new(f: Box<dyn Fn() -> Result<Val>>) -> Self {28		LazyVal(Rc::new(RefCell::new(LazyValInternals::Waiting(f))))29	}30	pub fn new_resolved(val: Val) -> Self {31		LazyVal(Rc::new(RefCell::new(LazyValInternals::Computed(val))))32	}33	pub fn evaluate(&self) -> Result<Val> {34		let new_value = match &*self.0.borrow() {35			LazyValInternals::Computed(v) => return Ok(v.clone()),36			LazyValInternals::Waiting(f) => f()?,37		};38		*self.0.borrow_mut() = LazyValInternals::Computed(new_value.clone());39		Ok(new_value)40	}41}4243#[macro_export]44macro_rules! lazy_val {45	($f: expr) => {46		$crate::LazyVal::new(Box::new($f))47	};48}49#[macro_export]50macro_rules! resolved_lazy_val {51	($f: expr) => {52		$crate::LazyVal::new_resolved($f)53	};54}55impl Debug for LazyVal {56	fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {57		write!(f, "Lazy")58	}59}60impl PartialEq for LazyVal {61	fn eq(&self, other: &Self) -> bool {62		Rc::ptr_eq(&self.0, &other.0)63	}64}6566#[derive(Debug, PartialEq)]67pub struct FuncDesc {68	pub name: Rc<str>,69	pub ctx: Context,70	pub params: ParamsDesc,71	pub body: LocExpr,72}7374#[derive(Debug)]75pub enum FuncVal {76	/// Plain function implemented in jsonnet77	Normal(FuncDesc),78	/// Standard library function79	Intristic(Rc<str>, Rc<str>),80	/// Library functions implemented in native81	NativeExt(Rc<str>, Rc<NativeCallback>),82}8384impl PartialEq for FuncVal {85	fn eq(&self, other: &Self) -> bool {86		match (self, other) {87			(FuncVal::Normal(a), FuncVal::Normal(b)) => a == b,88			(FuncVal::Intristic(ans, an), FuncVal::Intristic(bns, bn)) => ans == bns && an == bn,89			(FuncVal::NativeExt(an, _), FuncVal::NativeExt(bn, _)) => an == bn,90			(..) => false,91		}92	}93}94impl FuncVal {95	pub fn is_ident(&self) -> bool {96		matches!(&self, FuncVal::Intristic(ns, n) if ns as &str == "std" && n as &str == "id")97	}98	pub fn name(&self) -> Rc<str> {99		match self {100			FuncVal::Normal(normal) => normal.name.clone(),101			FuncVal::Intristic(ns, name) => format!("intristic.{}.{}", ns, name).into(),102			FuncVal::NativeExt(n, _) => format!("native.{}", n).into(),103		}104	}105	pub fn evaluate(106		&self,107		call_ctx: Context,108		loc: &Option<ExprLocation>,109		args: &ArgsDesc,110		tailstrict: bool,111	) -> Result<Val> {112		match self {113			FuncVal::Normal(func) => {114				let ctx = parse_function_call(115					call_ctx,116					Some(func.ctx.clone()),117					&func.params,118					args,119					tailstrict,120				)?;121				evaluate(ctx, &func.body)122			}123			FuncVal::Intristic(ns, name) => call_builtin(call_ctx, loc, &ns, &name, args),124			FuncVal::NativeExt(_name, handler) => {125				let args = parse_function_call(call_ctx, None, &handler.params, args, true)?;126				let mut out_args = Vec::with_capacity(handler.params.len());127				for p in handler.params.0.iter() {128					out_args.push(args.binding(p.0.clone())?.evaluate()?);129				}130				Ok(handler.call(&out_args)?)131			}132		}133	}134135	pub fn evaluate_map(136		&self,137		call_ctx: Context,138		args: &HashMap<Rc<str>, Val>,139		tailstrict: bool,140	) -> Result<Val> {141		match self {142			FuncVal::Normal(func) => {143				let ctx = parse_function_call_map(144					call_ctx,145					Some(func.ctx.clone()),146					&func.params,147					args,148					tailstrict,149				)?;150				evaluate(ctx, &func.body)151			}152			FuncVal::Intristic(_, _) => todo!(),153			FuncVal::NativeExt(_, _) => todo!(),154		}155	}156157	pub fn evaluate_values(&self, call_ctx: Context, args: &[Val]) -> Result<Val> {158		match self {159			FuncVal::Normal(func) => {160				let ctx = place_args(call_ctx, Some(func.ctx.clone()), &func.params, args)?;161				evaluate(ctx, &func.body)162			}163			FuncVal::Intristic(_, _) => todo!(),164			FuncVal::NativeExt(_, _) => todo!(),165		}166	}167}168169#[derive(Debug, Clone, Copy, PartialEq)]170pub enum ValType {171	Bool,172	Null,173	Str,174	Num,175	Arr,176	Obj,177	Func,178}179impl ValType {180	pub fn name(&self) -> &'static str {181		use ValType::*;182		match self {183			Bool => "boolean",184			Null => "null",185			Str => "string",186			Num => "number",187			Arr => "array",188			Obj => "object",189			Func => "function",190		}191	}192}193impl Display for ValType {194	fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {195		write!(f, "{}", self.name())196	}197}198199#[derive(Clone)]200pub enum ManifestFormat {201	YamlStream(Box<ManifestFormat>),202	Yaml(usize),203	Json(usize),204	String,205}206207#[derive(Debug, Clone)]208pub enum Val {209	Bool(bool),210	Null,211	Str(Rc<str>),212	Num(f64),213	Lazy(LazyVal),214	Arr(Rc<Vec<Val>>),215	Obj(ObjValue),216	Func(Rc<FuncVal>),217}218219macro_rules! matches_unwrap {220	($e: expr, $p: pat, $r: expr) => {221		match $e {222			$p => $r,223			_ => panic!("no match"),224			}225	};226}227impl Val {228	/// Creates Val::Num after checking for overflow. As numbers are f64, we can just check for finity229	pub fn new_checked_num(num: f64) -> Result<Val> {230		if num.is_finite() {231			Ok(Val::Num(num))232		} else {233			throw!(RuntimeError("overflow".into()))234		}235	}236237	pub fn assert_type(&self, context: &'static str, val_type: ValType) -> Result<()> {238		let this_type = self.value_type()?;239		if this_type != val_type {240			throw!(TypeMismatch(context, vec![val_type], this_type))241		} else {242			Ok(())243		}244	}245	pub fn try_cast_bool(self, context: &'static str) -> Result<bool> {246		self.assert_type(context, ValType::Bool)?;247		Ok(matches_unwrap!(self.unwrap_if_lazy()?, Val::Bool(v), v))248	}249	pub fn try_cast_str(self, context: &'static str) -> Result<Rc<str>> {250		self.assert_type(context, ValType::Str)?;251		Ok(matches_unwrap!(self.unwrap_if_lazy()?, Val::Str(v), v))252	}253	pub fn try_cast_num(self, context: &'static str) -> Result<f64> {254		self.assert_type(context, ValType::Num)?;255		Ok(matches_unwrap!(self.unwrap_if_lazy()?, Val::Num(v), v))256	}257	pub fn inplace_unwrap(&mut self) -> Result<()> {258		while let Val::Lazy(lazy) = self {259			*self = lazy.evaluate()?;260		}261		Ok(())262	}263	pub fn unwrap_if_lazy(&self) -> Result<Self> {264		Ok(if let Val::Lazy(v) = self {265			v.evaluate()?.unwrap_if_lazy()?266		} else {267			self.clone()268		})269	}270	pub fn value_type(&self) -> Result<ValType> {271		Ok(match self {272			Val::Str(..) => ValType::Str,273			Val::Num(..) => ValType::Num,274			Val::Arr(..) => ValType::Arr,275			Val::Obj(..) => ValType::Obj,276			Val::Bool(_) => ValType::Bool,277			Val::Null => ValType::Null,278			Val::Func(..) => ValType::Func,279			Val::Lazy(_) => self.clone().unwrap_if_lazy()?.value_type()?,280		})281	}282283	pub fn to_string(&self) -> Result<Rc<str>> {284		Ok(match self.unwrap_if_lazy()? {285			Val::Bool(true) => "true".into(),286			Val::Bool(false) => "false".into(),287			Val::Null => "null".into(),288			Val::Str(s) => s,289			v => manifest_json_ex(290				&v,291				&ManifestJsonOptions {292					padding: &"",293					mtype: ManifestType::ToString,294				},295			)?296			.into(),297		})298	}299300	/// Expects value to be object, outputs (key, manifested value) pairs301	pub fn manifest_multi(&self, ty: &ManifestFormat) -> Result<Vec<(Rc<str>, Rc<str>)>> {302		let obj = match self {303			Val::Obj(obj) => obj,304			_ => throw!(MultiManifestOutputIsNotAObject),305		};306		let keys = obj.visible_fields();307		let mut out = Vec::with_capacity(keys.len());308		for key in keys {309			let value = obj310				.get(key.clone())?311				.expect("item in object")312				.manifest(ty)?;313			out.push((key, value));314		}315		Ok(out)316	}317318	/// Expects value to be array, outputs manifested values319	pub fn manifest_stream(&self, ty: &ManifestFormat) -> Result<Vec<Rc<str>>> {320		let arr = match self {321			Val::Arr(a) => a,322			_ => throw!(StreamManifestOutputIsNotAArray),323		};324		let mut out = Vec::with_capacity(arr.len());325		for i in arr.iter() {326			out.push(i.manifest(ty)?);327		}328		Ok(out)329	}330331	pub fn manifest(&self, ty: &ManifestFormat) -> Result<Rc<str>> {332		Ok(match ty {333			ManifestFormat::YamlStream(format) => {334				let arr = match self {335					Val::Arr(a) => a,336					_ => throw!(StreamManifestOutputIsNotAArray),337				};338				let mut out = String::new();339340				match format as &ManifestFormat {341					ManifestFormat::YamlStream(_) => throw!(StreamManifestOutputCannotBeRecursed),342					ManifestFormat::String => throw!(StreamManifestCannotNestString),343					_ => {}344				};345346				if !arr.is_empty() {347					for v in arr.iter() {348						out.push_str("---\n");349						out.push_str(&v.manifest(format)?);350						out.push_str("\n");351					}352					out.push_str("...");353				}354355				out.into()356			}357			ManifestFormat::Yaml(padding) => self.to_yaml(*padding)?,358			ManifestFormat::Json(padding) => self.to_json(*padding)?,359			ManifestFormat::String => match self {360				Val::Str(s) => s.clone(),361				_ => throw!(StringManifestOutputIsNotAString),362			},363		})364	}365366	/// For manifestification367	pub fn to_json(&self, padding: usize) -> Result<Rc<str>> {368		manifest_json_ex(369			self,370			&ManifestJsonOptions {371				padding: &" ".repeat(padding),372				mtype: if padding == 0 {373					ManifestType::Minify374				} else {375					ManifestType::Manifest376				},377			},378		)379		.map(|s| s.into())380	}381382	/// Calls std.manifestJson383	#[cfg(feature = "faster")]384	pub fn to_std_json(&self, padding: usize) -> Result<Rc<str>> {385		manifest_json_ex(386			&self,387			&ManifestJsonOptions {388				padding: &" ".repeat(padding),389				mtype: ManifestType::Std,390			},391		)392		.map(|s| s.into())393	}394395	/// Calls std.manifestJson396	#[cfg(not(feature = "faster"))]397	pub fn to_std_json(&self, padding: usize) -> Result<Rc<str>> {398		with_state(|s| {399			let ctx = s400				.create_default_context()?401				.with_var("__tmp__to_json__".into(), self.clone())?;402			Ok(evaluate(403				ctx,404				&el!(Expr::Apply(405					el!(Expr::Index(406						el!(Expr::Var("std".into())),407						el!(Expr::Str("manifestJsonEx".into()))408					)),409					ArgsDesc(vec![410						Arg(None, el!(Expr::Var("__tmp__to_json__".into()))),411						Arg(None, el!(Expr::Str(" ".repeat(padding).into())))412					]),413					false414				)),415			)?416			.try_cast_str("to json")?)417		})418	}419	pub fn to_yaml(&self, padding: usize) -> Result<Rc<str>> {420		with_state(|s| {421			let ctx = s422				.create_default_context()?423				.with_var("__tmp__to_json__".into(), self.clone());424			Ok(evaluate(425				ctx,426				&el!(Expr::Apply(427					el!(Expr::Index(428						el!(Expr::Var("std".into())),429						el!(Expr::Str("manifestYamlDoc".into()))430					)),431					ArgsDesc(vec![432						Arg(None, el!(Expr::Var("__tmp__to_json__".into()))),433						Arg(None, el!(Expr::Str(" ".repeat(padding).into())))434					]),435					false436				)),437			)?438			.try_cast_str("to json")?)439		})440	}441}442443fn is_function_like(val: &Val) -> bool {444	matches!(val, Val::Func(_))445}446447/// Implements std.primitiveEquals builtin448pub fn primitive_equals(val_a: &Val, val_b: &Val) -> Result<bool> {449	Ok(match (val_a.unwrap_if_lazy()?, val_b.unwrap_if_lazy()?) {450		(Val::Bool(a), Val::Bool(b)) => a == b,451		(Val::Null, Val::Null) => true,452		(Val::Str(a), Val::Str(b)) => a == b,453		(Val::Num(a), Val::Num(b)) => (a - b).abs() <= f64::EPSILON,454		(Val::Arr(_), Val::Arr(_)) => throw!(RuntimeError(455			"primitiveEquals operates on primitive types, got array".into(),456		)),457		(Val::Obj(_), Val::Obj(_)) => throw!(RuntimeError(458			"primitiveEquals operates on primitive types, got object".into(),459		)),460		(a, b) if is_function_like(&a) && is_function_like(&b) => {461			throw!(RuntimeError("cannot test equality of functions".into()))462		}463		(_, _) => false,464	})465}466467/// Native implementation of std.equals468pub fn equals(val_a: &Val, val_b: &Val) -> Result<bool> {469	let val_a = val_a.unwrap_if_lazy()?;470	let val_b = val_b.unwrap_if_lazy()?;471472	if val_a.value_type()? != val_b.value_type()? {473		return Ok(false);474	}475	match (val_a, val_b) {476		// Cant test for ptr equality, because all fields needs to be evaluated477		(Val::Arr(a), Val::Arr(b)) => {478			if a.len() != b.len() {479				return Ok(false);480			}481			for (a, b) in a.iter().zip(b.iter()) {482				if !equals(&a.unwrap_if_lazy()?, &b.unwrap_if_lazy()?)? {483					return Ok(false);484				}485			}486			Ok(true)487		}488		(Val::Obj(a), Val::Obj(b)) => {489			let fields = a.visible_fields();490			if fields != b.visible_fields() {491				return Ok(false);492			}493			for field in fields {494				if !equals(&a.get(field.clone())?.unwrap(), &b.get(field)?.unwrap())? {495					return Ok(false);496				}497			}498			Ok(true)499		}500		(a, b) => Ok(primitive_equals(&a, &b)?),501	}502}