git.delta.rocks / jrsonnet / refs/commits / 30ce98effbb6

difftreelog

source

crates/jsonnet-evaluator/src/lib.rs12.0 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 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_global(&self, name: String, value: Val) {149		self.0.globals.borrow_mut().insert(name, value);150	}151152	pub fn add_stdlib(&self) {153		self.begin_state();154		use jsonnet_stdlib::STDLIB_STR;155		if cfg!(feature = "serialized-stdlib") {156			self.add_parsed_file(157				"std.jsonnet".to_owned(),158				STDLIB_STR.to_owned(),159				bincode::deserialize(include_bytes!(concat!(env!("OUT_DIR"), "/stdlib.bincode")))160					.expect("deserialize stdlib"),161			)162			.unwrap();163		} else {164			self.add_file("std.jsonnet".to_owned(), STDLIB_STR.to_owned())165				.unwrap();166		}167		let val = self.evaluate_file("std.jsonnet").unwrap();168		self.add_global("std".to_owned(), val);169		self.end_state();170	}171172	pub fn create_default_context(&self) -> Result<Context> {173		let globals = self.0.globals.borrow();174		let mut new_bindings: HashMap<String, LazyBinding> = HashMap::new();175		for (name, value) in globals.iter() {176			new_bindings.insert(177				name.clone(),178				lazy_binding!(179					closure!(clone value, |_self, _super_obj| Ok(lazy_val!(closure!(clone value, ||Ok(value.clone())))))180				),181			);182		}183		Context::new().extend(new_bindings, None, None, None)184	}185186	pub fn push<T>(&self, e: LocExpr, comment: String, f: impl FnOnce() -> T) -> T {187		self.0188			.stack189			.borrow_mut()190			.push(StackTraceElement(e, comment));191		let result = f();192		self.0.stack.borrow_mut().pop();193		result194	}195	pub fn print_stack_trace(&self) {196		for e in self.stack_trace().0 {197			println!("{:?} - {:?}", e.0, e.1)198		}199	}200	pub fn stack_trace(&self) -> StackTrace {201		StackTrace(self.0.stack.borrow().iter().rev().cloned().collect())202	}203	pub fn error<T>(&self, err: Error) -> Result<T> {204		Err(LocError(err, self.stack_trace()))205	}206207	fn begin_state(&self) {208		EVAL_STATE.with(|v| v.borrow_mut().replace(self.clone()));209	}210	fn end_state(&self) {211		EVAL_STATE.with(|v| v.borrow_mut().take());212	}213}214215#[cfg(test)]216pub mod tests {217	use super::Val;218	use crate::EvaluationState;219	use jsonnet_parser::*;220221	#[test]222	fn eval_state_stacktrace() {223		let state = EvaluationState::default();224		state.push(225			loc_expr!(Expr::Num(0.0), true, ("test1.jsonnet".to_owned(), 10, 20)),226			"outer".to_owned(),227			|| {228				state.push(229					loc_expr!(Expr::Num(0.0), true, ("test2.jsonnet".to_owned(), 30, 40)),230					"inner".to_owned(),231					|| state.print_stack_trace(),232				);233			},234		);235	}236237	#[test]238	fn eval_state_standard() {239		let state = EvaluationState::default();240		state.add_stdlib();241		assert_eq!(242			state243				.parse_evaluate_raw(r#"std.assertEqual(std.base64("test"), "dGVzdA==w")"#)244				.unwrap(),245			Val::Bool(true)246		);247	}248249	macro_rules! eval {250		($str: expr) => {251			evaluate(252				Context::new(),253				EvaluationState::default(),254				&parse(255					$str,256					&ParserSettings {257						loc_data: true,258						file_name: "test.jsonnet".to_owned(),259					},260					)261				.unwrap(),262				)263		};264	}265266	macro_rules! eval_stdlib {267		($str: expr) => {{268			let std = "local std = ".to_owned() + jsonnet_stdlib::STDLIB_STR + ";";269			evaluate(270				Context::new(),271				EvaluationState::default(),272				&parse(273					&(std + $str),274					&ParserSettings {275						loc_data: true,276						file_name: "test.jsonnet".to_owned(),277					},278					)279				.unwrap(),280				)281			}};282	}283284	macro_rules! assert_eval {285		($str: expr) => {286			assert_eq!(287				evaluate(288					Context::new(),289					EvaluationState::default(),290					&parse(291						$str,292						&ParserSettings {293							loc_data: true,294							file_name: "test.jsonnet".to_owned(),295						}296						)297					.unwrap()298					),299				Val::Bool(true)300				)301		};302	}303	macro_rules! assert_json {304		($str: expr, $out: expr) => {305			assert_eq!(306				format!(307					"{}",308					evaluate(309						Context::new(),310						EvaluationState::default(),311						&parse(312							$str,313							&ParserSettings {314								loc_data: true,315								file_name: "test.jsonnet".to_owned(),316							}317						)318						.unwrap()319						)320					),321				$out322				)323		};324	}325	macro_rules! assert_json_stdlib {326		($str: expr, $out: expr) => {327			assert_eq!(format!("{}", eval_stdlib!($str)), $out)328		};329	}330	macro_rules! assert_eval_neg {331		($str: expr) => {332			assert_eq!(333				evaluate(334					Context::new(),335					EvaluationState::default(),336					&parse(337						$str,338						&ParserSettings {339							loc_data: true,340							file_name: "test.jsonnet".to_owned(),341						}342						)343					.unwrap()344					),345				Val::Bool(false)346				)347		};348	}349350	/*351	/// Sanity checking, before trusting to another tests352	#[test]353	fn equality_operator() {354		assert_eval!("2 == 2");355		assert_eval_neg!("2 != 2");356		assert_eval!("2 != 3");357		assert_eval_neg!("2 == 3");358		assert_eval!("'Hello' == 'Hello'");359		assert_eval_neg!("'Hello' != 'Hello'");360		assert_eval!("'Hello' != 'World'");361		assert_eval_neg!("'Hello' == 'World'");362	}363364	#[test]365	fn math_evaluation() {366		assert_eval!("2 + 2 * 2 == 6");367		assert_eval!("3 + (2 + 2 * 2) == 9");368	}369370	#[test]371	fn string_concat() {372		assert_eval!("'Hello' + 'World' == 'HelloWorld'");373		assert_eval!("'Hello' * 3 == 'HelloHelloHello'");374		assert_eval!("'Hello' + 'World' * 3 == 'HelloWorldWorldWorld'");375	}376377	#[test]378	fn local() {379		assert_eval!("local a = 2; local b = 3; a + b == 5");380		assert_eval!("local a = 1, b = a + 1; a + b == 3");381		assert_eval!("local a = 1; local a = 2; a == 2");382	}383384	#[test]385	fn object_lazyness() {386		assert_json!("local a = {a:error 'test'}; {}", r#"{}"#);387	}388389	#[test]390	fn object_inheritance() {391		assert_json!("{a: self.b} + {b:3}", r#"{"a":3,"b":3}"#);392	}393394	#[test]395	fn test_object() {396		assert_json!("{a:2}", r#"{"a":2}"#);397		assert_json!("{a:2+2}", r#"{"a":4}"#);398		assert_json!("{a:2}+{b:2}", r#"{"a":2,"b":2}"#);399		assert_json!("{b:3}+{b:2}", r#"{"b":2}"#);400		assert_json!("{b:3}+{b+:2}", r#"{"b":5}"#);401		assert_json!("local test='a'; {[test]:2}", r#"{"a":2}"#);402		assert_json!(403			r#"404				{405					name: "Alice",406					welcome: "Hello " + self.name + "!",407				}408			"#,409			r#"{"name":"Alice","welcome":"Hello Alice!"}"#410		);411		assert_json!(412			r#"413				{414					name: "Alice",415					welcome: "Hello " + self.name + "!",416				} + {417					name: "Bob"418				}419			"#,420			r#"{"name":"Bob","welcome":"Hello Bob!"}"#421		);422	}423424	#[test]425	fn functions() {426		assert_json!(r#"local a = function(b, c = 2) b + c; a(2)"#, "4");427		assert_json!(428			r#"local a = function(b, c = "Dear") b + c + d, d = "World"; a("Hello")"#,429			r#""HelloDearWorld""#430		);431	}432433	#[test]434	fn local_methods() {435		assert_json!(r#"local a(b, c = 2) = b + c; a(2)"#, "4");436		assert_json!(437			r#"local a(b, c = "Dear") = b + c + d, d = "World"; a("Hello")"#,438			r#""HelloDearWorld""#439		);440	}441442	#[test]443	fn object_locals() {444		assert_json!(r#"{local a = 3, b: a}"#, r#"{"b":3}"#);445		assert_json!(r#"{local a = 3, local c = a, b: c}"#, r#"{"b":3}"#);446		assert_json!(447			r#"{local a = function (b) {[b]:4}, test: a("test")}"#,448			r#"{"test":{"test":4}}"#449		);450	}451452	#[test]453	fn direct_self() {454		println!(455			"{:#?}",456			eval!(457				r#"458					{459						local me = self,460						a: 3,461						b(): me.a,462					}463				"#464			)465		);466	}467468	#[test]469	fn indirect_self() {470		// `self` assigned to `me` was lost when being471		// referenced from field472		eval_stdlib!(473			r#"{474				local me = self,475				a: 3,476				b: me.a,477			}.b"#478		);479	}480481	// We can't trust other tests (And official jsonnet testsuite), if assert is not working correctly482	#[test]483	fn std_assert_ok() {484		eval_stdlib!("std.assertEqual(4.5 << 2, 16)");485	}486487	#[test]488	#[should_panic]489	fn std_assert_failure() {490		eval_stdlib!("std.assertEqual(4.5 << 2, 15)");491	}492493	#[test]494	fn string_is_string() {495		assert_eq!(496			eval_stdlib!("local arr = 'hello'; (!std.isArray(arr)) && (!std.isString(arr))"),497			Val::Bool(false)498		);499	}500501	#[test]502	fn base64_works() {503		assert_json_stdlib!(r#"std.base64("test")"#, r#""dGVzdA==""#);504	}505506	#[test]507	fn utf8_chars() {508		assert_json_stdlib!(509			r#"local c="😎";{c:std.codepoint(c),l:std.length(c)}"#,510			r#"{"c":128526,"l":1}"#511		)512	}513514	#[test]515	fn json() {516		assert_json_stdlib!(517			r#"std.manifestJsonEx({a:3, b:4, c:6},"")"#,518			r#""{\n"a": 3,\n"b": 4,\n"c": 6\n}""#519		);520	}521522	#[test]523	fn test() {524		assert_json_stdlib!(525			r#"[[a, b] for a in [1,2,3] for b in [4,5,6]]"#,526			"[[1,4],[1,5],[1,6],[2,4],[2,5],[2,6],[3,4],[3,5],[3,6]]"527		);528	}529530	#[test]531	fn sjsonnet() {532		eval!(533			r#"534			local x0 = {k: 1};535			local x1 = {k: x0.k + x0.k};536			local x2 = {k: x1.k + x1.k};537			local x3 = {k: x2.k + x2.k};538			local x4 = {k: x3.k + x3.k};539			local x5 = {k: x4.k + x4.k};540			local x6 = {k: x5.k + x5.k};541			local x7 = {k: x6.k + x6.k};542			local x8 = {k: x7.k + x7.k};543			local x9 = {k: x8.k + x8.k};544			local x10 = {k: x9.k + x9.k};545			local x11 = {k: x10.k + x10.k};546			local x12 = {k: x11.k + x11.k};547			local x13 = {k: x12.k + x12.k};548			local x14 = {k: x13.k + x13.k};549			local x15 = {k: x14.k + x14.k};550			local x16 = {k: x15.k + x15.k};551			local x17 = {k: x16.k + x16.k};552			local x18 = {k: x17.k + x17.k};553			local x19 = {k: x18.k + x18.k};554			local x20 = {k: x19.k + x19.k};555			local x21 = {k: x20.k + x20.k};556			x21.k557		"#558		);559	}560	*/561}