git.delta.rocks / jrsonnet / refs/commits / 3302a3dd316f

difftreelog

source

crates/jsonnet-evaluator/src/lib.rs11.4 KiBsourcehistory
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 pretty printing stacktraces45	files: RefCell<HashMap<String, FileData>>,46	globals: RefCell<HashMap<String, Val>>,47}4849thread_local! {50	pub static EVAL_STATE: RefCell<Option<EvaluationState>> = RefCell::new(None)51}52pub(crate) fn with_state<T>(f: impl FnOnce(&EvaluationState) -> T) -> T {53	EVAL_STATE.with(|s| f(s.borrow().as_ref().unwrap()))54}55pub(crate) fn create_error<T>(err: Error) -> Result<T> {56	with_state(|s| s.error(err))57}58pub(crate) fn push<T>(e: LocExpr, comment: String, f: impl FnOnce() -> T) -> T {59	with_state(|s| s.push(e, comment, f))60}6162#[derive(Default, Clone)]63pub struct EvaluationState(Rc<EvaluationStateInternals>);64impl EvaluationState {65	pub fn add_file(66		&self,67		name: String,68		code: String,69	) -> std::result::Result<(), Box<dyn std::error::Error>> {70		self.0.files.borrow_mut().insert(71			name.clone(),72			FileData(73				code.clone(),74				parse(75					&code,76					&ParserSettings {77						file_name: name,78						loc_data: true,79					},80				)?,81				None,82			),83		);8485		Ok(())86	}87	pub fn get_source(&self, name: &str) -> String {88		let ro_map = self.0.files.borrow();89		let value = ro_map90			.get(name)91			.unwrap_or_else(|| panic!("file not added: {:?}", name));92		value.0.clone()93	}94	pub fn evaluate_file(&self, name: &str) -> Result<Val> {95		self.begin_state();96		let expr: LocExpr = {97			let ro_map = self.0.files.borrow();98			let value = ro_map99				.get(name)100				.unwrap_or_else(|| panic!("file not added: {:?}", name));101			if value.2.is_some() {102				return Ok(value.2.clone().unwrap());103			}104			value.1.clone()105		};106		let value = evaluate(self.create_default_context()?, &expr)?;107		{108			self.0109				.files110				.borrow_mut()111				.get_mut(name)112				.unwrap()113				.2114				.replace(value.clone());115		}116		self.end_state();117		Ok(value)118	}119120	pub fn parse_evaluate_raw(&self, code: &str) -> Result<Val> {121		let parsed = parse(122			&code,123			&ParserSettings {124				file_name: "raw.jsonnet".to_owned(),125				loc_data: true,126			},127		);128		self.begin_state();129		let value = evaluate(self.create_default_context()?, &parsed.unwrap());130		self.end_state();131		value132	}133134	pub fn add_stdlib(&self) {135		self.begin_state();136		use jsonnet_stdlib::STDLIB_STR;137		self.add_file("std.jsonnet".to_owned(), STDLIB_STR.to_owned())138			.unwrap();139		let val = self.evaluate_file("std.jsonnet").unwrap();140		self.0.globals.borrow_mut().insert("std".to_owned(), val);141		self.end_state();142	}143144	pub fn create_default_context(&self) -> Result<Context> {145		let globals = self.0.globals.borrow();146		let mut new_bindings: HashMap<String, LazyBinding> = HashMap::new();147		for (name, value) in globals.iter() {148			new_bindings.insert(149				name.clone(),150				lazy_binding!(151					closure!(clone value, |_self, _super_obj| Ok(lazy_val!(closure!(clone value, ||Ok(value.clone())))))152				),153			);154		}155		Context::new().extend(new_bindings, None, None, None)156	}157158	pub fn push<T>(&self, e: LocExpr, comment: String, f: impl FnOnce() -> T) -> T {159		self.0160			.stack161			.borrow_mut()162			.push(StackTraceElement(e, comment));163		let result = f();164		self.0.stack.borrow_mut().pop();165		result166	}167	pub fn print_stack_trace(&self) {168		for e in self.stack_trace().0 {169			println!("{:?} - {:?}", e.0, e.1)170		}171	}172	pub fn stack_trace(&self) -> StackTrace {173		StackTrace(self.0.stack.borrow().iter().rev().cloned().collect())174	}175	pub fn error<T>(&self, err: Error) -> Result<T> {176		Err(LocError(err, self.stack_trace()))177	}178179	fn begin_state(&self) {180		EVAL_STATE.with(|v| v.borrow_mut().replace(self.clone()));181	}182	fn end_state(&self) {183		EVAL_STATE.with(|v| v.borrow_mut().take());184	}185}186187#[cfg(test)]188pub mod tests {189	use super::Val;190	use crate::EvaluationState;191	use jsonnet_parser::*;192193	#[test]194	fn eval_state_stacktrace() {195		let state = EvaluationState::default();196		state.push(197			loc_expr!(Expr::Num(0.0), true, ("test1.jsonnet".to_owned(), 10, 20)),198			"outer".to_owned(),199			|| {200				state.push(201					loc_expr!(Expr::Num(0.0), true, ("test2.jsonnet".to_owned(), 30, 40)),202					"inner".to_owned(),203					|| state.print_stack_trace(),204				);205			},206		);207	}208209	#[test]210	fn eval_state_standard() {211		let state = EvaluationState::default();212		state.add_stdlib();213		assert_eq!(214			state215				.parse_evaluate_raw(r#"std.assertEqual(std.base64("test"), "dGVzdA==w")"#)216				.unwrap(),217			Val::Bool(true)218		);219	}220221	macro_rules! eval {222		($str: expr) => {223			evaluate(224				Context::new(),225				EvaluationState::default(),226				&parse(227					$str,228					&ParserSettings {229						loc_data: true,230						file_name: "test.jsonnet".to_owned(),231					},232					)233				.unwrap(),234				)235		};236	}237238	macro_rules! eval_stdlib {239		($str: expr) => {{240			let std = "local std = ".to_owned() + jsonnet_stdlib::STDLIB_STR + ";";241			evaluate(242				Context::new(),243				EvaluationState::default(),244				&parse(245					&(std + $str),246					&ParserSettings {247						loc_data: true,248						file_name: "test.jsonnet".to_owned(),249					},250					)251				.unwrap(),252				)253			}};254	}255256	macro_rules! assert_eval {257		($str: expr) => {258			assert_eq!(259				evaluate(260					Context::new(),261					EvaluationState::default(),262					&parse(263						$str,264						&ParserSettings {265							loc_data: true,266							file_name: "test.jsonnet".to_owned(),267						}268						)269					.unwrap()270					),271				Val::Bool(true)272				)273		};274	}275	macro_rules! assert_json {276		($str: expr, $out: expr) => {277			assert_eq!(278				format!(279					"{}",280					evaluate(281						Context::new(),282						EvaluationState::default(),283						&parse(284							$str,285							&ParserSettings {286								loc_data: true,287								file_name: "test.jsonnet".to_owned(),288							}289						)290						.unwrap()291						)292					),293				$out294				)295		};296	}297	macro_rules! assert_json_stdlib {298		($str: expr, $out: expr) => {299			assert_eq!(format!("{}", eval_stdlib!($str)), $out)300		};301	}302	macro_rules! assert_eval_neg {303		($str: expr) => {304			assert_eq!(305				evaluate(306					Context::new(),307					EvaluationState::default(),308					&parse(309						$str,310						&ParserSettings {311							loc_data: true,312							file_name: "test.jsonnet".to_owned(),313						}314						)315					.unwrap()316					),317				Val::Bool(false)318				)319		};320	}321322	/*323	/// Sanity checking, before trusting to another tests324	#[test]325	fn equality_operator() {326		assert_eval!("2 == 2");327		assert_eval_neg!("2 != 2");328		assert_eval!("2 != 3");329		assert_eval_neg!("2 == 3");330		assert_eval!("'Hello' == 'Hello'");331		assert_eval_neg!("'Hello' != 'Hello'");332		assert_eval!("'Hello' != 'World'");333		assert_eval_neg!("'Hello' == 'World'");334	}335336	#[test]337	fn math_evaluation() {338		assert_eval!("2 + 2 * 2 == 6");339		assert_eval!("3 + (2 + 2 * 2) == 9");340	}341342	#[test]343	fn string_concat() {344		assert_eval!("'Hello' + 'World' == 'HelloWorld'");345		assert_eval!("'Hello' * 3 == 'HelloHelloHello'");346		assert_eval!("'Hello' + 'World' * 3 == 'HelloWorldWorldWorld'");347	}348349	#[test]350	fn local() {351		assert_eval!("local a = 2; local b = 3; a + b == 5");352		assert_eval!("local a = 1, b = a + 1; a + b == 3");353		assert_eval!("local a = 1; local a = 2; a == 2");354	}355356	#[test]357	fn object_lazyness() {358		assert_json!("local a = {a:error 'test'}; {}", r#"{}"#);359	}360361	#[test]362	fn object_inheritance() {363		assert_json!("{a: self.b} + {b:3}", r#"{"a":3,"b":3}"#);364	}365366	#[test]367	fn test_object() {368		assert_json!("{a:2}", r#"{"a":2}"#);369		assert_json!("{a:2+2}", r#"{"a":4}"#);370		assert_json!("{a:2}+{b:2}", r#"{"a":2,"b":2}"#);371		assert_json!("{b:3}+{b:2}", r#"{"b":2}"#);372		assert_json!("{b:3}+{b+:2}", r#"{"b":5}"#);373		assert_json!("local test='a'; {[test]:2}", r#"{"a":2}"#);374		assert_json!(375			r#"376				{377					name: "Alice",378					welcome: "Hello " + self.name + "!",379				}380			"#,381			r#"{"name":"Alice","welcome":"Hello Alice!"}"#382		);383		assert_json!(384			r#"385				{386					name: "Alice",387					welcome: "Hello " + self.name + "!",388				} + {389					name: "Bob"390				}391			"#,392			r#"{"name":"Bob","welcome":"Hello Bob!"}"#393		);394	}395396	#[test]397	fn functions() {398		assert_json!(r#"local a = function(b, c = 2) b + c; a(2)"#, "4");399		assert_json!(400			r#"local a = function(b, c = "Dear") b + c + d, d = "World"; a("Hello")"#,401			r#""HelloDearWorld""#402		);403	}404405	#[test]406	fn local_methods() {407		assert_json!(r#"local a(b, c = 2) = b + c; a(2)"#, "4");408		assert_json!(409			r#"local a(b, c = "Dear") = b + c + d, d = "World"; a("Hello")"#,410			r#""HelloDearWorld""#411		);412	}413414	#[test]415	fn object_locals() {416		assert_json!(r#"{local a = 3, b: a}"#, r#"{"b":3}"#);417		assert_json!(r#"{local a = 3, local c = a, b: c}"#, r#"{"b":3}"#);418		assert_json!(419			r#"{local a = function (b) {[b]:4}, test: a("test")}"#,420			r#"{"test":{"test":4}}"#421		);422	}423424	#[test]425	fn direct_self() {426		println!(427			"{:#?}",428			eval!(429				r#"430					{431						local me = self,432						a: 3,433						b(): me.a,434					}435				"#436			)437		);438	}439440	#[test]441	fn indirect_self() {442		// `self` assigned to `me` was lost when being443		// referenced from field444		eval_stdlib!(445			r#"{446				local me = self,447				a: 3,448				b: me.a,449			}.b"#450		);451	}452453	// We can't trust other tests (And official jsonnet testsuite), if assert is not working correctly454	#[test]455	fn std_assert_ok() {456		eval_stdlib!("std.assertEqual(4.5 << 2, 16)");457	}458459	#[test]460	#[should_panic]461	fn std_assert_failure() {462		eval_stdlib!("std.assertEqual(4.5 << 2, 15)");463	}464465	#[test]466	fn string_is_string() {467		assert_eq!(468			eval_stdlib!("local arr = 'hello'; (!std.isArray(arr)) && (!std.isString(arr))"),469			Val::Bool(false)470		);471	}472473	#[test]474	fn base64_works() {475		assert_json_stdlib!(r#"std.base64("test")"#, r#""dGVzdA==""#);476	}477478	#[test]479	fn utf8_chars() {480		assert_json_stdlib!(481			r#"local c="😎";{c:std.codepoint(c),l:std.length(c)}"#,482			r#"{"c":128526,"l":1}"#483		)484	}485486	#[test]487	fn json() {488		assert_json_stdlib!(489			r#"std.manifestJsonEx({a:3, b:4, c:6},"")"#,490			r#""{\n"a": 3,\n"b": 4,\n"c": 6\n}""#491		);492	}493494	#[test]495	fn test() {496		assert_json_stdlib!(497			r#"[[a, b] for a in [1,2,3] for b in [4,5,6]]"#,498			"[[1,4],[1,5],[1,6],[2,4],[2,5],[2,6],[3,4],[3,5],[3,6]]"499		);500	}501502	#[test]503	fn sjsonnet() {504		eval!(505			r#"506			local x0 = {k: 1};507			local x1 = {k: x0.k + x0.k};508			local x2 = {k: x1.k + x1.k};509			local x3 = {k: x2.k + x2.k};510			local x4 = {k: x3.k + x3.k};511			local x5 = {k: x4.k + x4.k};512			local x6 = {k: x5.k + x5.k};513			local x7 = {k: x6.k + x6.k};514			local x8 = {k: x7.k + x7.k};515			local x9 = {k: x8.k + x8.k};516			local x10 = {k: x9.k + x9.k};517			local x11 = {k: x10.k + x10.k};518			local x12 = {k: x11.k + x11.k};519			local x13 = {k: x12.k + x12.k};520			local x14 = {k: x13.k + x13.k};521			local x15 = {k: x14.k + x14.k};522			local x16 = {k: x15.k + x15.k};523			local x17 = {k: x16.k + x16.k};524			local x18 = {k: x17.k + x17.k};525			local x19 = {k: x18.k + x18.k};526			local x20 = {k: x19.k + x19.k};527			local x21 = {k: x20.k + x20.k};528			x21.k529		"#530		);531	}532	*/533}