git.delta.rocks / jrsonnet / refs/commits / 31f2b649c192

difftreelog

source

crates/jrsonnet-evaluator/src/val.rs15.0 KiBsourcehistory
1use crate::{2	builtin::{3		call_builtin,4		manifest::{5			manifest_json_ex, manifest_yaml_ex, ManifestJsonOptions, ManifestType,6			ManifestYamlOptions,7		},8	},9	error::{Error::*, LocError},10	evaluate,11	function::{parse_function_call, parse_function_call_map, place_args},12	native::NativeCallback,13	throw, Context, ObjValue, Result,14};15use jrsonnet_gc::{Gc, GcCell, Trace};16use jrsonnet_interner::IStr;17use jrsonnet_parser::{ArgsDesc, ExprLocation, LocExpr, ParamsDesc};18use jrsonnet_types::ValType;19use std::{collections::HashMap, fmt::Debug, rc::Rc};2021pub trait LazyValValue: Trace {22	fn get(self: Box<Self>) -> Result<Val>;23}2425#[derive(Trace)]26#[trivially_drop]27enum LazyValInternals {28	Computed(Val),29	Errored(LocError),30	Waiting(Box<dyn LazyValValue>),31	Pending,32}3334#[derive(Clone, Trace)]35#[trivially_drop]36pub struct LazyVal(Gc<GcCell<LazyValInternals>>);37impl LazyVal {38	pub fn new(f: Box<dyn LazyValValue>) -> Self {39		Self(Gc::new(GcCell::new(LazyValInternals::Waiting(f))))40	}41	pub fn new_resolved(val: Val) -> Self {42		Self(Gc::new(GcCell::new(LazyValInternals::Computed(val))))43	}44	pub fn evaluate(&self) -> Result<Val> {45		match &*self.0.borrow() {46			LazyValInternals::Computed(v) => return Ok(v.clone()),47			LazyValInternals::Errored(e) => return Err(e.clone()),48			LazyValInternals::Pending => return Err(RecursiveLazyValueEvaluation.into()),49			_ => (),50		};51		let value = if let LazyValInternals::Waiting(value) =52			std::mem::replace(&mut *self.0.borrow_mut(), LazyValInternals::Pending)53		{54			value55		} else {56			unreachable!()57		};58		let new_value = match value.get() {59			Ok(v) => v,60			Err(e) => {61				*self.0.borrow_mut() = LazyValInternals::Errored(e.clone());62				return Err(e);63			}64		};65		*self.0.borrow_mut() = LazyValInternals::Computed(new_value.clone());66		Ok(new_value)67	}68}6970impl Debug for LazyVal {71	fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {72		write!(f, "Lazy")73	}74}75impl PartialEq for LazyVal {76	fn eq(&self, other: &Self) -> bool {77		Gc::ptr_eq(&self.0, &other.0)78	}79}8081#[derive(Debug, PartialEq, Trace)]82#[trivially_drop]83pub struct FuncDesc {84	pub name: IStr,85	pub ctx: Context,86	pub params: ParamsDesc,87	pub body: LocExpr,88}8990#[derive(Debug, Trace)]91#[trivially_drop]92pub enum FuncVal {93	/// Plain function implemented in jsonnet94	Normal(FuncDesc),95	/// Standard library function96	Intrinsic(IStr),97	/// Library functions implemented in native98	NativeExt(IStr, Gc<NativeCallback>),99}100101impl PartialEq for FuncVal {102	fn eq(&self, other: &Self) -> bool {103		match (self, other) {104			(Self::Normal(a), Self::Normal(b)) => a == b,105			(Self::Intrinsic(an), Self::Intrinsic(bn)) => an == bn,106			(Self::NativeExt(an, _), Self::NativeExt(bn, _)) => an == bn,107			(..) => false,108		}109	}110}111impl FuncVal {112	pub fn is_ident(&self) -> bool {113		matches!(&self, Self::Intrinsic(n) if n as &str == "id")114	}115	pub fn name(&self) -> IStr {116		match self {117			Self::Normal(normal) => normal.name.clone(),118			Self::Intrinsic(name) => format!("std.{}", name).into(),119			Self::NativeExt(n, _) => format!("native.{}", n).into(),120		}121	}122	pub fn evaluate(123		&self,124		call_ctx: Context,125		loc: Option<&ExprLocation>,126		args: &ArgsDesc,127		tailstrict: bool,128	) -> Result<Val> {129		match self {130			Self::Normal(func) => {131				let ctx = parse_function_call(132					call_ctx,133					func.ctx.clone(),134					&func.params,135					args,136					tailstrict,137				)?;138				evaluate(ctx, &func.body)139			}140			Self::Intrinsic(name) => call_builtin(call_ctx, loc, name, args),141			Self::NativeExt(_name, handler) => {142				let args =143					parse_function_call(call_ctx, Context::new(), &handler.params, args, true)?;144				let mut out_args = Vec::with_capacity(handler.params.len());145				for p in handler.params.0.iter() {146					out_args.push(args.binding(p.0.clone())?.evaluate()?);147				}148				Ok(handler.call(loc.map(|l| l.0.clone()), &out_args)?)149			}150		}151	}152153	pub fn evaluate_map(154		&self,155		call_ctx: Context,156		args: &HashMap<IStr, Val>,157		tailstrict: bool,158	) -> Result<Val> {159		match self {160			Self::Normal(func) => {161				let ctx = parse_function_call_map(162					call_ctx,163					Some(func.ctx.clone()),164					&func.params,165					args,166					tailstrict,167				)?;168				evaluate(ctx, &func.body)169			}170			Self::Intrinsic(_) => todo!(),171			Self::NativeExt(_, _) => todo!(),172		}173	}174175	pub fn evaluate_values(&self, call_ctx: Context, args: &[Val]) -> Result<Val> {176		match self {177			Self::Normal(func) => {178				let ctx = place_args(call_ctx, Some(func.ctx.clone()), &func.params, args)?;179				evaluate(ctx, &func.body)180			}181			Self::Intrinsic(_) => todo!(),182			Self::NativeExt(_, _) => todo!(),183		}184	}185}186187#[derive(Clone)]188pub enum ManifestFormat {189	YamlStream(Box<ManifestFormat>),190	Yaml(usize),191	Json(usize),192	ToString,193	String,194}195196#[derive(Debug, Clone, Trace)]197#[trivially_drop]198pub enum ArrValue {199	Lazy(Gc<Vec<LazyVal>>),200	Eager(Gc<Vec<Val>>),201	Extended(Box<(Self, Self)>),202}203impl ArrValue {204	pub fn new_eager() -> Self {205		Self::Eager(Gc::new(Vec::new()))206	}207208	pub fn len(&self) -> usize {209		match self {210			Self::Lazy(l) => l.len(),211			Self::Eager(e) => e.len(),212			Self::Extended(v) => v.0.len() + v.1.len(),213		}214	}215216	pub fn is_empty(&self) -> bool {217		self.len() == 0218	}219220	pub fn get(&self, index: usize) -> Result<Option<Val>> {221		match self {222			Self::Lazy(vec) => {223				if let Some(v) = vec.get(index) {224					Ok(Some(v.evaluate()?))225				} else {226					Ok(None)227				}228			}229			Self::Eager(vec) => Ok(vec.get(index).cloned()),230			Self::Extended(v) => {231				let a_len = v.0.len();232				if a_len > index {233					v.0.get(index)234				} else {235					v.1.get(index - a_len)236				}237			}238		}239	}240241	pub fn get_lazy(&self, index: usize) -> Option<LazyVal> {242		match self {243			Self::Lazy(vec) => vec.get(index).cloned(),244			Self::Eager(vec) => vec.get(index).cloned().map(LazyVal::new_resolved),245			Self::Extended(v) => {246				let a_len = v.0.len();247				if a_len > index {248					v.0.get_lazy(index)249				} else {250					v.1.get_lazy(index - a_len)251				}252			}253		}254	}255256	pub fn evaluated(&self) -> Result<Gc<Vec<Val>>> {257		Ok(match self {258			Self::Lazy(vec) => {259				let mut out = Vec::with_capacity(vec.len());260				for item in vec.iter() {261					out.push(item.evaluate()?);262				}263				Gc::new(out)264			}265			Self::Eager(vec) => vec.clone(),266			Self::Extended(_v) => {267				let mut out = Vec::with_capacity(self.len());268				for item in self.iter() {269					out.push(item?);270				}271				Gc::new(out)272			}273		})274	}275276	pub fn iter(&self) -> impl DoubleEndedIterator<Item = Result<Val>> + '_ {277		(0..self.len()).map(move |idx| match self {278			Self::Lazy(l) => l[idx].evaluate(),279			Self::Eager(e) => Ok(e[idx].clone()),280			Self::Extended(_) => self.get(idx).map(|e| e.unwrap()),281		})282	}283284	pub fn iter_lazy(&self) -> impl DoubleEndedIterator<Item = LazyVal> + '_ {285		(0..self.len()).map(move |idx| match self {286			Self::Lazy(l) => l[idx].clone(),287			Self::Eager(e) => LazyVal::new_resolved(e[idx].clone()),288			Self::Extended(_) => self.get_lazy(idx).unwrap(),289		})290	}291292	pub fn reversed(self) -> Self {293		match self {294			Self::Lazy(vec) => {295				let mut out = (&vec as &Vec<_>).clone();296				out.reverse();297				Self::Lazy(Gc::new(out))298			}299			Self::Eager(vec) => {300				let mut out = (&vec as &Vec<_>).clone();301				out.reverse();302				Self::Eager(Gc::new(out))303			}304			Self::Extended(b) => Self::Extended(Box::new((b.1.reversed(), b.0.reversed()))),305		}306	}307308	pub fn map(self, mapper: impl Fn(Val) -> Result<Val>) -> Result<Self> {309		let mut out = Vec::with_capacity(self.len());310311		for value in self.iter() {312			out.push(mapper(value?)?);313		}314315		Ok(Self::Eager(Gc::new(out)))316	}317318	pub fn filter(self, filter: impl Fn(&Val) -> Result<bool>) -> Result<Self> {319		let mut out = Vec::with_capacity(self.len());320321		for value in self.iter() {322			let value = value?;323			if filter(&value)? {324				out.push(value);325			}326		}327328		Ok(Self::Eager(Gc::new(out)))329	}330331	pub fn ptr_eq(a: &Self, b: &Self) -> bool {332		match (a, b) {333			(Self::Lazy(a), Self::Lazy(b)) => Gc::ptr_eq(a, b),334			(Self::Eager(a), Self::Eager(b)) => Gc::ptr_eq(a, b),335			_ => false,336		}337	}338}339340impl From<Vec<LazyVal>> for ArrValue {341	fn from(v: Vec<LazyVal>) -> Self {342		Self::Lazy(Gc::new(v))343	}344}345346impl From<Vec<Val>> for ArrValue {347	fn from(v: Vec<Val>) -> Self {348		Self::Eager(Gc::new(v))349	}350}351352pub enum IndexableVal {353	Str(IStr),354	Arr(ArrValue),355}356357#[derive(Debug, Clone, Trace)]358#[trivially_drop]359pub enum Val {360	Bool(bool),361	Null,362	Str(IStr),363	Num(f64),364	Arr(ArrValue),365	Obj(ObjValue),366	Func(Gc<FuncVal>),367}368369macro_rules! matches_unwrap {370	($e: expr, $p: pat, $r: expr) => {371		match $e {372			$p => $r,373			_ => panic!("no match"),374		}375	};376}377impl Val {378	/// Creates `Val::Num` after checking for numeric overflow.379	/// As numbers are `f64`, we can just check for their finity.380	pub fn new_checked_num(num: f64) -> Result<Self> {381		if num.is_finite() {382			Ok(Self::Num(num))383		} else {384			throw!(RuntimeError("overflow".into()))385		}386	}387388	pub fn assert_type(&self, context: &'static str, val_type: ValType) -> Result<()> {389		let this_type = self.value_type();390		if this_type != val_type {391			throw!(TypeMismatch(context, vec![val_type], this_type))392		} else {393			Ok(())394		}395	}396	pub fn unwrap_num(self) -> Result<f64> {397		Ok(matches_unwrap!(self, Self::Num(v), v))398	}399	pub fn unwrap_str(self) -> Result<IStr> {400		Ok(matches_unwrap!(self, Self::Str(v), v))401	}402	pub fn unwrap_arr(self) -> Result<ArrValue> {403		Ok(matches_unwrap!(self, Self::Arr(v), v))404	}405	pub fn unwrap_func(self) -> Result<Gc<FuncVal>> {406		Ok(matches_unwrap!(self, Self::Func(v), v))407	}408	pub fn try_cast_bool(self, context: &'static str) -> Result<bool> {409		self.assert_type(context, ValType::Bool)?;410		Ok(matches_unwrap!(self, Self::Bool(v), v))411	}412	pub fn try_cast_str(self, context: &'static str) -> Result<IStr> {413		self.assert_type(context, ValType::Str)?;414		Ok(matches_unwrap!(self, Self::Str(v), v))415	}416	pub fn try_cast_num(self, context: &'static str) -> Result<f64> {417		self.assert_type(context, ValType::Num)?;418		self.unwrap_num()419	}420	pub fn try_cast_nullable_num(self, context: &'static str) -> Result<Option<f64>> {421		Ok(match self {422			Val::Null => None,423			Val::Num(num) => Some(num),424			_ => throw!(TypeMismatch(425				context,426				vec![ValType::Null, ValType::Num],427				self.value_type()428			)),429		})430	}431	pub const fn value_type(&self) -> ValType {432		match self {433			Self::Str(..) => ValType::Str,434			Self::Num(..) => ValType::Num,435			Self::Arr(..) => ValType::Arr,436			Self::Obj(..) => ValType::Obj,437			Self::Bool(_) => ValType::Bool,438			Self::Null => ValType::Null,439			Self::Func(..) => ValType::Func,440		}441	}442443	pub fn to_string(&self) -> Result<IStr> {444		Ok(match self {445			Self::Bool(true) => "true".into(),446			Self::Bool(false) => "false".into(),447			Self::Null => "null".into(),448			Self::Str(s) => s.clone(),449			v => manifest_json_ex(450				v,451				&ManifestJsonOptions {452					padding: "",453					mtype: ManifestType::ToString,454				},455			)?456			.into(),457		})458	}459460	/// Expects value to be object, outputs (key, manifested value) pairs461	pub fn manifest_multi(&self, ty: &ManifestFormat) -> Result<Vec<(IStr, IStr)>> {462		let obj = match self {463			Self::Obj(obj) => obj,464			_ => throw!(MultiManifestOutputIsNotAObject),465		};466		let keys = obj.fields();467		let mut out = Vec::with_capacity(keys.len());468		for key in keys {469			let value = obj470				.get(key.clone())?471				.expect("item in object")472				.manifest(ty)?;473			out.push((key, value));474		}475		Ok(out)476	}477478	/// Expects value to be array, outputs manifested values479	pub fn manifest_stream(&self, ty: &ManifestFormat) -> Result<Vec<IStr>> {480		let arr = match self {481			Self::Arr(a) => a,482			_ => throw!(StreamManifestOutputIsNotAArray),483		};484		let mut out = Vec::with_capacity(arr.len());485		for i in arr.iter() {486			out.push(i?.manifest(ty)?);487		}488		Ok(out)489	}490491	pub fn manifest(&self, ty: &ManifestFormat) -> Result<IStr> {492		Ok(match ty {493			ManifestFormat::YamlStream(format) => {494				let arr = match self {495					Self::Arr(a) => a,496					_ => throw!(StreamManifestOutputIsNotAArray),497				};498				let mut out = String::new();499500				match format as &ManifestFormat {501					ManifestFormat::YamlStream(_) => throw!(StreamManifestOutputCannotBeRecursed),502					ManifestFormat::String => throw!(StreamManifestCannotNestString),503					_ => {}504				};505506				if !arr.is_empty() {507					for v in arr.iter() {508						out.push_str("---\n");509						out.push_str(&v?.manifest(format)?);510						out.push('\n');511					}512					out.push_str("...");513				}514515				out.into()516			}517			ManifestFormat::Yaml(padding) => self.to_yaml(*padding)?,518			ManifestFormat::Json(padding) => self.to_json(*padding)?,519			ManifestFormat::ToString => self.to_string()?,520			ManifestFormat::String => match self {521				Self::Str(s) => s.clone(),522				_ => throw!(StringManifestOutputIsNotAString),523			},524		})525	}526527	/// For manifestification528	pub fn to_json(&self, padding: usize) -> Result<IStr> {529		manifest_json_ex(530			self,531			&ManifestJsonOptions {532				padding: &" ".repeat(padding),533				mtype: if padding == 0 {534					ManifestType::Minify535				} else {536					ManifestType::Manifest537				},538			},539		)540		.map(|s| s.into())541	}542543	/// Calls `std.manifestJson`544	pub fn to_std_json(&self, padding: usize) -> Result<Rc<str>> {545		manifest_json_ex(546			self,547			&ManifestJsonOptions {548				padding: &" ".repeat(padding),549				mtype: ManifestType::Std,550			},551		)552		.map(|s| s.into())553	}554555	pub fn to_yaml(&self, padding: usize) -> Result<IStr> {556		let padding = &" ".repeat(padding);557		manifest_yaml_ex(558			self,559			&ManifestYamlOptions {560				padding,561				arr_element_padding: padding,562			},563		)564		.map(|s| s.into())565	}566	pub fn into_indexable(self) -> Result<IndexableVal> {567		Ok(match self {568			Val::Str(s) => IndexableVal::Str(s),569			Val::Arr(arr) => IndexableVal::Arr(arr),570			_ => throw!(ValueIsNotIndexable(self.value_type())),571		})572	}573}574575const fn is_function_like(val: &Val) -> bool {576	matches!(val, Val::Func(_))577}578579/// Native implementation of `std.primitiveEquals`580pub fn primitive_equals(val_a: &Val, val_b: &Val) -> Result<bool> {581	Ok(match (val_a, val_b) {582		(Val::Bool(a), Val::Bool(b)) => a == b,583		(Val::Null, Val::Null) => true,584		(Val::Str(a), Val::Str(b)) => a == b,585		(Val::Num(a), Val::Num(b)) => (a - b).abs() <= f64::EPSILON,586		(Val::Arr(_), Val::Arr(_)) => throw!(RuntimeError(587			"primitiveEquals operates on primitive types, got array".into(),588		)),589		(Val::Obj(_), Val::Obj(_)) => throw!(RuntimeError(590			"primitiveEquals operates on primitive types, got object".into(),591		)),592		(a, b) if is_function_like(a) && is_function_like(b) => {593			throw!(RuntimeError("cannot test equality of functions".into()))594		}595		(_, _) => false,596	})597}598599/// Native implementation of `std.equals`600pub fn equals(val_a: &Val, val_b: &Val) -> Result<bool> {601	if val_a.value_type() != val_b.value_type() {602		return Ok(false);603	}604	match (val_a, val_b) {605		(Val::Arr(a), Val::Arr(b)) => {606			if ArrValue::ptr_eq(a, b) {607				return Ok(true);608			}609			if a.len() != b.len() {610				return Ok(false);611			}612			for (a, b) in a.iter().zip(b.iter()) {613				if !equals(&a?, &b?)? {614					return Ok(false);615				}616			}617			Ok(true)618		}619		(Val::Obj(a), Val::Obj(b)) => {620			if ObjValue::ptr_eq(a, b) {621				return Ok(true);622			}623			let fields = a.fields();624			if fields != b.fields() {625				return Ok(false);626			}627			for field in fields {628				if !equals(&a.get(field.clone())?.unwrap(), &b.get(field)?.unwrap())? {629					return Ok(false);630				}631			}632			Ok(true)633		}634		(a, b) => Ok(primitive_equals(a, b)?),635	}636}