git.delta.rocks / jrsonnet / refs/commits / 4f4be44d138e

difftreelog

source

crates/jrsonnet-evaluator/src/val.rs14.5 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::{9		parse_default_function_call, parse_function_call, ArgsLike, Builtin, CallLocation,10		StaticBuiltin,11	},12	gc::TraceBox,13	throw, Context, ObjValue, Result,14};15use gcmodule::{Cc, Trace};16use jrsonnet_interner::IStr;17use jrsonnet_parser::{LocExpr, ParamsDesc};18use jrsonnet_types::ValType;19use std::{cell::RefCell, fmt::Debug, rc::Rc};2021pub trait LazyValValue: Trace {22	fn get(self: Box<Self>) -> Result<Val>;23}2425#[derive(Trace)]26enum LazyValInternals {27	Computed(Val),28	Errored(LocError),29	Waiting(TraceBox<dyn LazyValValue>),30	Pending,31}3233#[derive(Clone, Trace)]34pub struct LazyVal(Cc<RefCell<LazyValInternals>>);35impl LazyVal {36	pub fn new(f: TraceBox<dyn LazyValValue>) -> Self {37		Self(Cc::new(RefCell::new(LazyValInternals::Waiting(f))))38	}39	pub fn new_resolved(val: Val) -> Self {40		Self(Cc::new(RefCell::new(LazyValInternals::Computed(val))))41	}42	pub fn force(&self) -> Result<()> {43		self.evaluate()?;44		Ok(())45	}46	pub fn evaluate(&self) -> Result<Val> {47		match &*self.0.borrow() {48			LazyValInternals::Computed(v) => return Ok(v.clone()),49			LazyValInternals::Errored(e) => return Err(e.clone()),50			LazyValInternals::Pending => return Err(RecursiveLazyValueEvaluation.into()),51			_ => (),52		};53		let value = if let LazyValInternals::Waiting(value) =54			std::mem::replace(&mut *self.0.borrow_mut(), LazyValInternals::Pending)55		{56			value57		} else {58			unreachable!()59		};60		let new_value = match value.0.get() {61			Ok(v) => v,62			Err(e) => {63				*self.0.borrow_mut() = LazyValInternals::Errored(e.clone());64				return Err(e);65			}66		};67		*self.0.borrow_mut() = LazyValInternals::Computed(new_value.clone());68		Ok(new_value)69	}70}7172impl Debug for LazyVal {73	fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {74		write!(f, "Lazy")75	}76}77impl PartialEq for LazyVal {78	fn eq(&self, other: &Self) -> bool {79		cc_ptr_eq(&self.0, &other.0)80	}81}8283#[derive(Debug, PartialEq, Trace)]84pub struct FuncDesc {85	pub name: IStr,86	pub ctx: Context,87	pub params: ParamsDesc,88	pub body: LocExpr,89}90impl FuncDesc {91	/// Create body context, but fill arguments without defaults with lazy error92	pub fn default_body_context(&self) -> Context {93		parse_default_function_call(self.ctx.clone(), &self.params)94	}9596	/// Create context, with which body code will run97	pub fn call_body_context(98		&self,99		call_ctx: Context,100		args: &dyn ArgsLike,101		tailstrict: bool,102	) -> Result<Context> {103		parse_function_call(call_ctx, self.ctx.clone(), &self.params, args, tailstrict)104	}105}106107#[derive(Trace, Clone)]108pub enum FuncVal {109	/// Plain function implemented in jsonnet110	Normal(Cc<FuncDesc>),111	/// Standard library function112	StaticBuiltin(#[skip_trace] &'static dyn StaticBuiltin),113	/// User-provided function114	Builtin(Cc<TraceBox<dyn Builtin>>),115}116117impl Debug for FuncVal {118	fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {119		match self {120			Self::Normal(arg0) => f.debug_tuple("Normal").field(arg0).finish(),121			Self::StaticBuiltin(arg0) => {122				f.debug_tuple("StaticBuiltin").field(&arg0.name()).finish()123			}124			Self::Builtin(arg0) => f.debug_tuple("Builtin").field(&arg0.name()).finish(),125		}126	}127}128129impl FuncVal {130	pub fn args_len(&self) -> usize {131		match self {132			Self::Normal(n) => n.params.iter().filter(|p| p.1.is_none()).count(),133			Self::StaticBuiltin(i) => i.params().iter().filter(|p| !p.has_default).count(),134			Self::Builtin(i) => i.params().iter().filter(|p| !p.has_default).count(),135		}136	}137	pub fn name(&self) -> IStr {138		match self {139			Self::Normal(normal) => normal.name.clone(),140			Self::StaticBuiltin(builtin) => builtin.name().into(),141			Self::Builtin(builtin) => builtin.name().into(),142		}143	}144	pub fn evaluate(145		&self,146		call_ctx: Context,147		loc: CallLocation,148		args: &dyn ArgsLike,149		tailstrict: bool,150	) -> Result<Val> {151		match self {152			Self::Normal(func) => {153				let body_ctx = func.call_body_context(call_ctx, args, tailstrict)?;154				evaluate(body_ctx, &func.body)155			}156			Self::StaticBuiltin(b) => b.call(call_ctx, loc, args),157			Self::Builtin(b) => b.call(call_ctx, loc, args),158		}159	}160	pub fn evaluate_simple(&self, args: &dyn ArgsLike) -> Result<Val> {161		self.evaluate(Context::default(), CallLocation::native(), args, true)162	}163}164165#[derive(Clone)]166pub enum ManifestFormat {167	YamlStream(Box<ManifestFormat>),168	Yaml(usize),169	Json(usize),170	ToString,171	String,172}173174#[derive(Debug, Clone, Trace)]175#[force_tracking]176pub enum ArrValue {177	Lazy(Cc<Vec<LazyVal>>),178	Eager(Cc<Vec<Val>>),179	Extended(Box<(Self, Self)>),180}181impl ArrValue {182	pub fn new_eager() -> Self {183		Self::Eager(Cc::new(Vec::new()))184	}185186	pub fn len(&self) -> usize {187		match self {188			Self::Lazy(l) => l.len(),189			Self::Eager(e) => e.len(),190			Self::Extended(v) => v.0.len() + v.1.len(),191		}192	}193194	pub fn is_empty(&self) -> bool {195		self.len() == 0196	}197198	pub fn get(&self, index: usize) -> Result<Option<Val>> {199		match self {200			Self::Lazy(vec) => {201				if let Some(v) = vec.get(index) {202					Ok(Some(v.evaluate()?))203				} else {204					Ok(None)205				}206			}207			Self::Eager(vec) => Ok(vec.get(index).cloned()),208			Self::Extended(v) => {209				let a_len = v.0.len();210				if a_len > index {211					v.0.get(index)212				} else {213					v.1.get(index - a_len)214				}215			}216		}217	}218219	pub fn get_lazy(&self, index: usize) -> Option<LazyVal> {220		match self {221			Self::Lazy(vec) => vec.get(index).cloned(),222			Self::Eager(vec) => vec.get(index).cloned().map(LazyVal::new_resolved),223			Self::Extended(v) => {224				let a_len = v.0.len();225				if a_len > index {226					v.0.get_lazy(index)227				} else {228					v.1.get_lazy(index - a_len)229				}230			}231		}232	}233234	pub fn evaluated(&self) -> Result<Cc<Vec<Val>>> {235		Ok(match self {236			Self::Lazy(vec) => {237				let mut out = Vec::with_capacity(vec.len());238				for item in vec.iter() {239					out.push(item.evaluate()?);240				}241				Cc::new(out)242			}243			Self::Eager(vec) => vec.clone(),244			Self::Extended(_v) => {245				let mut out = Vec::with_capacity(self.len());246				for item in self.iter() {247					out.push(item?);248				}249				Cc::new(out)250			}251		})252	}253254	pub fn iter(&self) -> impl DoubleEndedIterator<Item = Result<Val>> + '_ {255		(0..self.len()).map(move |idx| match self {256			Self::Lazy(l) => l[idx].evaluate(),257			Self::Eager(e) => Ok(e[idx].clone()),258			Self::Extended(_) => self.get(idx).map(|e| e.unwrap()),259		})260	}261262	pub fn iter_lazy(&self) -> impl DoubleEndedIterator<Item = LazyVal> + '_ {263		(0..self.len()).map(move |idx| match self {264			Self::Lazy(l) => l[idx].clone(),265			Self::Eager(e) => LazyVal::new_resolved(e[idx].clone()),266			Self::Extended(_) => self.get_lazy(idx).unwrap(),267		})268	}269270	pub fn reversed(self) -> Self {271		match self {272			Self::Lazy(vec) => {273				let mut out = (&vec as &Vec<_>).clone();274				out.reverse();275				Self::Lazy(Cc::new(out))276			}277			Self::Eager(vec) => {278				let mut out = (&vec as &Vec<_>).clone();279				out.reverse();280				Self::Eager(Cc::new(out))281			}282			Self::Extended(b) => Self::Extended(Box::new((b.1.reversed(), b.0.reversed()))),283		}284	}285286	pub fn map(self, mapper: impl Fn(Val) -> Result<Val>) -> Result<Self> {287		let mut out = Vec::with_capacity(self.len());288289		for value in self.iter() {290			out.push(mapper(value?)?);291		}292293		Ok(Self::Eager(Cc::new(out)))294	}295296	pub fn filter(self, filter: impl Fn(&Val) -> Result<bool>) -> Result<Self> {297		let mut out = Vec::with_capacity(self.len());298299		for value in self.iter() {300			let value = value?;301			if filter(&value)? {302				out.push(value);303			}304		}305306		Ok(Self::Eager(Cc::new(out)))307	}308309	pub fn ptr_eq(a: &Self, b: &Self) -> bool {310		match (a, b) {311			(Self::Lazy(a), Self::Lazy(b)) => cc_ptr_eq(a, b),312			(Self::Eager(a), Self::Eager(b)) => cc_ptr_eq(a, b),313			_ => false,314		}315	}316}317318impl From<Vec<LazyVal>> for ArrValue {319	fn from(v: Vec<LazyVal>) -> Self {320		Self::Lazy(Cc::new(v))321	}322}323324impl From<Vec<Val>> for ArrValue {325	fn from(v: Vec<Val>) -> Self {326		Self::Eager(Cc::new(v))327	}328}329330pub enum IndexableVal {331	Str(IStr),332	Arr(ArrValue),333}334335#[derive(Debug, Clone, Trace)]336pub enum Val {337	Bool(bool),338	Null,339	Str(IStr),340	Num(f64),341	Arr(ArrValue),342	Obj(ObjValue),343	Func(FuncVal),344}345346impl Val {347	pub const fn as_bool(&self) -> Option<bool> {348		match self {349			Val::Bool(v) => Some(*v),350			_ => None,351		}352	}353	pub const fn as_null(&self) -> Option<()> {354		match self {355			Val::Null => Some(()),356			_ => None,357		}358	}359	pub fn as_str(&self) -> Option<IStr> {360		match self {361			Val::Str(s) => Some(s.clone()),362			_ => None,363		}364	}365	pub const fn as_num(&self) -> Option<f64> {366		match self {367			Val::Num(n) => Some(*n),368			_ => None,369		}370	}371	pub fn as_arr(&self) -> Option<ArrValue> {372		match self {373			Val::Arr(a) => Some(a.clone()),374			_ => None,375		}376	}377	pub fn as_obj(&self) -> Option<ObjValue> {378		match self {379			Val::Obj(o) => Some(o.clone()),380			_ => None,381		}382	}383	pub fn as_func(&self) -> Option<FuncVal> {384		match self {385			Val::Func(f) => Some(f.clone()),386			_ => None,387		}388	}389390	/// Creates `Val::Num` after checking for numeric overflow.391	/// As numbers are `f64`, we can just check for their finity.392	pub fn new_checked_num(num: f64) -> Result<Self> {393		if num.is_finite() {394			Ok(Self::Num(num))395		} else {396			throw!(RuntimeError("overflow".into()))397		}398	}399400	pub fn try_cast_nullable_num(self, context: &'static str) -> Result<Option<f64>> {401		Ok(match self {402			Val::Null => None,403			Val::Num(num) => Some(num),404			_ => throw!(TypeMismatch(405				context,406				vec![ValType::Null, ValType::Num],407				self.value_type()408			)),409		})410	}411	pub const fn value_type(&self) -> ValType {412		match self {413			Self::Str(..) => ValType::Str,414			Self::Num(..) => ValType::Num,415			Self::Arr(..) => ValType::Arr,416			Self::Obj(..) => ValType::Obj,417			Self::Bool(_) => ValType::Bool,418			Self::Null => ValType::Null,419			Self::Func(..) => ValType::Func,420		}421	}422423	pub fn to_string(&self) -> Result<IStr> {424		Ok(match self {425			Self::Bool(true) => "true".into(),426			Self::Bool(false) => "false".into(),427			Self::Null => "null".into(),428			Self::Str(s) => s.clone(),429			v => manifest_json_ex(430				v,431				&ManifestJsonOptions {432					padding: "",433					mtype: ManifestType::ToString,434					newline: "\n",435					key_val_sep: ": ",436				},437			)?438			.into(),439		})440	}441442	/// Expects value to be object, outputs (key, manifested value) pairs443	pub fn manifest_multi(&self, ty: &ManifestFormat) -> Result<Vec<(IStr, IStr)>> {444		let obj = match self {445			Self::Obj(obj) => obj,446			_ => throw!(MultiManifestOutputIsNotAObject),447		};448		let keys = obj.fields();449		let mut out = Vec::with_capacity(keys.len());450		for key in keys {451			let value = obj452				.get(key.clone())?453				.expect("item in object")454				.manifest(ty)?;455			out.push((key, value));456		}457		Ok(out)458	}459460	/// Expects value to be array, outputs manifested values461	pub fn manifest_stream(&self, ty: &ManifestFormat) -> Result<Vec<IStr>> {462		let arr = match self {463			Self::Arr(a) => a,464			_ => throw!(StreamManifestOutputIsNotAArray),465		};466		let mut out = Vec::with_capacity(arr.len());467		for i in arr.iter() {468			out.push(i?.manifest(ty)?);469		}470		Ok(out)471	}472473	pub fn manifest(&self, ty: &ManifestFormat) -> Result<IStr> {474		Ok(match ty {475			ManifestFormat::YamlStream(format) => {476				let arr = match self {477					Self::Arr(a) => a,478					_ => throw!(StreamManifestOutputIsNotAArray),479				};480				let mut out = String::new();481482				match format as &ManifestFormat {483					ManifestFormat::YamlStream(_) => throw!(StreamManifestOutputCannotBeRecursed),484					ManifestFormat::String => throw!(StreamManifestCannotNestString),485					_ => {}486				};487488				if !arr.is_empty() {489					for v in arr.iter() {490						out.push_str("---\n");491						out.push_str(&v?.manifest(format)?);492						out.push('\n');493					}494					out.push_str("...");495				}496497				out.into()498			}499			ManifestFormat::Yaml(padding) => self.to_yaml(*padding)?,500			ManifestFormat::Json(padding) => self.to_json(*padding)?,501			ManifestFormat::ToString => self.to_string()?,502			ManifestFormat::String => match self {503				Self::Str(s) => s.clone(),504				_ => throw!(StringManifestOutputIsNotAString),505			},506		})507	}508509	/// For manifestification510	pub fn to_json(&self, padding: usize) -> Result<IStr> {511		manifest_json_ex(512			self,513			&ManifestJsonOptions {514				padding: &" ".repeat(padding),515				mtype: if padding == 0 {516					ManifestType::Minify517				} else {518					ManifestType::Manifest519				},520				newline: "\n",521				key_val_sep: ": ",522			},523		)524		.map(|s| s.into())525	}526527	/// Calls `std.manifestJson`528	pub fn to_std_json(&self, padding: usize) -> Result<Rc<str>> {529		manifest_json_ex(530			self,531			&ManifestJsonOptions {532				padding: &" ".repeat(padding),533				mtype: ManifestType::Std,534				newline: "\n",535				key_val_sep: ": ",536			},537		)538		.map(|s| s.into())539	}540541	pub fn to_yaml(&self, padding: usize) -> Result<IStr> {542		let padding = &" ".repeat(padding);543		manifest_yaml_ex(544			self,545			&ManifestYamlOptions {546				padding,547				arr_element_padding: padding,548				quote_keys: false,549			},550		)551		.map(|s| s.into())552	}553	pub fn into_indexable(self) -> Result<IndexableVal> {554		Ok(match self {555			Val::Str(s) => IndexableVal::Str(s),556			Val::Arr(arr) => IndexableVal::Arr(arr),557			_ => throw!(ValueIsNotIndexable(self.value_type())),558		})559	}560}561562const fn is_function_like(val: &Val) -> bool {563	matches!(val, Val::Func(_))564}565566/// Native implementation of `std.primitiveEquals`567pub fn primitive_equals(val_a: &Val, val_b: &Val) -> Result<bool> {568	Ok(match (val_a, val_b) {569		(Val::Bool(a), Val::Bool(b)) => a == b,570		(Val::Null, Val::Null) => true,571		(Val::Str(a), Val::Str(b)) => a == b,572		(Val::Num(a), Val::Num(b)) => (a - b).abs() <= f64::EPSILON,573		(Val::Arr(_), Val::Arr(_)) => throw!(RuntimeError(574			"primitiveEquals operates on primitive types, got array".into(),575		)),576		(Val::Obj(_), Val::Obj(_)) => throw!(RuntimeError(577			"primitiveEquals operates on primitive types, got object".into(),578		)),579		(a, b) if is_function_like(a) && is_function_like(b) => {580			throw!(RuntimeError("cannot test equality of functions".into()))581		}582		(_, _) => false,583	})584}585586/// Native implementation of `std.equals`587pub fn equals(val_a: &Val, val_b: &Val) -> Result<bool> {588	if val_a.value_type() != val_b.value_type() {589		return Ok(false);590	}591	match (val_a, val_b) {592		(Val::Arr(a), Val::Arr(b)) => {593			if ArrValue::ptr_eq(a, b) {594				return Ok(true);595			}596			if a.len() != b.len() {597				return Ok(false);598			}599			for (a, b) in a.iter().zip(b.iter()) {600				if !equals(&a?, &b?)? {601					return Ok(false);602				}603			}604			Ok(true)605		}606		(Val::Obj(a), Val::Obj(b)) => {607			if ObjValue::ptr_eq(a, b) {608				return Ok(true);609			}610			let fields = a.fields();611			if fields != b.fields() {612				return Ok(false);613			}614			for field in fields {615				if !equals(&a.get(field.clone())?.unwrap(), &b.get(field)?.unwrap())? {616					return Ok(false);617				}618			}619			Ok(true)620		}621		(a, b) => Ok(primitive_equals(a, b)?),622	}623}