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

difftreelog

source

crates/jsonnet-evaluator/src/lib.rs15.1 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)]5#![feature(stmt_expr_attributes)]6mod ctx;7mod dynamic;8mod error;9mod evaluate;10mod function;11mod import;12mod map;13mod obj;14mod val;1516pub use ctx::*;17pub use dynamic::*;18pub use error::*;19pub use evaluate::*;20pub use function::parse_function_call;21pub use import::*;22use jsonnet_parser::*;23pub use obj::*;24use std::{cell::RefCell, collections::HashMap, fmt::Debug, path::PathBuf, rc::Rc};25pub use val::*;2627type BindableFn = dyn Fn(Option<ObjValue>, Option<ObjValue>) -> Result<LazyVal>;28#[derive(Clone)]29pub enum LazyBinding {30	Bindable(Rc<BindableFn>),31	Bound(LazyVal),32}3334impl Debug for LazyBinding {35	fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {36		write!(f, "LazyBinding")37	}38}39impl LazyBinding {40	pub fn evaluate(&self, this: Option<ObjValue>, super_obj: Option<ObjValue>) -> Result<LazyVal> {41		match self {42			LazyBinding::Bindable(v) => v(this, super_obj),43			LazyBinding::Bound(v) => Ok(v.clone()),44		}45	}46}4748pub struct EvaluationSettings {49	pub max_stack_frames: usize,50	pub max_stack_trace_size: usize,51}52impl Default for EvaluationSettings {53	fn default() -> Self {54		EvaluationSettings {55			max_stack_frames: 200,56			max_stack_trace_size: 20,57		}58	}59}6061pub struct FileData(String, LocExpr, Option<Val>);62#[derive(Default)]63pub struct EvaluationStateInternals {64	/// Used for stack-overflows and stacktraces65	stack: RefCell<Vec<StackTraceElement>>,66	/// Contains file source codes and evaluated results for imports and pretty67	/// printing stacktraces68	files: RefCell<HashMap<PathBuf, FileData>>,69	str_files: RefCell<HashMap<PathBuf, String>>,70	globals: RefCell<HashMap<String, Val>>,7172	/// Values to use with std.extVar73	ext_vars: RefCell<HashMap<String, Val>>,7475	settings: EvaluationSettings,76	import_resolver: Box<dyn ImportResolver>,77}7879thread_local! {80	/// Contains state for currently executing file81	/// Global state is fine there82	pub(crate) static EVAL_STATE: RefCell<Option<EvaluationState>> = RefCell::new(None)83}84#[inline(always)]85pub(crate) fn with_state<T>(f: impl FnOnce(&EvaluationState) -> T) -> T {86	EVAL_STATE.with(87		#[inline(always)]88		|s| f(s.borrow().as_ref().unwrap()),89	)90}91pub(crate) fn create_error<T>(err: Error) -> Result<T> {92	with_state(|s| s.error(err))93}94#[inline(always)]95pub(crate) fn push<T>(e: LocExpr, comment: String, f: impl FnOnce() -> Result<T>) -> Result<T> {96	with_state(|s| s.push(e, comment, f))97}9899/// Maintains stack trace and import resolution100#[derive(Default, Clone)]101pub struct EvaluationState(Rc<EvaluationStateInternals>);102impl EvaluationState {103	pub fn new(settings: EvaluationSettings, import_resolver: Box<dyn ImportResolver>) -> Self {104		EvaluationState(Rc::new(EvaluationStateInternals {105			settings,106			import_resolver,107			..Default::default()108		}))109	}110	pub fn add_file(&self, name: PathBuf, code: String) -> std::result::Result<(), ParseError> {111		self.0.files.borrow_mut().insert(112			name.clone(),113			FileData(114				code.clone(),115				parse(116					&code,117					&ParserSettings {118						file_name: name,119						loc_data: true,120					},121				)?,122				None,123			),124		);125126		Ok(())127	}128	pub fn add_parsed_file(129		&self,130		name: PathBuf,131		code: String,132		parsed: LocExpr,133	) -> std::result::Result<(), ()> {134		self.0135			.files136			.borrow_mut()137			.insert(name, FileData(code, parsed, None));138139		Ok(())140	}141	pub fn get_source(&self, name: &PathBuf) -> Option<String> {142		let ro_map = self.0.files.borrow();143		ro_map.get(name).map(|value| value.0.clone())144	}145	pub fn evaluate_file(&self, name: &PathBuf) -> Result<Val> {146		self.begin_state();147		let value = self.evaluate_file_in_current_state(name)?;148		self.end_state();149		Ok(value)150	}151	pub(crate) fn evaluate_file_in_current_state(&self, name: &PathBuf) -> Result<Val> {152		let expr: LocExpr = {153			let ro_map = self.0.files.borrow();154			let value = ro_map155				.get(name)156				.unwrap_or_else(|| panic!("file not added: {:?}", name));157			if value.2.is_some() {158				return Ok(value.2.clone().unwrap());159			}160			value.1.clone()161		};162		let value = evaluate(self.create_default_context()?, &expr)?;163		{164			self.0165				.files166				.borrow_mut()167				.get_mut(name)168				.unwrap()169				.2170				.replace(value.clone());171		}172		Ok(value)173	}174	pub(crate) fn import_file(&self, from: &PathBuf, path: &PathBuf) -> Result<Val> {175		let file_path = self.0.import_resolver.resolve_file(from, path)?;176		{177			let files = self.0.files.borrow();178			if files.contains_key(&file_path) {179				return self.evaluate_file(&file_path);180			}181		}182		let contents = self.0.import_resolver.load_file_contents(&file_path)?;183		self.add_file(file_path.clone(), contents).map_err(|e| {184			create_error::<()>(Error::ImportSyntaxError(e))185				.err()186				.unwrap()187		})?;188		self.evaluate_file(&file_path)189	}190	pub(crate) fn import_file_str(&self, from: &PathBuf, path: &PathBuf) -> Result<String> {191		let path = self.0.import_resolver.resolve_file(from, path)?;192		if !self.0.str_files.borrow().contains_key(&path) {193			let file_str = self.0.import_resolver.load_file_contents(&path)?;194			self.0.str_files.borrow_mut().insert(path.clone(), file_str);195		}196		Ok(self.0.str_files.borrow().get(&path).cloned().unwrap())197	}198199	pub fn parse_evaluate_raw(&self, code: &str) -> Result<Val> {200		let parsed = parse(201			&code,202			&ParserSettings {203				file_name: PathBuf::from("raw.jsonnet"),204				loc_data: true,205			},206		)207		.unwrap();208		self.evaluate_raw(parsed)209	}210211	pub fn evaluate_raw(&self, code: LocExpr) -> Result<Val> {212		self.begin_state();213		let value = evaluate(self.create_default_context()?, &code);214		self.end_state();215		value216	}217218	pub fn add_global(&self, name: String, value: Val) {219		self.0.globals.borrow_mut().insert(name, value);220	}221	pub fn add_ext_var(&self, name: String, value: Val) {222		self.0.ext_vars.borrow_mut().insert(name, value);223	}224225	pub fn with_stdlib(&self) -> &Self {226		self.begin_state();227		use jsonnet_stdlib::STDLIB_STR;228		if cfg!(feature = "serialized-stdlib") {229			self.add_parsed_file(230				PathBuf::from("std.jsonnet"),231				STDLIB_STR.to_owned(),232				bincode::deserialize(include_bytes!(concat!(env!("OUT_DIR"), "/stdlib.bincode")))233					.expect("deserialize stdlib"),234			)235			.unwrap();236		} else {237			self.add_file(PathBuf::from("std.jsonnet"), STDLIB_STR.to_owned())238				.unwrap();239		}240		let val = self.evaluate_file(&PathBuf::from("std.jsonnet")).unwrap();241		self.add_global("std".to_owned(), val);242		self.end_state();243		self244	}245246	pub fn create_default_context(&self) -> Result<Context> {247		let globals = self.0.globals.borrow();248		let mut new_bindings: HashMap<String, LazyBinding> = HashMap::new();249		for (name, value) in globals.iter() {250			new_bindings.insert(251				name.clone(),252				LazyBinding::Bound(resolved_lazy_val!(value.clone())),253			);254		}255		Context::new().extend_unbound(new_bindings, None, None, None)256	}257258	#[inline(always)]259	pub fn push<T>(&self, e: LocExpr, comment: String, f: impl FnOnce() -> Result<T>) -> Result<T> {260		{261			let mut stack = self.0.stack.borrow_mut();262			if stack.len() > self.0.settings.max_stack_frames {263				drop(stack);264				return self.error(Error::StackOverflow);265			} else {266				stack.push(StackTraceElement(e, comment));267			}268		}269		let result = f();270		self.0.stack.borrow_mut().pop();271		result272	}273	pub fn print_stack_trace(&self) {274		for e in self.stack_trace().0 {275			println!("{:?} - {:?}", e.0, e.1)276		}277	}278	pub fn stack_trace(&self) -> StackTrace {279		StackTrace(280			self.0281				.stack282				.borrow()283				.iter()284				.rev()285				.take(self.0.settings.max_stack_trace_size)286				.cloned()287				.collect(),288		)289	}290	pub fn error<T>(&self, err: Error) -> Result<T> {291		Err(LocError(err, self.stack_trace()))292	}293294	fn begin_state(&self) {295		EVAL_STATE.with(|v| v.borrow_mut().replace(self.clone()));296	}297	fn end_state(&self) {298		EVAL_STATE.with(|v| v.borrow_mut().take());299	}300}301302#[cfg(test)]303pub mod tests {304	use super::Val;305	use crate::EvaluationState;306	use jsonnet_parser::*;307	use std::path::PathBuf;308309	#[test]310	fn eval_state_stacktrace() {311		let state = EvaluationState::default();312		state313			.push(314				loc_expr!(315					Expr::Num(0.0),316					true,317					(PathBuf::from("test1.jsonnet"), 10, 20)318				),319				"outer".to_owned(),320				|| {321					state.push(322						loc_expr!(323							Expr::Num(0.0),324							true,325							(PathBuf::from("test2.jsonnet"), 30, 40)326						),327						"inner".to_owned(),328						|| {329							state.print_stack_trace();330							Ok(())331						},332					)?;333					Ok(())334				},335			)336			.unwrap();337	}338339	#[test]340	fn eval_state_standard() {341		let state = EvaluationState::default();342		state.with_stdlib();343		assert_eq!(344			state345				.parse_evaluate_raw(r#"std.assertEqual(std.base64("test"), "dGVzdA==")"#)346				.unwrap(),347			Val::Bool(true)348		);349	}350351	macro_rules! eval {352		($str: expr) => {353			EvaluationState::default()354				.with_stdlib()355				.parse_evaluate_raw($str)356				.unwrap()357		};358	}359	macro_rules! eval_json {360		($str: expr) => {{361			let evaluator = EvaluationState::default();362			evaluator.with_stdlib();363			let val = evaluator.parse_evaluate_raw($str).unwrap();364			evaluator.add_global("__tmp__to_yaml__".to_owned(), val);365			evaluator366				.parse_evaluate_raw("std.manifestJsonEx(__tmp__to_yaml__, \"\")")367				.unwrap()368				.try_cast_str("there should be json string")369				.unwrap()370				.clone()371				.replace("\n", "")372			}};373	}374375	/// Asserts given code returns `true`376	macro_rules! assert_eval {377		($str: expr) => {378			assert_eq!(eval!($str), Val::Bool(true))379		};380	}381382	/// Asserts given code returns `false`383	macro_rules! assert_eval_neg {384		($str: expr) => {385			assert_eq!(eval!($str), Val::Bool(false))386		};387	}388	macro_rules! assert_json {389		($str: expr, $out: expr) => {390			assert_eq!(eval_json!($str), $out.replace("\t", ""))391		};392	}393394	/// Sanity checking, before trusting to another tests395	#[test]396	fn equality_operator() {397		assert_eval!("2 == 2");398		assert_eval_neg!("2 != 2");399		assert_eval!("2 != 3");400		assert_eval_neg!("2 == 3");401		assert_eval!("'Hello' == 'Hello'");402		assert_eval_neg!("'Hello' != 'Hello'");403		assert_eval!("'Hello' != 'World'");404		assert_eval_neg!("'Hello' == 'World'");405	}406407	#[test]408	fn math_evaluation() {409		assert_eval!("2 + 2 * 2 == 6");410		assert_eval!("3 + (2 + 2 * 2) == 9");411	}412413	#[test]414	fn string_concat() {415		assert_eval!("'Hello' + 'World' == 'HelloWorld'");416		assert_eval!("'Hello' * 3 == 'HelloHelloHello'");417		assert_eval!("'Hello' + 'World' * 3 == 'HelloWorldWorldWorld'");418	}419420	#[test]421	fn faster_join() {422		assert_eval!("std.join([0,0], [[1,2],[3,4],[5,6]]) == [1,2,0,0,3,4,0,0,5,6]");423		assert_eval!("std.join(',', ['1','2','3','4']) == '1,2,3,4'");424	}425426	#[test]427	fn function_contexts() {428		assert_eval!(429			r#"430				local k = {431					t(name = self.h): [self.h, name],432					h: 3,433				};434				local f = {435					t: k.t(),436					h: 4,437				};438				f.t[0] == f.t[1]439			"#440		);441	}442443	#[test]444	fn local() {445		assert_eval!("local a = 2; local b = 3; a + b == 5");446		assert_eval!("local a = 1, b = a + 1; a + b == 3");447		assert_eval!("local a = 1; local a = 2; a == 2");448	}449450	#[test]451	fn object_lazyness() {452		assert_json!("local a = {a:error 'test'}; {}", r#"{}"#);453	}454455	/// FIXME: This test gets stackoverflow in debug build456	#[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}