git.delta.rocks / jrsonnet / refs/commits / 3d527a7bcaaf

difftreelog

perf use pointer equality in std.equals

Yaroslav Bolyukin2021-01-12parent: #c214d99.patch.diff
in: master

2 files changed

modifiedcrates/jrsonnet-evaluator/src/obj.rsdiffbeforeafterboth
--- a/crates/jrsonnet-evaluator/src/obj.rs
+++ b/crates/jrsonnet-evaluator/src/obj.rs
@@ -139,6 +139,10 @@
 			.evaluate(Some(real_this.clone()), self.0.super_obj.clone())?
 			.evaluate()?)
 	}
+
+	pub fn ptr_eq(a: &ObjValue, b: &ObjValue) -> bool {
+		Rc::ptr_eq(&a.0, &b.0)
+	}
 }
 impl PartialEq for ObjValue {
 	fn eq(&self, other: &Self) -> bool {
modifiedcrates/jrsonnet-evaluator/src/val.rsdiffbeforeafterboth
before · crates/jrsonnet-evaluator/src/val.rs
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_interner::IStr;13use jrsonnet_parser::{el, Arg, ArgsDesc, Expr, ExprLocation, LiteralType, LocExpr, ParamsDesc};14use jrsonnet_types::ValType;15use std::{cell::RefCell, collections::HashMap, fmt::Debug, rc::Rc};1617enum LazyValInternals {18	Computed(Val),19	Waiting(Box<dyn Fn() -> Result<Val>>),20}21#[derive(Clone)]22pub struct LazyVal(Rc<RefCell<LazyValInternals>>);23impl LazyVal {24	pub fn new(f: Box<dyn Fn() -> Result<Val>>) -> Self {25		Self(Rc::new(RefCell::new(LazyValInternals::Waiting(f))))26	}27	pub fn new_resolved(val: Val) -> Self {28		Self(Rc::new(RefCell::new(LazyValInternals::Computed(val))))29	}30	pub fn evaluate(&self) -> Result<Val> {31		let new_value = match &*self.0.borrow() {32			LazyValInternals::Computed(v) => return Ok(v.clone()),33			LazyValInternals::Waiting(f) => f()?,34		};35		*self.0.borrow_mut() = LazyValInternals::Computed(new_value.clone());36		Ok(new_value)37	}38}3940#[macro_export]41macro_rules! lazy_val {42	($f: expr) => {43		$crate::LazyVal::new(Box::new($f))44	};45}46#[macro_export]47macro_rules! resolved_lazy_val {48	($f: expr) => {49		$crate::LazyVal::new_resolved($f)50	};51}52impl Debug for LazyVal {53	fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {54		write!(f, "Lazy")55	}56}57impl PartialEq for LazyVal {58	fn eq(&self, other: &Self) -> bool {59		Rc::ptr_eq(&self.0, &other.0)60	}61}6263#[derive(Debug, PartialEq)]64pub struct FuncDesc {65	pub name: IStr,66	pub ctx: Context,67	pub params: ParamsDesc,68	pub body: LocExpr,69}7071#[derive(Debug)]72pub enum FuncVal {73	/// Plain function implemented in jsonnet74	Normal(FuncDesc),75	/// Standard library function76	Intrinsic(IStr),77	/// Library functions implemented in native78	NativeExt(IStr, Rc<NativeCallback>),79}8081impl PartialEq for FuncVal {82	fn eq(&self, other: &Self) -> bool {83		match (self, other) {84			(Self::Normal(a), Self::Normal(b)) => a == b,85			(Self::Intrinsic(an), Self::Intrinsic(bn)) => an == bn,86			(Self::NativeExt(an, _), Self::NativeExt(bn, _)) => an == bn,87			(..) => false,88		}89	}90}91impl FuncVal {92	pub fn is_ident(&self) -> bool {93		matches!(&self, Self::Intrinsic(n) if n as &str == "id")94	}95	pub fn name(&self) -> IStr {96		match self {97			Self::Normal(normal) => normal.name.clone(),98			Self::Intrinsic(name) => format!("std.{}", name).into(),99			Self::NativeExt(n, _) => format!("native.{}", n).into(),100		}101	}102	pub fn evaluate(103		&self,104		call_ctx: Context,105		loc: &Option<ExprLocation>,106		args: &ArgsDesc,107		tailstrict: bool,108	) -> Result<Val> {109		match self {110			Self::Normal(func) => {111				let ctx = parse_function_call(112					call_ctx,113					Some(func.ctx.clone()),114					&func.params,115					args,116					tailstrict,117				)?;118				evaluate(ctx, &func.body)119			}120			Self::Intrinsic(name) => call_builtin(call_ctx, loc, name, args),121			Self::NativeExt(_name, handler) => {122				let args = parse_function_call(call_ctx, None, &handler.params, args, true)?;123				let mut out_args = Vec::with_capacity(handler.params.len());124				for p in handler.params.0.iter() {125					out_args.push(args.binding(p.0.clone())?.evaluate()?);126				}127				Ok(handler.call(&out_args)?)128			}129		}130	}131132	pub fn evaluate_map(133		&self,134		call_ctx: Context,135		args: &HashMap<IStr, Val>,136		tailstrict: bool,137	) -> Result<Val> {138		match self {139			Self::Normal(func) => {140				let ctx = parse_function_call_map(141					call_ctx,142					Some(func.ctx.clone()),143					&func.params,144					args,145					tailstrict,146				)?;147				evaluate(ctx, &func.body)148			}149			Self::Intrinsic(_) => todo!(),150			Self::NativeExt(_, _) => todo!(),151		}152	}153154	pub fn evaluate_values(&self, call_ctx: Context, args: &[Val]) -> Result<Val> {155		match self {156			Self::Normal(func) => {157				let ctx = place_args(call_ctx, Some(func.ctx.clone()), &func.params, args)?;158				evaluate(ctx, &func.body)159			}160			Self::Intrinsic(_) => todo!(),161			Self::NativeExt(_, _) => todo!(),162		}163	}164}165166#[derive(Clone)]167pub enum ManifestFormat {168	YamlStream(Box<ManifestFormat>),169	Yaml(usize),170	Json(usize),171	ToString,172	String,173}174175#[derive(Debug, Clone)]176pub enum ArrValue {177	Lazy(Rc<Vec<LazyVal>>),178	Eager(Rc<Vec<Val>>),179}180impl ArrValue {181	pub fn len(&self) -> usize {182		match self {183			ArrValue::Lazy(l) => l.len(),184			ArrValue::Eager(e) => e.len(),185		}186	}187188	pub fn is_empty(&self) -> bool {189		self.len() == 0190	}191192	pub fn get(&self, index: usize) -> Result<Option<Val>> {193		match self {194			ArrValue::Lazy(vec) => {195				if let Some(v) = vec.get(index) {196					Ok(Some(v.evaluate()?))197				} else {198					Ok(None)199				}200			}201			ArrValue::Eager(vec) => Ok(vec.get(index).cloned()),202		}203	}204205	pub fn get_lazy(&self, index: usize) -> Option<LazyVal> {206		match self {207			ArrValue::Lazy(vec) => vec.get(index).cloned(),208			ArrValue::Eager(vec) => vec209				.get(index)210				.cloned()211				.map(|val| LazyVal::new_resolved(val)),212		}213	}214215	pub fn evaluated(&self) -> Result<Rc<Vec<Val>>> {216		Ok(match self {217			ArrValue::Lazy(vec) => {218				let mut out = Vec::with_capacity(vec.len());219				for item in vec.iter() {220					out.push(item.evaluate()?);221				}222				Rc::new(out)223			}224			ArrValue::Eager(vec) => vec.clone(),225		})226	}227228	pub fn iter(&self) -> impl DoubleEndedIterator<Item = Result<Val>> + '_ {229		(0..self.len()).map(move |idx| match self {230			ArrValue::Lazy(l) => l[idx].evaluate(),231			ArrValue::Eager(e) => Ok(e[idx].clone()),232		})233	}234235	pub fn iter_lazy(&self) -> impl DoubleEndedIterator<Item = LazyVal> + '_ {236		(0..self.len()).map(move |idx| match self {237			ArrValue::Lazy(l) => l[idx].clone(),238			ArrValue::Eager(e) => LazyVal::new_resolved(e[idx].clone()),239		})240	}241242	pub fn reversed(self) -> Self {243		match self {244			ArrValue::Lazy(vec) => {245				let mut out = (&vec as &Vec<_>).clone();246				out.reverse();247				Self::Lazy(Rc::new(out))248			}249			ArrValue::Eager(vec) => {250				let mut out = (&vec as &Vec<_>).clone();251				out.reverse();252				Self::Eager(Rc::new(out))253			}254		}255	}256}257258impl From<Vec<LazyVal>> for ArrValue {259	fn from(v: Vec<LazyVal>) -> Self {260		Self::Lazy(Rc::new(v))261	}262}263264impl From<Vec<Val>> for ArrValue {265	fn from(v: Vec<Val>) -> Self {266		Self::Eager(Rc::new(v))267	}268}269270#[derive(Debug, Clone)]271pub enum Val {272	Bool(bool),273	Null,274	Str(IStr),275	Num(f64),276	Arr(ArrValue),277	Obj(ObjValue),278	Func(Rc<FuncVal>),279}280281macro_rules! matches_unwrap {282	($e: expr, $p: pat, $r: expr) => {283		match $e {284			$p => $r,285			_ => panic!("no match"),286			}287	};288}289impl Val {290	/// Creates `Val::Num` after checking for numeric overflow.291	/// As numbers are `f64`, we can just check for their finity.292	pub fn new_checked_num(num: f64) -> Result<Self> {293		if num.is_finite() {294			Ok(Self::Num(num))295		} else {296			throw!(RuntimeError("overflow".into()))297		}298	}299300	pub fn assert_type(&self, context: &'static str, val_type: ValType) -> Result<()> {301		let this_type = self.value_type();302		if this_type != val_type {303			throw!(TypeMismatch(context, vec![val_type], this_type))304		} else {305			Ok(())306		}307	}308	pub fn unwrap_num(self) -> Result<f64> {309		Ok(matches_unwrap!(self, Self::Num(v), v))310	}311	pub fn unwrap_func(self) -> Result<Rc<FuncVal>> {312		Ok(matches_unwrap!(self, Self::Func(v), v))313	}314	pub fn try_cast_bool(self, context: &'static str) -> Result<bool> {315		self.assert_type(context, ValType::Bool)?;316		Ok(matches_unwrap!(self, Self::Bool(v), v))317	}318	pub fn try_cast_str(self, context: &'static str) -> Result<IStr> {319		self.assert_type(context, ValType::Str)?;320		Ok(matches_unwrap!(self, Self::Str(v), v))321	}322	pub fn try_cast_num(self, context: &'static str) -> Result<f64> {323		self.assert_type(context, ValType::Num)?;324		self.unwrap_num()325	}326	pub fn value_type(&self) -> ValType {327		match self {328			Self::Str(..) => ValType::Str,329			Self::Num(..) => ValType::Num,330			Self::Arr(..) => ValType::Arr,331			Self::Obj(..) => ValType::Obj,332			Self::Bool(_) => ValType::Bool,333			Self::Null => ValType::Null,334			Self::Func(..) => ValType::Func,335		}336	}337338	pub fn to_string(&self) -> Result<IStr> {339		Ok(match self {340			Self::Bool(true) => "true".into(),341			Self::Bool(false) => "false".into(),342			Self::Null => "null".into(),343			Self::Str(s) => s.clone(),344			v => manifest_json_ex(345				&v,346				&ManifestJsonOptions {347					padding: "",348					mtype: ManifestType::ToString,349				},350			)?351			.into(),352		})353	}354355	/// Expects value to be object, outputs (key, manifested value) pairs356	pub fn manifest_multi(&self, ty: &ManifestFormat) -> Result<Vec<(IStr, IStr)>> {357		let obj = match self {358			Self::Obj(obj) => obj,359			_ => throw!(MultiManifestOutputIsNotAObject),360		};361		let keys = obj.visible_fields();362		let mut out = Vec::with_capacity(keys.len());363		for key in keys {364			let value = obj365				.get(key.clone())?366				.expect("item in object")367				.manifest(ty)?;368			out.push((key, value));369		}370		Ok(out)371	}372373	/// Expects value to be array, outputs manifested values374	pub fn manifest_stream(&self, ty: &ManifestFormat) -> Result<Vec<IStr>> {375		let arr = match self {376			Self::Arr(a) => a,377			_ => throw!(StreamManifestOutputIsNotAArray),378		};379		let mut out = Vec::with_capacity(arr.len());380		for i in arr.iter() {381			out.push(i?.manifest(ty)?);382		}383		Ok(out)384	}385386	pub fn manifest(&self, ty: &ManifestFormat) -> Result<IStr> {387		Ok(match ty {388			ManifestFormat::YamlStream(format) => {389				let arr = match self {390					Self::Arr(a) => a,391					_ => throw!(StreamManifestOutputIsNotAArray),392				};393				let mut out = String::new();394395				match format as &ManifestFormat {396					ManifestFormat::YamlStream(_) => throw!(StreamManifestOutputCannotBeRecursed),397					ManifestFormat::String => throw!(StreamManifestCannotNestString),398					_ => {}399				};400401				if !arr.is_empty() {402					for v in arr.iter() {403						out.push_str("---\n");404						out.push_str(&v?.manifest(format)?);405						out.push('\n');406					}407					out.push_str("...");408				}409410				out.into()411			}412			ManifestFormat::Yaml(padding) => self.to_yaml(*padding)?,413			ManifestFormat::Json(padding) => self.to_json(*padding)?,414			ManifestFormat::ToString => self.to_string()?,415			ManifestFormat::String => match self {416				Self::Str(s) => s.clone(),417				_ => throw!(StringManifestOutputIsNotAString),418			},419		})420	}421422	/// For manifestification423	pub fn to_json(&self, padding: usize) -> Result<IStr> {424		manifest_json_ex(425			self,426			&ManifestJsonOptions {427				padding: &" ".repeat(padding),428				mtype: if padding == 0 {429					ManifestType::Minify430				} else {431					ManifestType::Manifest432				},433			},434		)435		.map(|s| s.into())436	}437438	/// Calls `std.manifestJson`439	#[cfg(feature = "faster")]440	pub fn to_std_json(&self, padding: usize) -> Result<Rc<str>> {441		manifest_json_ex(442			self,443			&ManifestJsonOptions {444				padding: &" ".repeat(padding),445				mtype: ManifestType::Std,446			},447		)448		.map(|s| s.into())449	}450451	/// Calls `std.manifestJson`452	#[cfg(not(feature = "faster"))]453	pub fn to_std_json(&self, padding: usize) -> Result<Rc<str>> {454		with_state(|s| {455			let ctx = s456				.create_default_context()?457				.with_var("__tmp__to_json__".into(), self.clone())?;458			Ok(evaluate(459				ctx,460				&el!(Expr::Apply(461					el!(Expr::Index(462						el!(Expr::Var("std".into())),463						el!(Expr::Str("manifestJsonEx".into()))464					)),465					ArgsDesc(vec![466						Arg(None, el!(Expr::Var("__tmp__to_json__".into()))),467						Arg(None, el!(Expr::Str(" ".repeat(padding).into())))468					]),469					false470				)),471			)?472			.try_cast_str("to json")?)473		})474	}475	pub fn to_yaml(&self, padding: usize) -> Result<IStr> {476		with_state(|s| {477			let ctx = s478				.create_default_context()?479				.with_var("__tmp__to_json__".into(), self.clone());480			Ok(evaluate(481				ctx,482				&el!(Expr::Apply(483					el!(Expr::Index(484						el!(Expr::Var("std".into())),485						el!(Expr::Str("manifestYamlDoc".into()))486					)),487					ArgsDesc(vec![488						Arg(None, el!(Expr::Var("__tmp__to_json__".into()))),489						Arg(490							None,491							el!(Expr::Literal(if padding != 0 {492								LiteralType::True493							} else {494								LiteralType::False495							}))496						)497					]),498					false499				)),500			)?501			.try_cast_str("to json")?)502		})503	}504}505506const fn is_function_like(val: &Val) -> bool {507	matches!(val, Val::Func(_))508}509510/// Native implementation of `std.primitiveEquals`511pub fn primitive_equals(val_a: &Val, val_b: &Val) -> Result<bool> {512	Ok(match (val_a, val_b) {513		(Val::Bool(a), Val::Bool(b)) => a == b,514		(Val::Null, Val::Null) => true,515		(Val::Str(a), Val::Str(b)) => a == b,516		(Val::Num(a), Val::Num(b)) => (a - b).abs() <= f64::EPSILON,517		(Val::Arr(_), Val::Arr(_)) => throw!(RuntimeError(518			"primitiveEquals operates on primitive types, got array".into(),519		)),520		(Val::Obj(_), Val::Obj(_)) => throw!(RuntimeError(521			"primitiveEquals operates on primitive types, got object".into(),522		)),523		(a, b) if is_function_like(&a) && is_function_like(&b) => {524			throw!(RuntimeError("cannot test equality of functions".into()))525		}526		(_, _) => false,527	})528}529530/// Native implementation of `std.equals`531pub fn equals(val_a: &Val, val_b: &Val) -> Result<bool> {532	if val_a.value_type() != val_b.value_type() {533		return Ok(false);534	}535	match (val_a, val_b) {536		// Cant test for ptr equality, because all fields needs to be evaluated537		(Val::Arr(a), Val::Arr(b)) => {538			if a.len() != b.len() {539				return Ok(false);540			}541			for (a, b) in a.iter().zip(b.iter()) {542				if !equals(&a?, &b?)? {543					return Ok(false);544				}545			}546			Ok(true)547		}548		(Val::Obj(a), Val::Obj(b)) => {549			let fields = a.visible_fields();550			if fields != b.visible_fields() {551				return Ok(false);552			}553			for field in fields {554				if !equals(&a.get(field.clone())?.unwrap(), &b.get(field)?.unwrap())? {555					return Ok(false);556				}557			}558			Ok(true)559		}560		(a, b) => Ok(primitive_equals(&a, &b)?),561	}562}