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

difftreelog

source

crates/jsonnet-evaluator/src/lib.rs14.9 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 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}