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
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}