git.delta.rocks / jrsonnet / refs/commits / eff1bc234bfb

difftreelog

perf(evaluator) remove unnecessary cloning

Лач2020-06-25parent: #ce9e7d9.patch.diff
in: master

4 files changed

modifiedcrates/jsonnet-evaluator/src/evaluate.rsdiffbeforeafterboth
--- a/crates/jsonnet-evaluator/src/evaluate.rs
+++ b/crates/jsonnet-evaluator/src/evaluate.rs
@@ -211,9 +211,9 @@
 			let future_this = FutureObjValue::new();
 			let context_creator = context_creator!(
 				closure!(clone context, clone new_bindings, |this: Option<ObjValue>, super_obj: Option<ObjValue>| {
-					Ok(context.clone().extend_unbound(
+					Ok(context.extend_unbound(
 						new_bindings.clone().unwrap(),
-						context.clone().dollar().clone().or_else(||this.clone()),
+						context.dollar().clone().or_else(||this.clone()),
 						Some(this.unwrap()),
 						super_obj
 					)?)
@@ -318,9 +318,9 @@
 					let new_bindings = FutureNewBindings::new();
 					let context_creator = context_creator!(
 						closure!(clone context, clone new_bindings, |this: Option<ObjValue>, super_obj: Option<ObjValue>| {
-							Ok(context.clone().extend_unbound(
+							Ok(context.extend_unbound(
 								new_bindings.clone().unwrap(),
-								context.clone().dollar().clone().or_else(||this.clone()),
+								context.dollar().clone().or_else(||this.clone()),
 								None,
 								super_obj
 							)?)
@@ -664,14 +664,14 @@
 					("std", "filter") => {
 						assert_eq!(args.len(), 2);
 						if let (Val::Func(predicate), Val::Arr(arr)) = (
-							evaluate(context, &args[0].1)?,
-							evaluate(context, &args[1].1)?,
+							evaluate(context.clone(), &args[0].1)?,
+							evaluate(context.clone(), &args[1].1)?,
 						) {
 							Val::Arr(
 								arr.into_iter()
 									.filter(|e| {
 										predicate
-											.evaluate_values(&context, &[e.clone()])
+											.evaluate_values(context.clone(), &[e.clone()])
 											.unwrap()
 											.try_cast_bool("filter predicate")
 											.unwrap()
@@ -685,7 +685,7 @@
 					// faster
 					("std", "join") => {
 						assert_eq!(args.len(), 2);
-						let joiner = evaluate(context, &args[0].1)?.unwrap_if_lazy()?;
+						let joiner = evaluate(context.clone(), &args[0].1)?.unwrap_if_lazy()?;
 						let items = evaluate(context, &args[1].1)?.unwrap_if_lazy()?;
 						println!("Before");
 						let result = match (joiner, items) {
@@ -775,7 +775,9 @@
 			cond_then,
 			cond_else,
 		} => {
-			if evaluate(context, &cond.0)?.try_cast_bool("if condition should be boolean")? {
+			if evaluate(context.clone(), &cond.0)?
+				.try_cast_bool("if condition should be boolean")?
+			{
 				evaluate(context, cond_then)?
 			} else {
 				match cond_else {
modifiedcrates/jsonnet-evaluator/src/function.rsdiffbeforeafterboth
--- a/crates/jsonnet-evaluator/src/function.rs
+++ b/crates/jsonnet-evaluator/src/function.rs
@@ -69,7 +69,7 @@
 			unreachable!()
 		};
 		let val = if tailstrict {
-			resolved_lazy_val!(evaluate(ctx.clone(), expr)?)
+			resolved_lazy_val!(evaluate(ctx, expr)?)
 		} else {
 			lazy_val!(closure!(clone ctx, clone expr, ||evaluate(ctx.clone(), &expr)))
 		};
modifiedcrates/jsonnet-evaluator/src/lib.rsdiffbeforeafterboth
after · crates/jsonnet-evaluator/src/lib.rs
1#![feature(box_syntax, box_patterns)]2#![feature(type_alias_impl_trait)]3#![feature(debug_non_exhaustive)]4#![allow(macro_expanded_macro_exports_accessed_by_absolute_paths)]5#![feature(stmt_expr_attributes)]6mod ctx;7mod dynamic;8mod error;9mod evaluate;10mod function;11mod import;12mod map;13mod obj;14mod val;1516pub use ctx::*;17pub use dynamic::*;18pub use error::*;19pub use evaluate::*;20pub use function::parse_function_call;21pub use import::*;22use jsonnet_parser::*;23pub use obj::*;24use std::{cell::RefCell, collections::HashMap, fmt::Debug, path::PathBuf, rc::Rc};25pub use val::*;2627type BindableFn = dyn Fn(Option<ObjValue>, Option<ObjValue>) -> Result<LazyVal>;28#[derive(Clone)]29pub enum LazyBinding {30	Bindable(Rc<BindableFn>),31	Bound(LazyVal),32}3334impl Debug for LazyBinding {35	fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {36		write!(f, "LazyBinding")37	}38}39impl LazyBinding {40	pub fn evaluate(&self, this: Option<ObjValue>, super_obj: Option<ObjValue>) -> Result<LazyVal> {41		match self {42			LazyBinding::Bindable(v) => v(this, super_obj),43			LazyBinding::Bound(v) => Ok(v.clone()),44		}45	}46}4748pub struct EvaluationSettings {49	pub max_stack_frames: usize,50	pub max_stack_trace_size: usize,51}52impl Default for EvaluationSettings {53	fn default() -> Self {54		EvaluationSettings {55			max_stack_frames: 200,56			max_stack_trace_size: 20,57		}58	}59}6061pub struct FileData(String, LocExpr, Option<Val>);62#[derive(Default)]63pub struct EvaluationStateInternals {64	/// Used for stack-overflows and stacktraces65	stack: RefCell<Vec<StackTraceElement>>,66	/// Contains file source codes and evaluated results for imports and pretty67	/// printing stacktraces68	files: RefCell<HashMap<PathBuf, FileData>>,69	str_files: RefCell<HashMap<PathBuf, String>>,70	globals: RefCell<HashMap<String, Val>>,7172	/// Values to use with std.extVar73	ext_vars: RefCell<HashMap<String, Val>>,7475	settings: EvaluationSettings,76	import_resolver: Box<dyn ImportResolver>,77}7879thread_local! {80	/// Contains state for currently executing file81	/// Global state is fine there82	pub(crate) static EVAL_STATE: RefCell<Option<EvaluationState>> = RefCell::new(None)83}84#[inline(always)]85pub(crate) fn with_state<T>(f: impl FnOnce(&EvaluationState) -> T) -> T {86	EVAL_STATE.with(87		#[inline(always)]88		|s| f(s.borrow().as_ref().unwrap()),89	)90}91pub(crate) fn create_error<T>(err: Error) -> Result<T> {92	with_state(|s| s.error(err))93}94#[inline(always)]95pub(crate) fn push<T>(e: LocExpr, comment: String, f: impl FnOnce() -> Result<T>) -> Result<T> {96	with_state(|s| s.push(e, comment, f))97}9899/// Maintains stack trace and import resolution100#[derive(Default, Clone)]101pub struct EvaluationState(Rc<EvaluationStateInternals>);102impl EvaluationState {103	pub fn new(settings: EvaluationSettings, import_resolver: Box<dyn ImportResolver>) -> Self {104		EvaluationState(Rc::new(EvaluationStateInternals {105			settings,106			import_resolver,107			..Default::default()108		}))109	}110	pub fn add_file(&self, name: PathBuf, code: String) -> std::result::Result<(), ParseError> {111		self.0.files.borrow_mut().insert(112			name.clone(),113			FileData(114				code.clone(),115				parse(116					&code,117					&ParserSettings {118						file_name: name,119						loc_data: true,120					},121				)?,122				None,123			),124		);125126		Ok(())127	}128	pub fn add_parsed_file(129		&self,130		name: PathBuf,131		code: String,132		parsed: LocExpr,133	) -> std::result::Result<(), ()> {134		self.0135			.files136			.borrow_mut()137			.insert(name, FileData(code, parsed, None));138139		Ok(())140	}141	pub fn get_source(&self, name: &PathBuf) -> Option<String> {142		let ro_map = self.0.files.borrow();143		ro_map.get(name).map(|value| value.0.clone())144	}145	pub fn evaluate_file(&self, name: &PathBuf) -> Result<Val> {146		self.run_in_state(|| {147			let expr: LocExpr = {148				let ro_map = self.0.files.borrow();149				let value = ro_map150					.get(name)151					.unwrap_or_else(|| panic!("file not added: {:?}", name));152				if value.2.is_some() {153					return Ok(value.2.clone().unwrap());154				}155				value.1.clone()156			};157			let value = evaluate(self.create_default_context()?, &expr)?;158			{159				self.0160					.files161					.borrow_mut()162					.get_mut(name)163					.unwrap()164					.2165					.replace(value.clone());166			}167			Ok(value)168		})169	}170	pub(crate) fn import_file(&self, from: &PathBuf, path: &PathBuf) -> Result<Val> {171		let file_path = self.0.import_resolver.resolve_file(from, path)?;172		{173			let files = self.0.files.borrow();174			if files.contains_key(&file_path) {175				return self.evaluate_file(&file_path);176			}177		}178		let contents = self.0.import_resolver.load_file_contents(&file_path)?;179		self.add_file(file_path.clone(), contents).map_err(|e| {180			create_error::<()>(Error::ImportSyntaxError(e))181				.err()182				.unwrap()183		})?;184		self.evaluate_file(&file_path)185	}186	pub(crate) fn import_file_str(&self, from: &PathBuf, path: &PathBuf) -> Result<String> {187		let path = self.0.import_resolver.resolve_file(from, path)?;188		if !self.0.str_files.borrow().contains_key(&path) {189			let file_str = self.0.import_resolver.load_file_contents(&path)?;190			self.0.str_files.borrow_mut().insert(path.clone(), file_str);191		}192		Ok(self.0.str_files.borrow().get(&path).cloned().unwrap())193	}194195	pub fn parse_evaluate_raw(&self, code: &str) -> Result<Val> {196		let parsed = parse(197			&code,198			&ParserSettings {199				file_name: PathBuf::from("raw.jsonnet"),200				loc_data: true,201			},202		)203		.unwrap();204		self.evaluate_raw(parsed)205	}206207	pub fn evaluate_raw(&self, code: LocExpr) -> Result<Val> {208		self.run_in_state(|| evaluate(self.create_default_context()?, &code))209	}210211	pub fn add_global(&self, name: String, value: Val) {212		self.0.globals.borrow_mut().insert(name, value);213	}214	pub fn add_ext_var(&self, name: String, value: Val) {215		self.0.ext_vars.borrow_mut().insert(name, value);216	}217218	pub fn with_stdlib(&self) -> &Self {219		self.run_in_state(|| {220			use jsonnet_stdlib::STDLIB_STR;221			if cfg!(feature = "serialized-stdlib") {222				self.add_parsed_file(223					PathBuf::from("std.jsonnet"),224					STDLIB_STR.to_owned(),225					bincode::deserialize(include_bytes!(concat!(226						env!("OUT_DIR"),227						"/stdlib.bincode"228					)))229					.expect("deserialize stdlib"),230				)231				.unwrap();232			} else {233				self.add_file(PathBuf::from("std.jsonnet"), STDLIB_STR.to_owned())234					.unwrap();235			}236			let val = self.evaluate_file(&PathBuf::from("std.jsonnet")).unwrap();237			self.add_global("std".to_owned(), val);238		});239		self240	}241242	pub fn create_default_context(&self) -> Result<Context> {243		let globals = self.0.globals.borrow();244		let mut new_bindings: HashMap<String, LazyBinding> = HashMap::new();245		for (name, value) in globals.iter() {246			new_bindings.insert(247				name.clone(),248				LazyBinding::Bound(resolved_lazy_val!(value.clone())),249			);250		}251		Context::new().extend_unbound(new_bindings, None, None, None)252	}253254	#[inline(always)]255	pub fn push<T>(&self, e: LocExpr, comment: String, f: impl FnOnce() -> Result<T>) -> Result<T> {256		{257			let mut stack = self.0.stack.borrow_mut();258			if stack.len() > self.0.settings.max_stack_frames {259				drop(stack);260				return self.error(Error::StackOverflow);261			} else {262				stack.push(StackTraceElement(e, comment));263			}264		}265		let result = f();266		self.0.stack.borrow_mut().pop();267		result268	}269	pub fn print_stack_trace(&self) {270		for e in self.stack_trace().0 {271			println!("{:?} - {:?}", e.0, e.1)272		}273	}274	pub fn stack_trace(&self) -> StackTrace {275		StackTrace(276			self.0277				.stack278				.borrow()279				.iter()280				.rev()281				.take(self.0.settings.max_stack_trace_size)282				.cloned()283				.collect(),284		)285	}286	pub fn error<T>(&self, err: Error) -> Result<T> {287		Err(LocError(err, self.stack_trace()))288	}289290	#[inline(always)]291	fn run_in_state<T>(&self, f: impl FnOnce() -> T) -> T {292		EVAL_STATE.with(|v| {293			let has_state = v.borrow().is_some();294			if !has_state {295				println!("Begin state");296				v.borrow_mut().replace(self.clone());297			}298			let result = f();299			if !has_state {300				println!("End state");301				v.borrow_mut().take();302			}303			result304		})305	}306}307308#[cfg(test)]309pub mod tests {310	use super::Val;311	use crate::EvaluationState;312	use jsonnet_parser::*;313	use std::path::PathBuf;314315	#[test]316	fn eval_state_stacktrace() {317		let state = EvaluationState::default();318		state319			.push(320				loc_expr!(321					Expr::Num(0.0),322					true,323					(PathBuf::from("test1.jsonnet"), 10, 20)324				),325				"outer".to_owned(),326				|| {327					state.push(328						loc_expr!(329							Expr::Num(0.0),330							true,331							(PathBuf::from("test2.jsonnet"), 30, 40)332						),333						"inner".to_owned(),334						|| {335							state.print_stack_trace();336							Ok(())337						},338					)?;339					Ok(())340				},341			)342			.unwrap();343	}344345	#[test]346	fn eval_state_standard() {347		let state = EvaluationState::default();348		state.with_stdlib();349		assert_eq!(350			state351				.parse_evaluate_raw(r#"std.assertEqual(std.base64("test"), "dGVzdA==")"#)352				.unwrap(),353			Val::Bool(true)354		);355	}356357	macro_rules! eval {358		($str: expr) => {359			EvaluationState::default()360				.with_stdlib()361				.parse_evaluate_raw($str)362				.unwrap()363		};364	}365	macro_rules! eval_json {366		($str: expr) => {{367			let evaluator = EvaluationState::default();368			evaluator.with_stdlib();369			let val = evaluator.parse_evaluate_raw($str).unwrap();370			evaluator.add_global("__tmp__to_yaml__".to_owned(), val);371			evaluator372				.parse_evaluate_raw("std.manifestJsonEx(__tmp__to_yaml__, \"\")")373				.unwrap()374				.try_cast_str("there should be json string")375				.unwrap()376				.clone()377				.replace("\n", "")378			}};379	}380381	/// Asserts given code returns `true`382	macro_rules! assert_eval {383		($str: expr) => {384			assert_eq!(eval!($str), Val::Bool(true))385		};386	}387388	/// Asserts given code returns `false`389	macro_rules! assert_eval_neg {390		($str: expr) => {391			assert_eq!(eval!($str), Val::Bool(false))392		};393	}394	macro_rules! assert_json {395		($str: expr, $out: expr) => {396			assert_eq!(eval_json!($str), $out.replace("\t", ""))397		};398	}399400	/// Sanity checking, before trusting to another tests401	#[test]402	fn equality_operator() {403		assert_eval!("2 == 2");404		assert_eval_neg!("2 != 2");405		assert_eval!("2 != 3");406		assert_eval_neg!("2 == 3");407		assert_eval!("'Hello' == 'Hello'");408		assert_eval_neg!("'Hello' != 'Hello'");409		assert_eval!("'Hello' != 'World'");410		assert_eval_neg!("'Hello' == 'World'");411	}412413	#[test]414	fn math_evaluation() {415		assert_eval!("2 + 2 * 2 == 6");416		assert_eval!("3 + (2 + 2 * 2) == 9");417	}418419	#[test]420	fn string_concat() {421		assert_eval!("'Hello' + 'World' == 'HelloWorld'");422		assert_eval!("'Hello' * 3 == 'HelloHelloHello'");423		assert_eval!("'Hello' + 'World' * 3 == 'HelloWorldWorldWorld'");424	}425426	#[test]427	fn faster_join() {428		assert_eval!("std.join([0,0], [[1,2],[3,4],[5,6]]) == [1,2,0,0,3,4,0,0,5,6]");429		assert_eval!("std.join(',', ['1','2','3','4']) == '1,2,3,4'");430	}431432	#[test]433	fn function_contexts() {434		assert_eval!(435			r#"436				local k = {437					t(name = self.h): [self.h, name],438					h: 3,439				};440				local f = {441					t: k.t(),442					h: 4,443				};444				f.t[0] == f.t[1]445			"#446		);447	}448449	#[test]450	fn local() {451		assert_eval!("local a = 2; local b = 3; a + b == 5");452		assert_eval!("local a = 1, b = a + 1; a + b == 3");453		assert_eval!("local a = 1; local a = 2; a == 2");454	}455456	#[test]457	fn object_lazyness() {458		assert_json!("local a = {a:error 'test'}; {}", r#"{}"#);459	}460461	/// FIXME: This test gets stackoverflow in debug build462	#[test]463	fn object_inheritance() {464		assert_json!("{a: self.b} + {b:3}", r#"{"a": 3,"b": 3}"#);465	}466467	#[test]468	fn object_assertion_success() {469		eval!("{assert \"a\" in self} + {a:2}");470	}471472	#[test]473	fn object_assertion_error() {474		eval!("{assert \"a\" in self}");475	}476477	#[test]478	fn lazy_args() {479		eval!("local test(a) = 2; test(error '3')");480	}481482	#[test]483	fn tailstrict_args() {484		eval!("local test(a) = 2; test(error '3') tailstrict");485	}486487	#[test]488	fn no_binding_error() {489		eval!("a");490	}491492	#[test]493	fn test_object() {494		assert_json!("{a:2}", r#"{"a": 2}"#);495		assert_json!("{a:2+2}", r#"{"a": 4}"#);496		assert_json!("{a:2}+{b:2}", r#"{"a": 2,"b": 2}"#);497		assert_json!("{b:3}+{b:2}", r#"{"b": 2}"#);498		assert_json!("{b:3}+{b+:2}", r#"{"b": 5}"#);499		assert_json!("local test='a'; {[test]:2}", r#"{"a": 2}"#);500		assert_json!(501			r#"502				{503					name: "Alice",504					welcome: "Hello " + self.name + "!",505				}506			"#,507			r#"{"name": "Alice","welcome": "Hello Alice!"}"#508		);509		assert_json!(510			r#"511				{512					name: "Alice",513					welcome: "Hello " + self.name + "!",514				} + {515					name: "Bob"516				}517			"#,518			r#"{"name": "Bob","welcome": "Hello Bob!"}"#519		);520	}521522	#[test]523	fn functions() {524		assert_json!(r#"local a = function(b, c = 2) b + c; a(2)"#, "4");525		assert_json!(526			r#"local a = function(b, c = "Dear") b + c + d, d = "World"; a("Hello")"#,527			r#""HelloDearWorld""#528		);529	}530531	#[test]532	fn local_methods() {533		assert_json!(r#"local a(b, c = 2) = b + c; a(2)"#, "4");534		assert_json!(535			r#"local a(b, c = "Dear") = b + c + d, d = "World"; a("Hello")"#,536			r#""HelloDearWorld""#537		);538	}539540	#[test]541	fn object_locals() {542		assert_json!(r#"{local a = 3, b: a}"#, r#"{"b": 3}"#);543		assert_json!(r#"{local a = 3, local c = a, b: c}"#, r#"{"b": 3}"#);544		assert_json!(545			r#"{local a = function (b) {[b]:4}, test: a("test")}"#,546			r#"{"test": {"test": 4}}"#547		);548	}549550	#[test]551	fn object_comp() {552		assert_json!(553			r#"{local t = "a", ["h"+i+"_"+z]: if "h"+(i-1)+"_"+z in self then t+1 else 0+t for i in [1,2,3] for z in [2,3,4] if z != i}"#,554			"{\"h1_2\": \"0a\",\"h1_3\": \"0a\",\"h1_4\": \"0a\",\"h2_3\": \"a1\",\"h2_4\": \"a1\",\"h3_2\": \"0a\",\"h3_4\": \"a1\"}"555		)556	}557558	#[test]559	fn direct_self() {560		println!(561			"{:#?}",562			eval!(563				r#"564					{565						local me = self,566						a: 3,567						b(): me.a,568					}569				"#570			)571		);572	}573574	#[test]575	fn indirect_self() {576		// `self` assigned to `me` was lost when being577		// referenced from field578		eval!(579			r#"{580				local me = self,581				a: 3,582				b: me.a,583			}.b"#584		);585	}586587	// We can't trust other tests (And official jsonnet testsuite), if assert is not working correctly588	#[test]589	fn std_assert_ok() {590		eval!("std.assertEqual(4.5 << 2, 16)");591	}592593	#[test]594	#[should_panic]595	fn std_assert_failure() {596		eval!("std.assertEqual(4.5 << 2, 15)");597	}598599	#[test]600	fn string_is_string() {601		assert_eq!(602			eval!("local arr = 'hello'; (!std.isArray(arr)) && (!std.isString(arr))"),603			Val::Bool(false)604		);605	}606607	#[test]608	fn base64_works() {609		assert_json!(r#"std.base64("test")"#, r#""dGVzdA==""#);610	}611612	#[test]613	fn utf8_chars() {614		assert_json!(615			r#"local c="😎";{c:std.codepoint(c),l:std.length(c)}"#,616			r#"{"c": 128526,"l": 1}"#617		)618	}619620	#[test]621	fn json() {622		assert_json!(623			r#"std.manifestJsonEx({a:3, b:4, c:6},"")"#,624			r#""{\n\"a\": 3,\n\"b\": 4,\n\"c\": 6\n}""#625		);626	}627628	#[test]629	fn test() {630		assert_json!(631			r#"[[a, b] for a in [1,2,3] for b in [4,5,6]]"#,632			"[[1,4],[1,5],[1,6],[2,4],[2,5],[2,6],[3,4],[3,5],[3,6]]"633		);634	}635636	#[test]637	fn sjsonnet() {638		eval!(639			r#"640			local x0 = {k: 1};641			local x1 = {k: x0.k + x0.k};642			local x2 = {k: x1.k + x1.k};643			local x3 = {k: x2.k + x2.k};644			local x4 = {k: x3.k + x3.k};645			local x5 = {k: x4.k + x4.k};646			local x6 = {k: x5.k + x5.k};647			local x7 = {k: x6.k + x6.k};648			local x8 = {k: x7.k + x7.k};649			local x9 = {k: x8.k + x8.k};650			local x10 = {k: x9.k + x9.k};651			local x11 = {k: x10.k + x10.k};652			local x12 = {k: x11.k + x11.k};653			local x13 = {k: x12.k + x12.k};654			local x14 = {k: x13.k + x13.k};655			local x15 = {k: x14.k + x14.k};656			local x16 = {k: x15.k + x15.k};657			local x17 = {k: x16.k + x16.k};658			local x18 = {k: x17.k + x17.k};659			local x19 = {k: x18.k + x18.k};660			local x20 = {k: x19.k + x19.k};661			local x21 = {k: x20.k + x20.k};662			x21.k663		"#664		);665	}666}
modifiedcrates/jsonnet-evaluator/src/val.rsdiffbeforeafterboth
--- a/crates/jsonnet-evaluator/src/val.rs
+++ b/crates/jsonnet-evaluator/src/val.rs
@@ -179,7 +179,7 @@
 				.create_default_context()?
 				.with_var("__tmp__to_json__".to_owned(), self)?;
 			if let Val::Str(result) = evaluate(
-				&ctx,
+				ctx,
 				&el!(Expr::Apply(
 					el!(Expr::Index(
 						el!(Expr::Var("std".to_owned())),