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

difftreelog

source

crates/jsonnet-evaluator/src/lib.rs14.8 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, Rc<str>>>,69	globals: RefCell<HashMap<Rc<str>, Val>>,7071	/// Values to use with std.extVar72	ext_vars: RefCell<HashMap<Rc<str>, 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<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: Rc::new(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<Rc<str>> {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.0193				.str_files194				.borrow_mut()195				.insert(path.clone(), file_str.into());196		}197		Ok(self.0.str_files.borrow().get(&path).cloned().unwrap())198	}199200	pub fn parse_evaluate_raw(&self, code: &str) -> Result<Val> {201		let parsed = parse(202			&code,203			&ParserSettings {204				file_name: Rc::new(PathBuf::from("raw.jsonnet")),205				loc_data: true,206			},207		)208		.unwrap();209		self.evaluate_raw(parsed)210	}211212	pub fn evaluate_raw(&self, code: LocExpr) -> Result<Val> {213		self.run_in_state(|| evaluate(self.create_default_context()?, &code))214	}215216	pub fn add_global(&self, name: Rc<str>, value: Val) {217		self.0.globals.borrow_mut().insert(name, value);218	}219	pub fn add_ext_var(&self, name: Rc<str>, value: Val) {220		self.0.ext_vars.borrow_mut().insert(name, value);221	}222223	pub fn with_stdlib(&self) -> &Self {224		self.run_in_state(|| {225			use jsonnet_stdlib::STDLIB_STR;226			if cfg!(feature = "serialized-stdlib") {227				self.add_parsed_file(228					PathBuf::from("std.jsonnet"),229					STDLIB_STR.to_owned(),230					bincode::deserialize(include_bytes!(concat!(231						env!("OUT_DIR"),232						"/stdlib.bincode"233					)))234					.expect("deserialize stdlib"),235				)236				.unwrap();237			} else {238				self.add_file(PathBuf::from("std.jsonnet"), STDLIB_STR.to_owned())239					.unwrap();240			}241			let val = self.evaluate_file(&PathBuf::from("std.jsonnet")).unwrap();242			self.add_global("std".into(), val);243		});244		self245	}246247	pub fn create_default_context(&self) -> Result<Context> {248		let globals = self.0.globals.borrow();249		let mut new_bindings: HashMap<Rc<str>, LazyBinding> = HashMap::new();250		for (name, value) in globals.iter() {251			new_bindings.insert(252				name.clone(),253				LazyBinding::Bound(resolved_lazy_val!(value.clone())),254			);255		}256		Context::new().extend_unbound(new_bindings, None, None, None)257	}258259	pub fn push<T>(260		&self,261		e: ExprLocation,262		comment: String,263		f: impl FnOnce() -> Result<T>,264	) -> Result<T> {265		{266			let mut stack = self.0.stack.borrow_mut();267			if stack.len() > self.0.settings.max_stack_frames {268				drop(stack);269				return self.error(Error::StackOverflow);270			} else {271				stack.push(StackTraceElement(e, comment));272			}273		}274		let result = f();275		self.0.stack.borrow_mut().pop();276		result277	}278	pub fn print_stack_trace(&self) {279		for e in self.stack_trace().0 {280			println!("{:?} - {:?}", e.0, e.1)281		}282	}283	pub fn stack_trace(&self) -> StackTrace {284		StackTrace(285			self.0286				.stack287				.borrow()288				.iter()289				.rev()290				.take(self.0.settings.max_stack_trace_size)291				.cloned()292				.collect(),293		)294	}295	pub fn error<T>(&self, err: Error) -> Result<T> {296		Err(LocError(err, self.stack_trace()))297	}298299	pub fn run_in_state<T>(&self, f: impl FnOnce() -> T) -> T {300		EVAL_STATE.with(|v| {301			let has_state = v.borrow().is_some();302			if !has_state {303				v.borrow_mut().replace(self.clone());304			}305			let result = f();306			if !has_state {307				v.borrow_mut().take();308			}309			result310		})311	}312}313314#[cfg(test)]315pub mod tests {316	use super::Val;317	use crate::EvaluationState;318	use jsonnet_parser::*;319	use std::{path::PathBuf, rc::Rc};320321	#[test]322	fn eval_state_stacktrace() {323		let state = EvaluationState::default();324		state325			.push(326				ExprLocation(Rc::new(PathBuf::from("test1.jsonnet")), 10, 20),327				"outer".to_owned(),328				|| {329					state.push(330						ExprLocation(Rc::new(PathBuf::from("test2.jsonnet")), 30, 40),331						"inner".to_owned(),332						|| {333							state.print_stack_trace();334							Ok(())335						},336					)?;337					Ok(())338				},339			)340			.unwrap();341	}342343	#[test]344	fn eval_state_standard() {345		let state = EvaluationState::default();346		state.with_stdlib();347		assert_eq!(348			state349				.parse_evaluate_raw(r#"std.assertEqual(std.base64("test"), "dGVzdA==")"#)350				.unwrap(),351			Val::Bool(true)352		);353	}354355	macro_rules! eval {356		($str: expr) => {357			EvaluationState::default()358				.with_stdlib()359				.parse_evaluate_raw($str)360				.unwrap()361		};362	}363	macro_rules! eval_json {364		($str: expr) => {{365			let evaluator = EvaluationState::default();366			evaluator.with_stdlib();367			evaluator368				.parse_evaluate_raw($str)369				.unwrap()370				.into_json(0)371				.unwrap()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}