git.delta.rocks / jrsonnet / refs/commits / 90cacba70c63

difftreelog

perf(evaluator) emove expr from stacktraces

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

4 files changed

modifiedcmds/jrsonnet/src/main.rsdiffbeforeafterboth
--- a/cmds/jrsonnet/src/main.rs
+++ b/cmds/jrsonnet/src/main.rs
@@ -271,10 +271,7 @@
 	};
 	for item in trace.0.iter() {
 		let desc = &item.1;
-		if (item.0).1.is_none() {
-			continue;
-		}
-		let source = (item.0).1.clone().unwrap();
+		let source = item.0.clone();
 		let code = evaluator.get_source(&source.0);
 		if code.is_none() {
 			continue;
modifiedcrates/jsonnet-evaluator/src/error.rsdiffbeforeafterboth
--- a/crates/jsonnet-evaluator/src/error.rs
+++ b/crates/jsonnet-evaluator/src/error.rs
@@ -1,6 +1,6 @@
 use crate::ValType;
-use jsonnet_parser::LocExpr;
-use std::path::PathBuf;
+use jsonnet_parser::ExprLocation;
+use std::{path::PathBuf, rc::Rc};
 
 #[derive(Debug, Clone)]
 pub enum Error {
@@ -38,7 +38,7 @@
 }
 
 #[derive(Clone, Debug)]
-pub struct StackTraceElement(pub LocExpr, pub String);
+pub struct StackTraceElement(pub Rc<ExprLocation>, pub String);
 #[derive(Debug, Clone)]
 pub struct StackTrace(pub Vec<StackTraceElement>);
 
modifiedcrates/jsonnet-evaluator/src/evaluate.rsdiffbeforeafterboth
--- a/crates/jsonnet-evaluator/src/evaluate.rs
+++ b/crates/jsonnet-evaluator/src/evaluate.rs
@@ -35,7 +35,7 @@
 			b.name.clone(),
 			LazyBinding::Bindable(Rc::new(move |this, super_obj| {
 				Ok(lazy_val!(closure!(clone context_creator, clone b, ||
-					push(b.value.clone(), "thunk".to_owned(), ||{
+					push(&b.value.1, "thunk", ||{
 						evaluate(
 							context_creator.0(this.clone(), super_obj.clone())?,
 							&b.value
@@ -255,7 +255,7 @@
 								visibility: visibility.clone(),
 								invoke: LazyBinding::Bindable(Rc::new(
 									closure!(clone name, clone value, clone context_creator, |this, super_obj| {
-										Ok(LazyVal::new_resolved(push(value.clone(), "object ".to_owned()+&name+" field", ||{
+										Ok(LazyVal::new_resolved(push(&value.1, "object field", ||{
 											let context = context_creator.0(this, super_obj)?;
 											evaluate(
 												context,
@@ -371,7 +371,6 @@
 
 pub fn evaluate(context: Context, expr: &LocExpr) -> Result<Val> {
 	use Expr::*;
-	let locexpr = expr.clone();
 	let LocExpr(expr, loc) = expr;
 	Ok(match &**expr {
 		Literal(LiteralType::This) => Val::Obj(
@@ -394,7 +393,7 @@
 		Num(v) => Val::Num(*v),
 		BinaryOp(v1, o, v2) => evaluate_binary_op_special(context, &v1, *o, &v2)?,
 		UnaryOp(o, v) => evaluate_unary_op(*o, &evaluate(context, v)?)?,
-		Var(name) => push(locexpr, "var".to_owned(), || {
+		Var(name) => push(loc, "var", || {
 			Val::Lazy(context.binding(&name)?).unwrap_if_lazy()
 		})?,
 		Index(LocExpr(v, _), index) if matches!(&**v, Expr::Literal(LiteralType::Super)) => {
@@ -733,7 +732,7 @@
 					if *tailstrict {
 						body()?
 					} else {
-						push(locexpr, "function call".to_owned(), body)?
+						push(loc, "function call", body)?
 					}
 				}
 				_ => panic!("{:?} is not a function", value),
@@ -741,16 +740,12 @@
 		}
 		Function(params, body) => evaluate_method(context, params.clone(), body.clone()),
 		AssertExpr(AssertStmt(value, msg), returned) => {
-			let assertion_result = push(value.clone(), "assertion condition".to_owned(), || {
+			let assertion_result = push(&value.1, "assertion condition", || {
 				evaluate(context.clone(), &value)?
 					.try_cast_bool("assertion condition should be boolean")
 			})?;
 			if assertion_result {
-				push(
-					returned.clone(),
-					"assert 'return' branch".to_owned(),
-					|| evaluate(context, returned),
-				)?
+				evaluate(context, returned)?
 			} else if let Some(msg) = msg {
 				panic!(
 					"assertion failed ({:?}): {}",
modifiedcrates/jsonnet-evaluator/src/lib.rsdiffbeforeafterboth
before · 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 function;10mod import;11mod map;12mod obj;13mod val;1415pub use ctx::*;16pub use dynamic::*;17pub use error::*;18pub use evaluate::*;19pub use function::parse_function_call;20pub use import::*;21use jsonnet_parser::*;22pub use obj::*;23use std::{cell::RefCell, collections::HashMap, fmt::Debug, path::PathBuf, rc::Rc};24pub use val::*;2526type BindableFn = dyn Fn(Option<ObjValue>, Option<ObjValue>) -> Result<LazyVal>;27#[derive(Clone)]28pub enum LazyBinding {29	Bindable(Rc<BindableFn>),30	Bound(LazyVal),31}3233impl Debug for LazyBinding {34	fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {35		write!(f, "LazyBinding")36	}37}38impl LazyBinding {39	pub fn evaluate(&self, this: Option<ObjValue>, super_obj: Option<ObjValue>) -> Result<LazyVal> {40		match self {41			LazyBinding::Bindable(v) => v(this, super_obj),42			LazyBinding::Bound(v) => Ok(v.clone()),43		}44	}45}4647pub struct EvaluationSettings {48	pub max_stack_frames: usize,49	pub max_stack_trace_size: usize,50}51impl Default for EvaluationSettings {52	fn default() -> Self {53		EvaluationSettings {54			max_stack_frames: 200,55			max_stack_trace_size: 20,56		}57	}58}5960pub struct FileData(String, LocExpr, Option<Val>);61#[derive(Default)]62pub struct EvaluationStateInternals {63	/// Used for stack-overflows and stacktraces64	stack: RefCell<Vec<StackTraceElement>>,65	/// Contains file source codes and evaluated results for imports and pretty66	/// printing stacktraces67	files: RefCell<HashMap<PathBuf, FileData>>,68	str_files: RefCell<HashMap<PathBuf, String>>,69	globals: RefCell<HashMap<String, Val>>,7071	/// Values to use with std.extVar72	ext_vars: RefCell<HashMap<String, Val>>,7374	settings: EvaluationSettings,75	import_resolver: Box<dyn ImportResolver>,76}7778thread_local! {79	/// Contains state for currently executing file80	/// Global state is fine there81	pub(crate) static EVAL_STATE: RefCell<Option<EvaluationState>> = RefCell::new(None)82}83pub(crate) fn with_state<T>(f: impl FnOnce(&EvaluationState) -> T) -> T {84	EVAL_STATE.with(85		|s| f(s.borrow().as_ref().unwrap()),86	)87}88pub(crate) fn create_error<T>(err: Error) -> Result<T> {89	with_state(|s| s.error(err))90}91pub(crate) fn push<T>(e: LocExpr, comment: String, f: impl FnOnce() -> Result<T>) -> Result<T> {92	with_state(|s| s.push(e, comment, f))93}9495/// Maintains stack trace and import resolution96#[derive(Default, Clone)]97pub struct EvaluationState(Rc<EvaluationStateInternals>);98impl EvaluationState {99	pub fn new(settings: EvaluationSettings, import_resolver: Box<dyn ImportResolver>) -> Self {100		EvaluationState(Rc::new(EvaluationStateInternals {101			settings,102			import_resolver,103			..Default::default()104		}))105	}106	pub fn add_file(&self, name: PathBuf, code: String) -> std::result::Result<(), ParseError> {107		self.0.files.borrow_mut().insert(108			name.clone(),109			FileData(110				code.clone(),111				parse(112					&code,113					&ParserSettings {114						file_name: name,115						loc_data: true,116					},117				)?,118				None,119			),120		);121122		Ok(())123	}124	pub fn add_parsed_file(125		&self,126		name: PathBuf,127		code: String,128		parsed: LocExpr,129	) -> std::result::Result<(), ()> {130		self.0131			.files132			.borrow_mut()133			.insert(name, FileData(code, parsed, None));134135		Ok(())136	}137	pub fn get_source(&self, name: &PathBuf) -> Option<String> {138		let ro_map = self.0.files.borrow();139		ro_map.get(name).map(|value| value.0.clone())140	}141	pub fn evaluate_file(&self, name: &PathBuf) -> Result<Val> {142		self.run_in_state(|| {143			let expr: LocExpr = {144				let ro_map = self.0.files.borrow();145				let value = ro_map146					.get(name)147					.unwrap_or_else(|| panic!("file not added: {:?}", name));148				if value.2.is_some() {149					return Ok(value.2.clone().unwrap());150				}151				value.1.clone()152			};153			let value = evaluate(self.create_default_context()?, &expr)?;154			{155				self.0156					.files157					.borrow_mut()158					.get_mut(name)159					.unwrap()160					.2161					.replace(value.clone());162			}163			Ok(value)164		})165	}166	pub(crate) fn import_file(&self, from: &PathBuf, path: &PathBuf) -> Result<Val> {167		let file_path = self.0.import_resolver.resolve_file(from, path)?;168		{169			let files = self.0.files.borrow();170			if files.contains_key(&file_path) {171				return self.evaluate_file(&file_path);172			}173		}174		let contents = self.0.import_resolver.load_file_contents(&file_path)?;175		self.add_file(file_path.clone(), contents).map_err(|e| {176			create_error::<()>(Error::ImportSyntaxError(e))177				.err()178				.unwrap()179		})?;180		self.evaluate_file(&file_path)181	}182	pub(crate) fn import_file_str(&self, from: &PathBuf, path: &PathBuf) -> Result<String> {183		let path = self.0.import_resolver.resolve_file(from, path)?;184		if !self.0.str_files.borrow().contains_key(&path) {185			let file_str = self.0.import_resolver.load_file_contents(&path)?;186			self.0.str_files.borrow_mut().insert(path.clone(), file_str);187		}188		Ok(self.0.str_files.borrow().get(&path).cloned().unwrap())189	}190191	pub fn parse_evaluate_raw(&self, code: &str) -> Result<Val> {192		let parsed = parse(193			&code,194			&ParserSettings {195				file_name: PathBuf::from("raw.jsonnet"),196				loc_data: true,197			},198		)199		.unwrap();200		self.evaluate_raw(parsed)201	}202203	pub fn evaluate_raw(&self, code: LocExpr) -> Result<Val> {204		self.run_in_state(|| evaluate(self.create_default_context()?, &code))205	}206207	pub fn add_global(&self, name: String, value: Val) {208		self.0.globals.borrow_mut().insert(name, value);209	}210	pub fn add_ext_var(&self, name: String, value: Val) {211		self.0.ext_vars.borrow_mut().insert(name, value);212	}213214	pub fn with_stdlib(&self) -> &Self {215		self.run_in_state(|| {216			use jsonnet_stdlib::STDLIB_STR;217			if cfg!(feature = "serialized-stdlib") {218				self.add_parsed_file(219					PathBuf::from("std.jsonnet"),220					STDLIB_STR.to_owned(),221					bincode::deserialize(include_bytes!(concat!(222						env!("OUT_DIR"),223						"/stdlib.bincode"224					)))225					.expect("deserialize stdlib"),226				)227				.unwrap();228			} else {229				self.add_file(PathBuf::from("std.jsonnet"), STDLIB_STR.to_owned())230					.unwrap();231			}232			let val = self.evaluate_file(&PathBuf::from("std.jsonnet")).unwrap();233			self.add_global("std".to_owned(), val);234		});235		self236	}237238	pub fn create_default_context(&self) -> Result<Context> {239		let globals = self.0.globals.borrow();240		let mut new_bindings: HashMap<String, LazyBinding> = HashMap::new();241		for (name, value) in globals.iter() {242			new_bindings.insert(243				name.clone(),244				LazyBinding::Bound(resolved_lazy_val!(value.clone())),245			);246		}247		Context::new().extend_unbound(new_bindings, None, None, None)248	}249250	pub fn push<T>(&self, e: LocExpr, comment: String, f: impl FnOnce() -> Result<T>) -> Result<T> {251		{252			let mut stack = self.0.stack.borrow_mut();253			if stack.len() > self.0.settings.max_stack_frames {254				drop(stack);255				return self.error(Error::StackOverflow);256			} else {257				stack.push(StackTraceElement(e, comment));258			}259		}260		let result = f();261		self.0.stack.borrow_mut().pop();262		result263	}264	pub fn print_stack_trace(&self) {265		for e in self.stack_trace().0 {266			println!("{:?} - {:?}", e.0, e.1)267		}268	}269	pub fn stack_trace(&self) -> StackTrace {270		StackTrace(271			self.0272				.stack273				.borrow()274				.iter()275				.rev()276				.take(self.0.settings.max_stack_trace_size)277				.cloned()278				.collect(),279		)280	}281	pub fn error<T>(&self, err: Error) -> Result<T> {282		Err(LocError(err, self.stack_trace()))283	}284285	fn run_in_state<T>(&self, f: impl FnOnce() -> T) -> T {286		EVAL_STATE.with(|v| {287			let has_state = v.borrow().is_some();288			if !has_state {289				v.borrow_mut().replace(self.clone());290			}291			let result = f();292			if !has_state {293				v.borrow_mut().take();294			}295			result296		})297	}298}299300#[cfg(test)]301pub mod tests {302	use super::Val;303	use crate::EvaluationState;304	use jsonnet_parser::*;305	use std::path::PathBuf;306307	#[test]308	fn eval_state_stacktrace() {309		let state = EvaluationState::default();310		state311			.push(312				loc_expr!(313					Expr::Num(0.0),314					true,315					(PathBuf::from("test1.jsonnet"), 10, 20)316				),317				"outer".to_owned(),318				|| {319					state.push(320						loc_expr!(321							Expr::Num(0.0),322							true,323							(PathBuf::from("test2.jsonnet"), 30, 40)324						),325						"inner".to_owned(),326						|| {327							state.print_stack_trace();328							Ok(())329						},330					)?;331					Ok(())332				},333			)334			.unwrap();335	}336337	#[test]338	fn eval_state_standard() {339		let state = EvaluationState::default();340		state.with_stdlib();341		assert_eq!(342			state343				.parse_evaluate_raw(r#"std.assertEqual(std.base64("test"), "dGVzdA==")"#)344				.unwrap(),345			Val::Bool(true)346		);347	}348349	macro_rules! eval {350		($str: expr) => {351			EvaluationState::default()352				.with_stdlib()353				.parse_evaluate_raw($str)354				.unwrap()355		};356	}357	macro_rules! eval_json {358		($str: expr) => {{359			let evaluator = EvaluationState::default();360			evaluator.with_stdlib();361			let val = evaluator.parse_evaluate_raw($str).unwrap();362			evaluator.add_global("__tmp__to_yaml__".to_owned(), val);363			evaluator364				.parse_evaluate_raw("std.manifestJsonEx(__tmp__to_yaml__, \"\")")365				.unwrap()366				.try_cast_str("there should be json string")367				.unwrap()368				.clone()369				.replace("\n", "")370			}};371	}372373	/// Asserts given code returns `true`374	macro_rules! assert_eval {375		($str: expr) => {376			assert_eq!(eval!($str), Val::Bool(true))377		};378	}379380	/// Asserts given code returns `false`381	macro_rules! assert_eval_neg {382		($str: expr) => {383			assert_eq!(eval!($str), Val::Bool(false))384		};385	}386	macro_rules! assert_json {387		($str: expr, $out: expr) => {388			assert_eq!(eval_json!($str), $out.replace("\t", ""))389		};390	}391392	/// Sanity checking, before trusting to another tests393	#[test]394	fn equality_operator() {395		assert_eval!("2 == 2");396		assert_eval_neg!("2 != 2");397		assert_eval!("2 != 3");398		assert_eval_neg!("2 == 3");399		assert_eval!("'Hello' == 'Hello'");400		assert_eval_neg!("'Hello' != 'Hello'");401		assert_eval!("'Hello' != 'World'");402		assert_eval_neg!("'Hello' == 'World'");403	}404405	#[test]406	fn math_evaluation() {407		assert_eval!("2 + 2 * 2 == 6");408		assert_eval!("3 + (2 + 2 * 2) == 9");409	}410411	#[test]412	fn string_concat() {413		assert_eval!("'Hello' + 'World' == 'HelloWorld'");414		assert_eval!("'Hello' * 3 == 'HelloHelloHello'");415		assert_eval!("'Hello' + 'World' * 3 == 'HelloWorldWorldWorld'");416	}417418	#[test]419	fn faster_join() {420		assert_eval!("std.join([0,0], [[1,2],[3,4],[5,6]]) == [1,2,0,0,3,4,0,0,5,6]");421		assert_eval!("std.join(',', ['1','2','3','4']) == '1,2,3,4'");422	}423424	#[test]425	fn function_contexts() {426		assert_eval!(427			r#"428				local k = {429					t(name = self.h): [self.h, name],430					h: 3,431				};432				local f = {433					t: k.t(),434					h: 4,435				};436				f.t[0] == f.t[1]437			"#438		);439	}440441	#[test]442	fn local() {443		assert_eval!("local a = 2; local b = 3; a + b == 5");444		assert_eval!("local a = 1, b = a + 1; a + b == 3");445		assert_eval!("local a = 1; local a = 2; a == 2");446	}447448	#[test]449	fn object_lazyness() {450		assert_json!("local a = {a:error 'test'}; {}", r#"{}"#);451	}452453	#[test]454	fn object_inheritance() {455		assert_json!("{a: self.b} + {b:3}", r#"{"a": 3,"b": 3}"#);456	}457458	#[test]459	fn object_assertion_success() {460		eval!("{assert \"a\" in self} + {a:2}");461	}462463	#[test]464	fn object_assertion_error() {465		eval!("{assert \"a\" in self}");466	}467468	#[test]469	fn lazy_args() {470		eval!("local test(a) = 2; test(error '3')");471	}472473	#[test]474	fn tailstrict_args() {475		eval!("local test(a) = 2; test(error '3') tailstrict");476	}477478	#[test]479	fn no_binding_error() {480		eval!("a");481	}482483	#[test]484	fn test_object() {485		assert_json!("{a:2}", r#"{"a": 2}"#);486		assert_json!("{a:2+2}", r#"{"a": 4}"#);487		assert_json!("{a:2}+{b:2}", r#"{"a": 2,"b": 2}"#);488		assert_json!("{b:3}+{b:2}", r#"{"b": 2}"#);489		assert_json!("{b:3}+{b+:2}", r#"{"b": 5}"#);490		assert_json!("local test='a'; {[test]:2}", r#"{"a": 2}"#);491		assert_json!(492			r#"493				{494					name: "Alice",495					welcome: "Hello " + self.name + "!",496				}497			"#,498			r#"{"name": "Alice","welcome": "Hello Alice!"}"#499		);500		assert_json!(501			r#"502				{503					name: "Alice",504					welcome: "Hello " + self.name + "!",505				} + {506					name: "Bob"507				}508			"#,509			r#"{"name": "Bob","welcome": "Hello Bob!"}"#510		);511	}512513	#[test]514	fn functions() {515		assert_json!(r#"local a = function(b, c = 2) b + c; a(2)"#, "4");516		assert_json!(517			r#"local a = function(b, c = "Dear") b + c + d, d = "World"; a("Hello")"#,518			r#""HelloDearWorld""#519		);520	}521522	#[test]523	fn local_methods() {524		assert_json!(r#"local a(b, c = 2) = b + c; a(2)"#, "4");525		assert_json!(526			r#"local a(b, c = "Dear") = b + c + d, d = "World"; a("Hello")"#,527			r#""HelloDearWorld""#528		);529	}530531	#[test]532	fn object_locals() {533		assert_json!(r#"{local a = 3, b: a}"#, r#"{"b": 3}"#);534		assert_json!(r#"{local a = 3, local c = a, b: c}"#, r#"{"b": 3}"#);535		assert_json!(536			r#"{local a = function (b) {[b]:4}, test: a("test")}"#,537			r#"{"test": {"test": 4}}"#538		);539	}540541	#[test]542	fn object_comp() {543		assert_json!(544			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}"#,545			"{\"h1_2\": \"0a\",\"h1_3\": \"0a\",\"h1_4\": \"0a\",\"h2_3\": \"a1\",\"h2_4\": \"a1\",\"h3_2\": \"0a\",\"h3_4\": \"a1\"}"546		)547	}548549	#[test]550	fn direct_self() {551		println!(552			"{:#?}",553			eval!(554				r#"555					{556						local me = self,557						a: 3,558						b(): me.a,559					}560				"#561			)562		);563	}564565	#[test]566	fn indirect_self() {567		// `self` assigned to `me` was lost when being568		// referenced from field569		eval!(570			r#"{571				local me = self,572				a: 3,573				b: me.a,574			}.b"#575		);576	}577578	// We can't trust other tests (And official jsonnet testsuite), if assert is not working correctly579	#[test]580	fn std_assert_ok() {581		eval!("std.assertEqual(4.5 << 2, 16)");582	}583584	#[test]585	#[should_panic]586	fn std_assert_failure() {587		eval!("std.assertEqual(4.5 << 2, 15)");588	}589590	#[test]591	fn string_is_string() {592		assert_eq!(593			eval!("local arr = 'hello'; (!std.isArray(arr)) && (!std.isString(arr))"),594			Val::Bool(false)595		);596	}597598	#[test]599	fn base64_works() {600		assert_json!(r#"std.base64("test")"#, r#""dGVzdA==""#);601	}602603	#[test]604	fn utf8_chars() {605		assert_json!(606			r#"local c="😎";{c:std.codepoint(c),l:std.length(c)}"#,607			r#"{"c": 128526,"l": 1}"#608		)609	}610611	#[test]612	fn json() {613		assert_json!(614			r#"std.manifestJsonEx({a:3, b:4, c:6},"")"#,615			r#""{\n\"a\": 3,\n\"b\": 4,\n\"c\": 6\n}""#616		);617	}618619	#[test]620	fn test() {621		assert_json!(622			r#"[[a, b] for a in [1,2,3] for b in [4,5,6]]"#,623			"[[1,4],[1,5],[1,6],[2,4],[2,5],[2,6],[3,4],[3,5],[3,6]]"624		);625	}626627	#[test]628	fn sjsonnet() {629		eval!(630			r#"631			local x0 = {k: 1};632			local x1 = {k: x0.k + x0.k};633			local x2 = {k: x1.k + x1.k};634			local x3 = {k: x2.k + x2.k};635			local x4 = {k: x3.k + x3.k};636			local x5 = {k: x4.k + x4.k};637			local x6 = {k: x5.k + x5.k};638			local x7 = {k: x6.k + x6.k};639			local x8 = {k: x7.k + x7.k};640			local x9 = {k: x8.k + x8.k};641			local x10 = {k: x9.k + x9.k};642			local x11 = {k: x10.k + x10.k};643			local x12 = {k: x11.k + x11.k};644			local x13 = {k: x12.k + x12.k};645			local x14 = {k: x13.k + x13.k};646			local x15 = {k: x14.k + x14.k};647			local x16 = {k: x15.k + x15.k};648			local x17 = {k: x16.k + x16.k};649			local x18 = {k: x17.k + x17.k};650			local x19 = {k: x18.k + x18.k};651			local x20 = {k: x19.k + x19.k};652			local x21 = {k: x20.k + x20.k};653			x21.k654		"#655		);656	}657}
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 function;10mod import;11mod map;12mod obj;13mod val;1415pub use ctx::*;16pub use dynamic::*;17pub use error::*;18pub use evaluate::*;19pub use function::parse_function_call;20pub use import::*;21use jsonnet_parser::*;22pub use obj::*;23use std::{cell::RefCell, collections::HashMap, fmt::Debug, path::PathBuf, rc::Rc};24pub use val::*;2526type BindableFn = dyn Fn(Option<ObjValue>, Option<ObjValue>) -> Result<LazyVal>;27#[derive(Clone)]28pub enum LazyBinding {29	Bindable(Rc<BindableFn>),30	Bound(LazyVal),31}3233impl Debug for LazyBinding {34	fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {35		write!(f, "LazyBinding")36	}37}38impl LazyBinding {39	pub fn evaluate(&self, this: Option<ObjValue>, super_obj: Option<ObjValue>) -> Result<LazyVal> {40		match self {41			LazyBinding::Bindable(v) => v(this, super_obj),42			LazyBinding::Bound(v) => Ok(v.clone()),43		}44	}45}4647pub struct EvaluationSettings {48	pub max_stack_frames: usize,49	pub max_stack_trace_size: usize,50}51impl Default for EvaluationSettings {52	fn default() -> Self {53		EvaluationSettings {54			max_stack_frames: 200,55			max_stack_trace_size: 20,56		}57	}58}5960pub struct FileData(String, LocExpr, Option<Val>);61#[derive(Default)]62pub struct EvaluationStateInternals {63	/// Used for stack-overflows and stacktraces64	stack: RefCell<Vec<StackTraceElement>>,65	/// Contains file source codes and evaluated results for imports and pretty66	/// printing stacktraces67	files: RefCell<HashMap<PathBuf, FileData>>,68	str_files: RefCell<HashMap<PathBuf, String>>,69	globals: RefCell<HashMap<String, Val>>,7071	/// Values to use with std.extVar72	ext_vars: RefCell<HashMap<String, Val>>,7374	settings: EvaluationSettings,75	import_resolver: Box<dyn ImportResolver>,76}7778thread_local! {79	/// Contains state for currently executing file80	/// Global state is fine there81	pub(crate) static EVAL_STATE: RefCell<Option<EvaluationState>> = RefCell::new(None)82}83pub(crate) fn with_state<T>(f: impl FnOnce(&EvaluationState) -> T) -> T {84	EVAL_STATE.with(|s| f(s.borrow().as_ref().unwrap()))85}86pub(crate) fn create_error<T>(err: Error) -> Result<T> {87	with_state(|s| s.error(err))88}89pub(crate) fn push<T>(90	e: &Option<Rc<ExprLocation>>,91	comment: &str,92	f: impl FnOnce() -> Result<T>,93) -> Result<T> {94	if e.is_some() {95		with_state(|s| s.push(e.clone().unwrap(), comment.to_owned(), f))96	} else {97		f()98	}99}100101/// Maintains stack trace and import resolution102#[derive(Default, Clone)]103pub struct EvaluationState(Rc<EvaluationStateInternals>);104impl EvaluationState {105	pub fn new(settings: EvaluationSettings, import_resolver: Box<dyn ImportResolver>) -> Self {106		EvaluationState(Rc::new(EvaluationStateInternals {107			settings,108			import_resolver,109			..Default::default()110		}))111	}112	pub fn add_file(&self, name: PathBuf, code: String) -> std::result::Result<(), ParseError> {113		self.0.files.borrow_mut().insert(114			name.clone(),115			FileData(116				code.clone(),117				parse(118					&code,119					&ParserSettings {120						file_name: name,121						loc_data: true,122					},123				)?,124				None,125			),126		);127128		Ok(())129	}130	pub fn add_parsed_file(131		&self,132		name: PathBuf,133		code: String,134		parsed: LocExpr,135	) -> std::result::Result<(), ()> {136		self.0137			.files138			.borrow_mut()139			.insert(name, FileData(code, parsed, None));140141		Ok(())142	}143	pub fn get_source(&self, name: &PathBuf) -> Option<String> {144		let ro_map = self.0.files.borrow();145		ro_map.get(name).map(|value| value.0.clone())146	}147	pub fn evaluate_file(&self, name: &PathBuf) -> Result<Val> {148		self.run_in_state(|| {149			let expr: LocExpr = {150				let ro_map = self.0.files.borrow();151				let value = ro_map152					.get(name)153					.unwrap_or_else(|| panic!("file not added: {:?}", name));154				if value.2.is_some() {155					return Ok(value.2.clone().unwrap());156				}157				value.1.clone()158			};159			let value = evaluate(self.create_default_context()?, &expr)?;160			{161				self.0162					.files163					.borrow_mut()164					.get_mut(name)165					.unwrap()166					.2167					.replace(value.clone());168			}169			Ok(value)170		})171	}172	pub(crate) fn import_file(&self, from: &PathBuf, path: &PathBuf) -> Result<Val> {173		let file_path = self.0.import_resolver.resolve_file(from, path)?;174		{175			let files = self.0.files.borrow();176			if files.contains_key(&file_path) {177				return self.evaluate_file(&file_path);178			}179		}180		let contents = self.0.import_resolver.load_file_contents(&file_path)?;181		self.add_file(file_path.clone(), contents).map_err(|e| {182			create_error::<()>(Error::ImportSyntaxError(e))183				.err()184				.unwrap()185		})?;186		self.evaluate_file(&file_path)187	}188	pub(crate) fn import_file_str(&self, from: &PathBuf, path: &PathBuf) -> Result<String> {189		let path = self.0.import_resolver.resolve_file(from, path)?;190		if !self.0.str_files.borrow().contains_key(&path) {191			let file_str = self.0.import_resolver.load_file_contents(&path)?;192			self.0.str_files.borrow_mut().insert(path.clone(), file_str);193		}194		Ok(self.0.str_files.borrow().get(&path).cloned().unwrap())195	}196197	pub fn parse_evaluate_raw(&self, code: &str) -> Result<Val> {198		let parsed = parse(199			&code,200			&ParserSettings {201				file_name: PathBuf::from("raw.jsonnet"),202				loc_data: true,203			},204		)205		.unwrap();206		self.evaluate_raw(parsed)207	}208209	pub fn evaluate_raw(&self, code: LocExpr) -> Result<Val> {210		self.run_in_state(|| evaluate(self.create_default_context()?, &code))211	}212213	pub fn add_global(&self, name: String, value: Val) {214		self.0.globals.borrow_mut().insert(name, value);215	}216	pub fn add_ext_var(&self, name: String, value: Val) {217		self.0.ext_vars.borrow_mut().insert(name, value);218	}219220	pub fn with_stdlib(&self) -> &Self {221		self.run_in_state(|| {222			use jsonnet_stdlib::STDLIB_STR;223			if cfg!(feature = "serialized-stdlib") {224				self.add_parsed_file(225					PathBuf::from("std.jsonnet"),226					STDLIB_STR.to_owned(),227					bincode::deserialize(include_bytes!(concat!(228						env!("OUT_DIR"),229						"/stdlib.bincode"230					)))231					.expect("deserialize stdlib"),232				)233				.unwrap();234			} else {235				self.add_file(PathBuf::from("std.jsonnet"), STDLIB_STR.to_owned())236					.unwrap();237			}238			let val = self.evaluate_file(&PathBuf::from("std.jsonnet")).unwrap();239			self.add_global("std".to_owned(), val);240		});241		self242	}243244	pub fn create_default_context(&self) -> Result<Context> {245		let globals = self.0.globals.borrow();246		let mut new_bindings: HashMap<String, LazyBinding> = HashMap::new();247		for (name, value) in globals.iter() {248			new_bindings.insert(249				name.clone(),250				LazyBinding::Bound(resolved_lazy_val!(value.clone())),251			);252		}253		Context::new().extend_unbound(new_bindings, None, None, None)254	}255256	pub fn push<T>(257		&self,258		e: Rc<ExprLocation>,259		comment: String,260		f: impl FnOnce() -> Result<T>,261	) -> Result<T> {262		{263			let mut stack = self.0.stack.borrow_mut();264			if stack.len() > self.0.settings.max_stack_frames {265				drop(stack);266				return self.error(Error::StackOverflow);267			} else {268				stack.push(StackTraceElement(e, comment));269			}270		}271		let result = f();272		self.0.stack.borrow_mut().pop();273		result274	}275	pub fn print_stack_trace(&self) {276		for e in self.stack_trace().0 {277			println!("{:?} - {:?}", e.0, e.1)278		}279	}280	pub fn stack_trace(&self) -> StackTrace {281		StackTrace(282			self.0283				.stack284				.borrow()285				.iter()286				.rev()287				.take(self.0.settings.max_stack_trace_size)288				.cloned()289				.collect(),290		)291	}292	pub fn error<T>(&self, err: Error) -> Result<T> {293		Err(LocError(err, self.stack_trace()))294	}295296	fn run_in_state<T>(&self, f: impl FnOnce() -> T) -> T {297		EVAL_STATE.with(|v| {298			let has_state = v.borrow().is_some();299			if !has_state {300				v.borrow_mut().replace(self.clone());301			}302			let result = f();303			if !has_state {304				v.borrow_mut().take();305			}306			result307		})308	}309}310311#[cfg(test)]312pub mod tests {313	use super::Val;314	use crate::EvaluationState;315	use jsonnet_parser::*;316	use std::{path::PathBuf, rc::Rc};317318	#[test]319	fn eval_state_stacktrace() {320		let state = EvaluationState::default();321		state322			.push(323				Rc::new(ExprLocation(PathBuf::from("test1.jsonnet"), 10, 20)),324				"outer".to_owned(),325				|| {326					state.push(327						Rc::new(ExprLocation(PathBuf::from("test2.jsonnet"), 30, 40)),328						"inner".to_owned(),329						|| {330							state.print_stack_trace();331							Ok(())332						},333					)?;334					Ok(())335				},336			)337			.unwrap();338	}339340	#[test]341	fn eval_state_standard() {342		let state = EvaluationState::default();343		state.with_stdlib();344		assert_eq!(345			state346				.parse_evaluate_raw(r#"std.assertEqual(std.base64("test"), "dGVzdA==")"#)347				.unwrap(),348			Val::Bool(true)349		);350	}351352	macro_rules! eval {353		($str: expr) => {354			EvaluationState::default()355				.with_stdlib()356				.parse_evaluate_raw($str)357				.unwrap()358		};359	}360	macro_rules! eval_json {361		($str: expr) => {{362			let evaluator = EvaluationState::default();363			evaluator.with_stdlib();364			let val = evaluator.parse_evaluate_raw($str).unwrap();365			evaluator.add_global("__tmp__to_yaml__".to_owned(), val);366			evaluator367				.parse_evaluate_raw("std.manifestJsonEx(__tmp__to_yaml__, \"\")")368				.unwrap()369				.try_cast_str("there should be json string")370				.unwrap()371				.clone()372				.replace("\n", "")373			}};374	}375376	/// Asserts given code returns `true`377	macro_rules! assert_eval {378		($str: expr) => {379			assert_eq!(eval!($str), Val::Bool(true))380		};381	}382383	/// Asserts given code returns `false`384	macro_rules! assert_eval_neg {385		($str: expr) => {386			assert_eq!(eval!($str), Val::Bool(false))387		};388	}389	macro_rules! assert_json {390		($str: expr, $out: expr) => {391			assert_eq!(eval_json!($str), $out.replace("\t", ""))392		};393	}394395	/// Sanity checking, before trusting to another tests396	#[test]397	fn equality_operator() {398		assert_eval!("2 == 2");399		assert_eval_neg!("2 != 2");400		assert_eval!("2 != 3");401		assert_eval_neg!("2 == 3");402		assert_eval!("'Hello' == 'Hello'");403		assert_eval_neg!("'Hello' != 'Hello'");404		assert_eval!("'Hello' != 'World'");405		assert_eval_neg!("'Hello' == 'World'");406	}407408	#[test]409	fn math_evaluation() {410		assert_eval!("2 + 2 * 2 == 6");411		assert_eval!("3 + (2 + 2 * 2) == 9");412	}413414	#[test]415	fn string_concat() {416		assert_eval!("'Hello' + 'World' == 'HelloWorld'");417		assert_eval!("'Hello' * 3 == 'HelloHelloHello'");418		assert_eval!("'Hello' + 'World' * 3 == 'HelloWorldWorldWorld'");419	}420421	#[test]422	fn faster_join() {423		assert_eval!("std.join([0,0], [[1,2],[3,4],[5,6]]) == [1,2,0,0,3,4,0,0,5,6]");424		assert_eval!("std.join(',', ['1','2','3','4']) == '1,2,3,4'");425	}426427	#[test]428	fn function_contexts() {429		assert_eval!(430			r#"431				local k = {432					t(name = self.h): [self.h, name],433					h: 3,434				};435				local f = {436					t: k.t(),437					h: 4,438				};439				f.t[0] == f.t[1]440			"#441		);442	}443444	#[test]445	fn local() {446		assert_eval!("local a = 2; local b = 3; a + b == 5");447		assert_eval!("local a = 1, b = a + 1; a + b == 3");448		assert_eval!("local a = 1; local a = 2; a == 2");449	}450451	#[test]452	fn object_lazyness() {453		assert_json!("local a = {a:error 'test'}; {}", r#"{}"#);454	}455456	#[test]457	fn object_inheritance() {458		assert_json!("{a: self.b} + {b:3}", r#"{"a": 3,"b": 3}"#);459	}460461	#[test]462	fn object_assertion_success() {463		eval!("{assert \"a\" in self} + {a:2}");464	}465466	#[test]467	fn object_assertion_error() {468		eval!("{assert \"a\" in self}");469	}470471	#[test]472	fn lazy_args() {473		eval!("local test(a) = 2; test(error '3')");474	}475476	#[test]477	fn tailstrict_args() {478		eval!("local test(a) = 2; test(error '3') tailstrict");479	}480481	#[test]482	fn no_binding_error() {483		eval!("a");484	}485486	#[test]487	fn test_object() {488		assert_json!("{a:2}", r#"{"a": 2}"#);489		assert_json!("{a:2+2}", r#"{"a": 4}"#);490		assert_json!("{a:2}+{b:2}", r#"{"a": 2,"b": 2}"#);491		assert_json!("{b:3}+{b:2}", r#"{"b": 2}"#);492		assert_json!("{b:3}+{b+:2}", r#"{"b": 5}"#);493		assert_json!("local test='a'; {[test]:2}", r#"{"a": 2}"#);494		assert_json!(495			r#"496				{497					name: "Alice",498					welcome: "Hello " + self.name + "!",499				}500			"#,501			r#"{"name": "Alice","welcome": "Hello Alice!"}"#502		);503		assert_json!(504			r#"505				{506					name: "Alice",507					welcome: "Hello " + self.name + "!",508				} + {509					name: "Bob"510				}511			"#,512			r#"{"name": "Bob","welcome": "Hello Bob!"}"#513		);514	}515516	#[test]517	fn functions() {518		assert_json!(r#"local a = function(b, c = 2) b + c; a(2)"#, "4");519		assert_json!(520			r#"local a = function(b, c = "Dear") b + c + d, d = "World"; a("Hello")"#,521			r#""HelloDearWorld""#522		);523	}524525	#[test]526	fn local_methods() {527		assert_json!(r#"local a(b, c = 2) = b + c; a(2)"#, "4");528		assert_json!(529			r#"local a(b, c = "Dear") = b + c + d, d = "World"; a("Hello")"#,530			r#""HelloDearWorld""#531		);532	}533534	#[test]535	fn object_locals() {536		assert_json!(r#"{local a = 3, b: a}"#, r#"{"b": 3}"#);537		assert_json!(r#"{local a = 3, local c = a, b: c}"#, r#"{"b": 3}"#);538		assert_json!(539			r#"{local a = function (b) {[b]:4}, test: a("test")}"#,540			r#"{"test": {"test": 4}}"#541		);542	}543544	#[test]545	fn object_comp() {546		assert_json!(547			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}"#,548			"{\"h1_2\": \"0a\",\"h1_3\": \"0a\",\"h1_4\": \"0a\",\"h2_3\": \"a1\",\"h2_4\": \"a1\",\"h3_2\": \"0a\",\"h3_4\": \"a1\"}"549		)550	}551552	#[test]553	fn direct_self() {554		println!(555			"{:#?}",556			eval!(557				r#"558					{559						local me = self,560						a: 3,561						b(): me.a,562					}563				"#564			)565		);566	}567568	#[test]569	fn indirect_self() {570		// `self` assigned to `me` was lost when being571		// referenced from field572		eval!(573			r#"{574				local me = self,575				a: 3,576				b: me.a,577			}.b"#578		);579	}580581	// We can't trust other tests (And official jsonnet testsuite), if assert is not working correctly582	#[test]583	fn std_assert_ok() {584		eval!("std.assertEqual(4.5 << 2, 16)");585	}586587	#[test]588	#[should_panic]589	fn std_assert_failure() {590		eval!("std.assertEqual(4.5 << 2, 15)");591	}592593	#[test]594	fn string_is_string() {595		assert_eq!(596			eval!("local arr = 'hello'; (!std.isArray(arr)) && (!std.isString(arr))"),597			Val::Bool(false)598		);599	}600601	#[test]602	fn base64_works() {603		assert_json!(r#"std.base64("test")"#, r#""dGVzdA==""#);604	}605606	#[test]607	fn utf8_chars() {608		assert_json!(609			r#"local c="😎";{c:std.codepoint(c),l:std.length(c)}"#,610			r#"{"c": 128526,"l": 1}"#611		)612	}613614	#[test]615	fn json() {616		assert_json!(617			r#"std.manifestJsonEx({a:3, b:4, c:6},"")"#,618			r#""{\n\"a\": 3,\n\"b\": 4,\n\"c\": 6\n}""#619		);620	}621622	#[test]623	fn test() {624		assert_json!(625			r#"[[a, b] for a in [1,2,3] for b in [4,5,6]]"#,626			"[[1,4],[1,5],[1,6],[2,4],[2,5],[2,6],[3,4],[3,5],[3,6]]"627		);628	}629630	#[test]631	fn sjsonnet() {632		eval!(633			r#"634			local x0 = {k: 1};635			local x1 = {k: x0.k + x0.k};636			local x2 = {k: x1.k + x1.k};637			local x3 = {k: x2.k + x2.k};638			local x4 = {k: x3.k + x3.k};639			local x5 = {k: x4.k + x4.k};640			local x6 = {k: x5.k + x5.k};641			local x7 = {k: x6.k + x6.k};642			local x8 = {k: x7.k + x7.k};643			local x9 = {k: x8.k + x8.k};644			local x10 = {k: x9.k + x9.k};645			local x11 = {k: x10.k + x10.k};646			local x12 = {k: x11.k + x11.k};647			local x13 = {k: x12.k + x12.k};648			local x14 = {k: x13.k + x13.k};649			local x15 = {k: x14.k + x14.k};650			local x16 = {k: x15.k + x15.k};651			local x17 = {k: x16.k + x16.k};652			local x18 = {k: x17.k + x17.k};653			local x19 = {k: x18.k + x18.k};654			local x20 = {k: x19.k + x19.k};655			local x21 = {k: x20.k + x20.k};656			x21.k657		"#658		);659	}660}