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

difftreelog

source

crates/jsonnet-evaluator/src/lib.rs10.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>) -> Val26);27rc_fn_helper!(28	LazyBinding,29	lazy_binding,30	dyn Fn(Option<ObjValue>, Option<ObjValue>) -> LazyVal31);32rc_fn_helper!(FunctionRhs, function_rhs, dyn Fn(Context) -> Val);33rc_fn_helper!(34	FunctionDefault,35	function_default,36	dyn Fn(Context, LocExpr) -> Val37);3839#[derive(Default)]40pub struct EvaluationStateInternals {41	/// Used for stack-overflows and stacktraces42	stack: RefCell<Vec<(LocExpr, String)>>,43	/// Contains file source codes and evaluated results for imports and pretty printing stacktraces44	files: RefCell<HashMap<String, (String, LocExpr, Option<Val>)>>,45	globals: RefCell<HashMap<String, Val>>,46}4748#[derive(Default, Clone)]49pub struct EvaluationState(Rc<EvaluationStateInternals>);50impl EvaluationState {51	pub fn add_file(&self, name: String, code: String) -> Result<(), Box<dyn std::error::Error>> {52		self.0.files.borrow_mut().insert(53			name.clone(),54			(55				code.clone(),56				parse(57					&code,58					&ParserSettings {59						file_name: name.clone(),60						loc_data: true,61					},62				)?,63				None,64			),65		);6667		Ok(())68	}69	pub fn evaluate_file(&self, name: &str) -> Result<Val, Box<dyn std::error::Error>> {70		let expr: LocExpr = {71			let ro_map = self.0.files.borrow();72			let value = ro_map73				.get(name)74				.unwrap_or_else(|| panic!("file not added: {:?}", name));75			if value.2.is_some() {76				return Ok(value.2.clone().unwrap());77			}78			value.1.clone()79		};80		let value = evaluate(self.create_default_context(), self.clone(), &expr);81		{82			self.083				.files84				.borrow_mut()85				.get_mut(name)86				.unwrap()87				.288				.replace(value.clone());89		}90		Ok(value)91	}9293	pub fn parse_evaluate_raw(&self, code: &str) -> Val {94		let parsed = parse(95			&code,96			&ParserSettings {97				file_name: "raw.jsonnet".to_owned(),98				loc_data: true,99			},100		);101		evaluate(102			self.create_default_context(),103			self.clone(),104			&parsed.unwrap(),105		)106	}107108	pub fn add_stdlib(&self) {109		use jsonnet_stdlib::STDLIB_STR;110		self.add_file("std.jsonnet".to_owned(), STDLIB_STR.to_owned())111			.unwrap();112		let val = self.evaluate_file("std.jsonnet").unwrap();113		self.0.globals.borrow_mut().insert("std".to_owned(), val);114	}115116	pub fn create_default_context(&self) -> Context {117		let globals = self.0.globals.borrow();118		let mut new_bindings: HashMap<String, LazyBinding> = HashMap::new();119		for (name, value) in globals.iter() {120			new_bindings.insert(121				name.clone(),122				lazy_binding!(123					closure!(clone value, |_self, _super_obj| lazy_val!(closure!(clone value, ||value.clone())))124				),125			);126		}127		Context::new().extend(new_bindings, None, None, None)128	}129130	pub fn push<T>(&self, e: LocExpr, comment: String, f: impl FnOnce() -> T) -> T {131		self.0.stack.borrow_mut().push((e, comment));132		let result = f();133		self.0.stack.borrow_mut().pop();134		result135	}136	pub fn print_stack_trace(&self) {137		for e in self.stack_trace() {138			println!("{:?} - {:?}", e.0, e.1)139		}140	}141	pub fn stack_trace(&self) -> Vec<(LocExpr, String)> {142		self.0143			.stack144			.borrow()145			.iter()146			.rev()147			.map(|e| e.clone())148			.collect()149	}150}151152#[cfg(test)]153pub mod tests {154	use super::{evaluate, Context, Val};155	use crate::EvaluationState;156	use jsonnet_parser::*;157158	#[test]159	fn eval_state_stacktrace() {160		let state = EvaluationState::default();161		state.push(162			loc_expr!(Expr::Num(0.0), true, ("test1.jsonnet".to_owned(), 10, 20)),163			"outer".to_owned(),164			|| {165				state.push(166					loc_expr!(Expr::Num(0.0), true, ("test2.jsonnet".to_owned(), 30, 40)),167					"inner".to_owned(),168					|| state.print_stack_trace(),169				);170			},171		);172	}173174	#[test]175	fn eval_state_standard() {176		let state = EvaluationState::default();177		state.add_stdlib();178		assert_eq!(179			state.parse_evaluate_raw(r#"std.base64("test") == "dGVzdA==""#),180			Val::Bool(true)181		);182	}183184	macro_rules! eval {185		($str: expr) => {186			evaluate(187				Context::new(),188				EvaluationState::default(),189				&parse(190					$str,191					&ParserSettings {192						loc_data: true,193						file_name: "test.jsonnet".to_owned(),194					},195					)196				.unwrap(),197				)198		};199	}200201	macro_rules! eval_stdlib {202		($str: expr) => {{203			let std = "local std = ".to_owned() + jsonnet_stdlib::STDLIB_STR + ";";204			evaluate(205				Context::new(),206				EvaluationState::default(),207				&parse(208					&(std + $str),209					&ParserSettings {210						loc_data: true,211						file_name: "test.jsonnet".to_owned(),212					},213					)214				.unwrap(),215				)216			}};217	}218219	macro_rules! assert_eval {220		($str: expr) => {221			assert_eq!(222				evaluate(223					Context::new(),224					EvaluationState::default(),225					&parse(226						$str,227						&ParserSettings {228							loc_data: true,229							file_name: "test.jsonnet".to_owned(),230						}231						)232					.unwrap()233					),234				Val::Bool(true)235				)236		};237	}238	macro_rules! assert_json {239		($str: expr, $out: expr) => {240			assert_eq!(241				format!(242					"{}",243					evaluate(244						Context::new(),245						EvaluationState::default(),246						&parse(247							$str,248							&ParserSettings {249								loc_data: true,250								file_name: "test.jsonnet".to_owned(),251							}252						)253						.unwrap()254						)255					),256				$out257				)258		};259	}260	macro_rules! assert_json_stdlib {261		($str: expr, $out: expr) => {262			assert_eq!(format!("{}", eval_stdlib!($str)), $out)263		};264	}265	macro_rules! assert_eval_neg {266		($str: expr) => {267			assert_eq!(268				evaluate(269					Context::new(),270					EvaluationState::default(),271					&parse(272						$str,273						&ParserSettings {274							loc_data: true,275							file_name: "test.jsonnet".to_owned(),276						}277						)278					.unwrap()279					),280				Val::Bool(false)281				)282		};283	}284285	/// Sanity checking, before trusting to another tests286	#[test]287	fn equality_operator() {288		assert_eval!("2 == 2");289		assert_eval_neg!("2 != 2");290		assert_eval!("2 != 3");291		assert_eval_neg!("2 == 3");292		assert_eval!("'Hello' == 'Hello'");293		assert_eval_neg!("'Hello' != 'Hello'");294		assert_eval!("'Hello' != 'World'");295		assert_eval_neg!("'Hello' == 'World'");296	}297298	#[test]299	fn math_evaluation() {300		assert_eval!("2 + 2 * 2 == 6");301		assert_eval!("3 + (2 + 2 * 2) == 9");302	}303304	#[test]305	fn string_concat() {306		assert_eval!("'Hello' + 'World' == 'HelloWorld'");307		assert_eval!("'Hello' * 3 == 'HelloHelloHello'");308		assert_eval!("'Hello' + 'World' * 3 == 'HelloWorldWorldWorld'");309	}310311	#[test]312	fn local() {313		assert_eval!("local a = 2; local b = 3; a + b == 5");314		assert_eval!("local a = 1, b = a + 1; a + b == 3");315		assert_eval!("local a = 1; local a = 2; a == 2");316	}317318	#[test]319	fn object_lazyness() {320		assert_json!("local a = {a:error 'test'}; {}", r#"{}"#);321	}322323	#[test]324	fn object_inheritance() {325		assert_json!("{a: self.b} + {b:3}", r#"{"a":3,"b":3}"#);326	}327328	#[test]329	fn test_object() {330		assert_json!("{a:2}", r#"{"a":2}"#);331		assert_json!("{a:2+2}", r#"{"a":4}"#);332		assert_json!("{a:2}+{b:2}", r#"{"a":2,"b":2}"#);333		assert_json!("{b:3}+{b:2}", r#"{"b":2}"#);334		assert_json!("{b:3}+{b+:2}", r#"{"b":5}"#);335		assert_json!("local test='a'; {[test]:2}", r#"{"a":2}"#);336		assert_json!(337			r#"338				{339					name: "Alice",340					welcome: "Hello " + self.name + "!",341				}342			"#,343			r#"{"name":"Alice","welcome":"Hello Alice!"}"#344		);345		assert_json!(346			r#"347				{348					name: "Alice",349					welcome: "Hello " + self.name + "!",350				} + {351					name: "Bob"352				}353			"#,354			r#"{"name":"Bob","welcome":"Hello Bob!"}"#355		);356	}357358	#[test]359	fn functions() {360		assert_json!(r#"local a = function(b, c = 2) b + c; a(2)"#, "4");361		assert_json!(362			r#"local a = function(b, c = "Dear") b + c + d, d = "World"; a("Hello")"#,363			r#""HelloDearWorld""#364		);365	}366367	#[test]368	fn local_methods() {369		assert_json!(r#"local a(b, c = 2) = b + c; a(2)"#, "4");370		assert_json!(371			r#"local a(b, c = "Dear") = b + c + d, d = "World"; a("Hello")"#,372			r#""HelloDearWorld""#373		);374	}375376	#[test]377	fn object_locals() {378		assert_json!(r#"{local a = 3, b: a}"#, r#"{"b":3}"#);379		assert_json!(r#"{local a = 3, local c = a, b: c}"#, r#"{"b":3}"#);380		assert_json!(381			r#"{local a = function (b) {[b]:4}, test: a("test")}"#,382			r#"{"test":{"test":4}}"#383		);384	}385386	#[test]387	fn direct_self() {388		println!(389			"{:#?}",390			eval!(391				r#"392					{393						local me = self,394						a: 3,395						b(): me.a,396					}397				"#398			)399		);400	}401402	#[test]403	fn indirect_self() {404		// `self` assigned to `me` was lost when being405		// referenced from field406		eval_stdlib!(407			r#"{408				local me = self,409				a: 3,410				b: me.a,411			}.b"#412		);413	}414415	// We can't trust other tests (And official jsonnet testsuite), if assert is not working correctly416	#[test]417	fn std_assert_ok() {418		eval_stdlib!("std.assertEqual(4.5 << 2, 16)");419	}420421	#[test]422	#[should_panic]423	fn std_assert_failure() {424		eval_stdlib!("std.assertEqual(4.5 << 2, 15)");425	}426427	#[test]428	fn string_is_string() {429		assert_eq!(430			eval_stdlib!("local arr = 'hello'; (!std.isArray(arr)) && (!std.isString(arr))"),431			Val::Bool(false)432		);433	}434435	#[test]436	fn base64_works() {437		assert_json_stdlib!(r#"std.base64("test")"#, r#""dGVzdA==""#);438	}439440	#[test]441	fn utf8_chars() {442		assert_json_stdlib!(443			r#"local c="😎";{c:std.codepoint(c),l:std.length(c)}"#,444			r#"{"c":128526,"l":1}"#445		)446	}447448	#[test]449	fn json() {450		assert_json_stdlib!(451			r#"std.manifestJsonEx({a:3, b:4, c:6},"")"#,452			r#""{\n"a": 3,\n"b": 4,\n"c": 6\n}""#453		);454	}455456	#[test]457	fn test() {458		assert_json_stdlib!(459			r#"[[a, b] for a in [1,2,3] for b in [4,5,6]]"#,460			"[[1,4],[1,5],[1,6],[2,4],[2,5],[2,6],[3,4],[3,5],[3,6]]"461		);462	}463464	#[test]465	fn sjsonnet() {466		eval!(467			r#"468			local x0 = {k: 1};469			local x1 = {k: x0.k + x0.k};470			local x2 = {k: x1.k + x1.k};471			local x3 = {k: x2.k + x2.k};472			local x4 = {k: x3.k + x3.k};473			local x5 = {k: x4.k + x4.k};474			local x6 = {k: x5.k + x5.k};475			local x7 = {k: x6.k + x6.k};476			local x8 = {k: x7.k + x7.k};477			local x9 = {k: x8.k + x8.k};478			local x10 = {k: x9.k + x9.k};479			local x11 = {k: x10.k + x10.k};480			local x12 = {k: x11.k + x11.k};481			local x13 = {k: x12.k + x12.k};482			local x14 = {k: x13.k + x13.k};483			local x15 = {k: x14.k + x14.k};484			local x16 = {k: x15.k + x15.k};485			local x17 = {k: x16.k + x16.k};486			local x18 = {k: x17.k + x17.k};487			local x19 = {k: x18.k + x18.k};488			local x20 = {k: x19.k + x19.k};489			local x21 = {k: x20.k + x20.k};490			x21.k491		"#492		);493	}494}