git.delta.rocks / jrsonnet / refs/commits / 03f24e72fbec

difftreelog

perf(evaluator) deserialize instead of parsing std

Лач2020-06-04parent: #f306bde.patch.diff
in: master

3 files changed

modifiedcrates/jsonnet-evaluator/Cargo.tomldiffbeforeafterboth
--- a/crates/jsonnet-evaluator/Cargo.toml
+++ b/crates/jsonnet-evaluator/Cargo.toml
@@ -6,7 +6,25 @@
 
 # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
 
+[features]
+default = ["serialized-stdlib"]
+serialized-stdlib = ["serde", "bincode"]
+
 [dependencies]
 jsonnet-parser = { path = "../jsonnet-parser" }
 closure = "0.3.0"
-jsonnet-stdlib = { version = "0.1.0", path = "../jsonnet-stdlib" }
+jsonnet-stdlib = { path = "../jsonnet-stdlib" }
+
+[dependencies.serde]
+version = "1.0.111"
+optional = true
+
+[dependencies.bincode]
+version = "1.2.1"
+optional = true
+
+[build-dependencies]
+jsonnet-parser = { path = "../jsonnet-parser" }
+jsonnet-stdlib = { path = "../jsonnet-stdlib" }
+serde = "1.0.111"
+bincode = "1.2.1"
addedcrates/jsonnet-evaluator/build.rsdiffbeforeafterboth
--- /dev/null
+++ b/crates/jsonnet-evaluator/build.rs
@@ -0,0 +1,21 @@
+use bincode::serialize;
+use jsonnet_parser::{parse, ParserSettings};
+use jsonnet_stdlib::STDLIB_STR;
+use std::{env, fs::File, io::Write, path::Path};
+
+fn main() {
+	let parsed = parse(
+		STDLIB_STR,
+		&ParserSettings {
+			file_name: "std.jsonnet".to_owned(),
+			loc_data: true,
+		},
+	)
+	.expect("parse");
+
+	let out_dir = env::var("OUT_DIR").unwrap();
+	let dest_path = Path::new(&out_dir).join("stdlib.bincode");
+	let mut f = File::create(&dest_path).unwrap();
+	f.write_all(&serialize(&parsed).expect("serialize"))
+		.unwrap();
+}
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)]5mod ctx;6mod dynamic;7mod error;8mod evaluate;9mod obj;10mod val;1112use closure::closure;13pub use ctx::*;14pub use dynamic::*;15pub use error::*;16pub use evaluate::*;17use jsonnet_parser::*;18pub use obj::*;19use std::{cell::RefCell, collections::HashMap, rc::Rc};20pub use val::*;2122rc_fn_helper!(23	Binding,24	binding,25	dyn Fn(Option<ObjValue>, Option<ObjValue>) -> Result<Val>26);27rc_fn_helper!(28	LazyBinding,29	lazy_binding,30	dyn Fn(Option<ObjValue>, Option<ObjValue>) -> Result<LazyVal>31);32rc_fn_helper!(FunctionRhs, function_rhs, dyn Fn(Context) -> Result<Val>);33rc_fn_helper!(34	FunctionDefault,35	function_default,36	dyn Fn(Context, LocExpr) -> Result<Val>37);3839pub struct FileData(String, LocExpr, Option<Val>);40#[derive(Default)]41pub struct EvaluationStateInternals {42	/// Used for stack-overflows and stacktraces43	stack: RefCell<Vec<StackTraceElement>>,44	/// Contains file source codes and evaluated results for imports and pretty45	/// printing stacktraces46	files: RefCell<HashMap<String, FileData>>,47	globals: RefCell<HashMap<String, Val>>,48}4950thread_local! {51	pub static EVAL_STATE: RefCell<Option<EvaluationState>> = RefCell::new(None)52}53pub(crate) fn with_state<T>(f: impl FnOnce(&EvaluationState) -> T) -> T {54	EVAL_STATE.with(|s| f(s.borrow().as_ref().unwrap()))55}56pub(crate) fn create_error<T>(err: Error) -> Result<T> {57	with_state(|s| s.error(err))58}59pub(crate) fn push<T>(e: LocExpr, comment: String, f: impl FnOnce() -> T) -> T {60	with_state(|s| s.push(e, comment, f))61}6263#[derive(Default, Clone)]64pub struct EvaluationState(Rc<EvaluationStateInternals>);65impl EvaluationState {66	pub fn add_file(67		&self,68		name: String,69		code: String,70	) -> std::result::Result<(), Box<dyn std::error::Error>> {71		self.0.files.borrow_mut().insert(72			name.clone(),73			FileData(74				code.clone(),75				parse(76					&code,77					&ParserSettings {78						file_name: name,79						loc_data: true,80					},81				)?,82				None,83			),84		);8586		Ok(())87	}88	pub fn add_parsed_file(89		&self,90		name: String,91		code: String,92		parsed: LocExpr,93	) -> std::result::Result<(), Box<dyn std::error::Error>> {94		self.095			.files96			.borrow_mut()97			.insert(name, FileData(code, parsed, None));9899		Ok(())100	}101	pub fn get_source(&self, name: &str) -> String {102		let ro_map = self.0.files.borrow();103		let value = ro_map104			.get(name)105			.unwrap_or_else(|| panic!("file not added: {:?}", name));106		value.0.clone()107	}108	pub fn evaluate_file(&self, name: &str) -> Result<Val> {109		self.begin_state();110		let expr: LocExpr = {111			let ro_map = self.0.files.borrow();112			let value = ro_map113				.get(name)114				.unwrap_or_else(|| panic!("file not added: {:?}", name));115			if value.2.is_some() {116				return Ok(value.2.clone().unwrap());117			}118			value.1.clone()119		};120		let value = evaluate(self.create_default_context()?, &expr)?;121		{122			self.0123				.files124				.borrow_mut()125				.get_mut(name)126				.unwrap()127				.2128				.replace(value.clone());129		}130		self.end_state();131		Ok(value)132	}133134	pub fn parse_evaluate_raw(&self, code: &str) -> Result<Val> {135		let parsed = parse(136			&code,137			&ParserSettings {138				file_name: "raw.jsonnet".to_owned(),139				loc_data: true,140			},141		);142		self.begin_state();143		let value = evaluate(self.create_default_context()?, &parsed.unwrap());144		self.end_state();145		value146	}147148	pub fn add_stdlib(&self) {149		self.begin_state();150		use jsonnet_stdlib::STDLIB_STR;151		if cfg!(feature = "serialized-stdlib") {152			self.add_parsed_file(153				"std.jsonnet".to_owned(),154				STDLIB_STR.to_owned(),155				bincode::deserialize(include_bytes!(concat!(env!("OUT_DIR"), "/stdlib.bincode"))).expect("deserialize stdlib"),156			).unwrap();157		} else {158			self.add_file("std.jsonnet".to_owned(), STDLIB_STR.to_owned())159				.unwrap();160		}161		let val = self.evaluate_file("std.jsonnet").unwrap();162		self.0.globals.borrow_mut().insert("std".to_owned(), val);163		self.end_state();164	}165166	pub fn create_default_context(&self) -> Result<Context> {167		let globals = self.0.globals.borrow();168		let mut new_bindings: HashMap<String, LazyBinding> = HashMap::new();169		for (name, value) in globals.iter() {170			new_bindings.insert(171				name.clone(),172				lazy_binding!(173					closure!(clone value, |_self, _super_obj| Ok(lazy_val!(closure!(clone value, ||Ok(value.clone())))))174				),175			);176		}177		Context::new().extend(new_bindings, None, None, None)178	}179180	pub fn push<T>(&self, e: LocExpr, comment: String, f: impl FnOnce() -> T) -> T {181		self.0182			.stack183			.borrow_mut()184			.push(StackTraceElement(e, comment));185		let result = f();186		self.0.stack.borrow_mut().pop();187		result188	}189	pub fn print_stack_trace(&self) {190		for e in self.stack_trace().0 {191			println!("{:?} - {:?}", e.0, e.1)192		}193	}194	pub fn stack_trace(&self) -> StackTrace {195		StackTrace(self.0.stack.borrow().iter().rev().cloned().collect())196	}197	pub fn error<T>(&self, err: Error) -> Result<T> {198		Err(LocError(err, self.stack_trace()))199	}200201	fn begin_state(&self) {202		EVAL_STATE.with(|v| v.borrow_mut().replace(self.clone()));203	}204	fn end_state(&self) {205		EVAL_STATE.with(|v| v.borrow_mut().take());206	}207}208209#[cfg(test)]210pub mod tests {211	use super::Val;212	use crate::EvaluationState;213	use jsonnet_parser::*;214215	#[test]216	fn eval_state_stacktrace() {217		let state = EvaluationState::default();218		state.push(219			loc_expr!(Expr::Num(0.0), true, ("test1.jsonnet".to_owned(), 10, 20)),220			"outer".to_owned(),221			|| {222				state.push(223					loc_expr!(Expr::Num(0.0), true, ("test2.jsonnet".to_owned(), 30, 40)),224					"inner".to_owned(),225					|| state.print_stack_trace(),226				);227			},228		);229	}230231	#[test]232	fn eval_state_standard() {233		let state = EvaluationState::default();234		state.add_stdlib();235		assert_eq!(236			state237				.parse_evaluate_raw(r#"std.assertEqual(std.base64("test"), "dGVzdA==w")"#)238				.unwrap(),239			Val::Bool(true)240		);241	}242243	macro_rules! eval {244		($str: expr) => {245			evaluate(246				Context::new(),247				EvaluationState::default(),248				&parse(249					$str,250					&ParserSettings {251						loc_data: true,252						file_name: "test.jsonnet".to_owned(),253					},254					)255				.unwrap(),256				)257		};258	}259260	macro_rules! eval_stdlib {261		($str: expr) => {{262			let std = "local std = ".to_owned() + jsonnet_stdlib::STDLIB_STR + ";";263			evaluate(264				Context::new(),265				EvaluationState::default(),266				&parse(267					&(std + $str),268					&ParserSettings {269						loc_data: true,270						file_name: "test.jsonnet".to_owned(),271					},272					)273				.unwrap(),274				)275			}};276	}277278	macro_rules! assert_eval {279		($str: expr) => {280			assert_eq!(281				evaluate(282					Context::new(),283					EvaluationState::default(),284					&parse(285						$str,286						&ParserSettings {287							loc_data: true,288							file_name: "test.jsonnet".to_owned(),289						}290						)291					.unwrap()292					),293				Val::Bool(true)294				)295		};296	}297	macro_rules! assert_json {298		($str: expr, $out: expr) => {299			assert_eq!(300				format!(301					"{}",302					evaluate(303						Context::new(),304						EvaluationState::default(),305						&parse(306							$str,307							&ParserSettings {308								loc_data: true,309								file_name: "test.jsonnet".to_owned(),310							}311						)312						.unwrap()313						)314					),315				$out316				)317		};318	}319	macro_rules! assert_json_stdlib {320		($str: expr, $out: expr) => {321			assert_eq!(format!("{}", eval_stdlib!($str)), $out)322		};323	}324	macro_rules! assert_eval_neg {325		($str: expr) => {326			assert_eq!(327				evaluate(328					Context::new(),329					EvaluationState::default(),330					&parse(331						$str,332						&ParserSettings {333							loc_data: true,334							file_name: "test.jsonnet".to_owned(),335						}336						)337					.unwrap()338					),339				Val::Bool(false)340				)341		};342	}343344	/*345	/// Sanity checking, before trusting to another tests346	#[test]347	fn equality_operator() {348		assert_eval!("2 == 2");349		assert_eval_neg!("2 != 2");350		assert_eval!("2 != 3");351		assert_eval_neg!("2 == 3");352		assert_eval!("'Hello' == 'Hello'");353		assert_eval_neg!("'Hello' != 'Hello'");354		assert_eval!("'Hello' != 'World'");355		assert_eval_neg!("'Hello' == 'World'");356	}357358	#[test]359	fn math_evaluation() {360		assert_eval!("2 + 2 * 2 == 6");361		assert_eval!("3 + (2 + 2 * 2) == 9");362	}363364	#[test]365	fn string_concat() {366		assert_eval!("'Hello' + 'World' == 'HelloWorld'");367		assert_eval!("'Hello' * 3 == 'HelloHelloHello'");368		assert_eval!("'Hello' + 'World' * 3 == 'HelloWorldWorldWorld'");369	}370371	#[test]372	fn local() {373		assert_eval!("local a = 2; local b = 3; a + b == 5");374		assert_eval!("local a = 1, b = a + 1; a + b == 3");375		assert_eval!("local a = 1; local a = 2; a == 2");376	}377378	#[test]379	fn object_lazyness() {380		assert_json!("local a = {a:error 'test'}; {}", r#"{}"#);381	}382383	#[test]384	fn object_inheritance() {385		assert_json!("{a: self.b} + {b:3}", r#"{"a":3,"b":3}"#);386	}387388	#[test]389	fn test_object() {390		assert_json!("{a:2}", r#"{"a":2}"#);391		assert_json!("{a:2+2}", r#"{"a":4}"#);392		assert_json!("{a:2}+{b:2}", r#"{"a":2,"b":2}"#);393		assert_json!("{b:3}+{b:2}", r#"{"b":2}"#);394		assert_json!("{b:3}+{b+:2}", r#"{"b":5}"#);395		assert_json!("local test='a'; {[test]:2}", r#"{"a":2}"#);396		assert_json!(397			r#"398				{399					name: "Alice",400					welcome: "Hello " + self.name + "!",401				}402			"#,403			r#"{"name":"Alice","welcome":"Hello Alice!"}"#404		);405		assert_json!(406			r#"407				{408					name: "Alice",409					welcome: "Hello " + self.name + "!",410				} + {411					name: "Bob"412				}413			"#,414			r#"{"name":"Bob","welcome":"Hello Bob!"}"#415		);416	}417418	#[test]419	fn functions() {420		assert_json!(r#"local a = function(b, c = 2) b + c; a(2)"#, "4");421		assert_json!(422			r#"local a = function(b, c = "Dear") b + c + d, d = "World"; a("Hello")"#,423			r#""HelloDearWorld""#424		);425	}426427	#[test]428	fn local_methods() {429		assert_json!(r#"local a(b, c = 2) = b + c; a(2)"#, "4");430		assert_json!(431			r#"local a(b, c = "Dear") = b + c + d, d = "World"; a("Hello")"#,432			r#""HelloDearWorld""#433		);434	}435436	#[test]437	fn object_locals() {438		assert_json!(r#"{local a = 3, b: a}"#, r#"{"b":3}"#);439		assert_json!(r#"{local a = 3, local c = a, b: c}"#, r#"{"b":3}"#);440		assert_json!(441			r#"{local a = function (b) {[b]:4}, test: a("test")}"#,442			r#"{"test":{"test":4}}"#443		);444	}445446	#[test]447	fn direct_self() {448		println!(449			"{:#?}",450			eval!(451				r#"452					{453						local me = self,454						a: 3,455						b(): me.a,456					}457				"#458			)459		);460	}461462	#[test]463	fn indirect_self() {464		// `self` assigned to `me` was lost when being465		// referenced from field466		eval_stdlib!(467			r#"{468				local me = self,469				a: 3,470				b: me.a,471			}.b"#472		);473	}474475	// We can't trust other tests (And official jsonnet testsuite), if assert is not working correctly476	#[test]477	fn std_assert_ok() {478		eval_stdlib!("std.assertEqual(4.5 << 2, 16)");479	}480481	#[test]482	#[should_panic]483	fn std_assert_failure() {484		eval_stdlib!("std.assertEqual(4.5 << 2, 15)");485	}486487	#[test]488	fn string_is_string() {489		assert_eq!(490			eval_stdlib!("local arr = 'hello'; (!std.isArray(arr)) && (!std.isString(arr))"),491			Val::Bool(false)492		);493	}494495	#[test]496	fn base64_works() {497		assert_json_stdlib!(r#"std.base64("test")"#, r#""dGVzdA==""#);498	}499500	#[test]501	fn utf8_chars() {502		assert_json_stdlib!(503			r#"local c="😎";{c:std.codepoint(c),l:std.length(c)}"#,504			r#"{"c":128526,"l":1}"#505		)506	}507508	#[test]509	fn json() {510		assert_json_stdlib!(511			r#"std.manifestJsonEx({a:3, b:4, c:6},"")"#,512			r#""{\n"a": 3,\n"b": 4,\n"c": 6\n}""#513		);514	}515516	#[test]517	fn test() {518		assert_json_stdlib!(519			r#"[[a, b] for a in [1,2,3] for b in [4,5,6]]"#,520			"[[1,4],[1,5],[1,6],[2,4],[2,5],[2,6],[3,4],[3,5],[3,6]]"521		);522	}523524	#[test]525	fn sjsonnet() {526		eval!(527			r#"528			local x0 = {k: 1};529			local x1 = {k: x0.k + x0.k};530			local x2 = {k: x1.k + x1.k};531			local x3 = {k: x2.k + x2.k};532			local x4 = {k: x3.k + x3.k};533			local x5 = {k: x4.k + x4.k};534			local x6 = {k: x5.k + x5.k};535			local x7 = {k: x6.k + x6.k};536			local x8 = {k: x7.k + x7.k};537			local x9 = {k: x8.k + x8.k};538			local x10 = {k: x9.k + x9.k};539			local x11 = {k: x10.k + x10.k};540			local x12 = {k: x11.k + x11.k};541			local x13 = {k: x12.k + x12.k};542			local x14 = {k: x13.k + x13.k};543			local x15 = {k: x14.k + x14.k};544			local x16 = {k: x15.k + x15.k};545			local x17 = {k: x16.k + x16.k};546			local x18 = {k: x17.k + x17.k};547			local x19 = {k: x18.k + x18.k};548			local x20 = {k: x19.k + x19.k};549			local x21 = {k: x20.k + x20.k};550			x21.k551		"#552		);553	}554	*/555}