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

difftreelog

source

crates/jsonnet-evaluator/src/lib.rs13.7 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 map;12mod obj;13mod val;1415pub use ctx::*;16pub use dynamic::*;17pub use error::*;18pub use evaluate::*;19pub use function::parse_function_call;20use jsonnet_parser::*;21pub use obj::*;22use std::{cell::RefCell, collections::HashMap, fmt::Debug, path::PathBuf, rc::Rc};23pub use val::*;2425rc_fn_helper!(26	Binding,27	binding,28	dyn Fn(Option<ObjValue>, Option<ObjValue>) -> Result<Val>29);3031type BindableFn = dyn Fn(Option<ObjValue>, Option<ObjValue>) -> Result<LazyVal>;32#[derive(Clone)]33pub enum LazyBinding {34	Bindable(Rc<BindableFn>),35	Bound(LazyVal),36}3738impl Debug for LazyBinding {39	fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {40		write!(f, "LazyBinding")41	}42}43impl LazyBinding {44	pub fn evaluate(&self, this: Option<ObjValue>, super_obj: Option<ObjValue>) -> Result<LazyVal> {45		match self {46			LazyBinding::Bindable(v) => v(this, super_obj),47			LazyBinding::Bound(v) => Ok(v.clone()),48		}49	}50}5152pub struct EvaluationSettings {53	pub max_stack_frames: usize,54	pub max_stack_trace_size: usize,55	pub import_resolver: Box<dyn Fn(&PathBuf) -> String>,56}57impl Default for EvaluationSettings {58	fn default() -> Self {59		EvaluationSettings {60			max_stack_frames: 200,61			max_stack_trace_size: 20,62			import_resolver: Box::new(|path| {63				panic!("default EvaluationSettings have no support for import resolution, can't import {:?}", path)64			}),65		}66	}67}6869pub struct FileData(String, LocExpr, Option<Val>);70#[derive(Default)]71pub struct EvaluationStateInternals {72	/// Used for stack-overflows and stacktraces73	stack: RefCell<Vec<StackTraceElement>>,74	/// Contains file source codes and evaluated results for imports and pretty75	/// printing stacktraces76	files: RefCell<HashMap<PathBuf, FileData>>,77	globals: RefCell<HashMap<String, Val>>,7879	/// Values to use with std.extVar80	ext_vars: RefCell<HashMap<String, Val>>,8182	settings: EvaluationSettings,83}8485thread_local! {86	/// Contains state for currently executing file87	/// Global state is fine there88	pub(crate) static EVAL_STATE: RefCell<Option<EvaluationState>> = RefCell::new(None)89}90#[inline(always)]91pub(crate) fn with_state<T>(f: impl FnOnce(&EvaluationState) -> T) -> T {92	EVAL_STATE.with(93		#[inline(always)]94		|s| f(s.borrow().as_ref().unwrap()),95	)96}97pub(crate) fn create_error<T>(err: Error) -> Result<T> {98	with_state(|s| s.error(err))99}100#[inline(always)]101pub(crate) fn push<T>(e: LocExpr, comment: String, f: impl FnOnce() -> Result<T>) -> Result<T> {102	with_state(|s| s.push(e, comment, f))103}104105/// Maintains stack trace and import resolution106#[derive(Default, Clone)]107pub struct EvaluationState(Rc<EvaluationStateInternals>);108impl EvaluationState {109	pub fn new(settings: EvaluationSettings) -> Self {110		EvaluationState(Rc::new(EvaluationStateInternals {111			settings,112			..Default::default()113		}))114	}115	pub fn add_file(&self, name: PathBuf, code: String) -> std::result::Result<(), ParseError> {116		self.0.files.borrow_mut().insert(117			name.clone(),118			FileData(119				code.clone(),120				parse(121					&code,122					&ParserSettings {123						file_name: name,124						loc_data: true,125					},126				)?,127				None,128			),129		);130131		Ok(())132	}133	pub fn add_parsed_file(134		&self,135		name: PathBuf,136		code: String,137		parsed: LocExpr,138	) -> std::result::Result<(), ()> {139		self.0140			.files141			.borrow_mut()142			.insert(name, FileData(code, parsed, None));143144		Ok(())145	}146	pub fn get_source(&self, name: &PathBuf) -> Option<String> {147		let ro_map = self.0.files.borrow();148		ro_map.get(name).map(|value| value.0.clone())149	}150	pub fn evaluate_file(&self, name: &PathBuf) -> Result<Val> {151		self.begin_state();152		let value = self.evaluate_file_in_current_state(name)?;153		self.end_state();154		Ok(value)155	}156	pub(crate) fn evaluate_file_in_current_state(&self, name: &PathBuf) -> Result<Val> {157		let expr: LocExpr = {158			let ro_map = self.0.files.borrow();159			let value = ro_map160				.get(name)161				.unwrap_or_else(|| panic!("file not added: {:?}", name));162			if value.2.is_some() {163				return Ok(value.2.clone().unwrap());164			}165			value.1.clone()166		};167		let value = evaluate(self.create_default_context()?, &expr)?;168		{169			self.0170				.files171				.borrow_mut()172				.get_mut(name)173				.unwrap()174				.2175				.replace(value.clone());176		}177		Ok(value)178	}179	pub(crate) fn import_file(&self, path: &PathBuf) -> Result<Val> {180		if !self.0.files.borrow().contains_key(path) {181			let file_str = (self.0.settings.import_resolver)(path);182			self.add_file(path.clone(), file_str).unwrap();183		}184		self.evaluate_file_in_current_state(path)185	}186187	pub fn parse_evaluate_raw(&self, code: &str) -> Result<Val> {188		let parsed = parse(189			&code,190			&ParserSettings {191				file_name: PathBuf::from("raw.jsonnet"),192				loc_data: true,193			},194		)195		.unwrap();196		self.evaluate_raw(parsed)197	}198199	pub fn evaluate_raw(&self, code: LocExpr) -> Result<Val> {200		self.begin_state();201		let value = evaluate(self.create_default_context()?, &code);202		self.end_state();203		value204	}205206	pub fn add_global(&self, name: String, value: Val) {207		self.0.globals.borrow_mut().insert(name, value);208	}209	pub fn add_ext_var(&self, name: String, value: Val) {210		self.0.ext_vars.borrow_mut().insert(name, value);211	}212213	pub fn with_stdlib(&self) -> &Self {214		self.begin_state();215		use jsonnet_stdlib::STDLIB_STR;216		if cfg!(feature = "serialized-stdlib") {217			self.add_parsed_file(218				PathBuf::from("std.jsonnet"),219				STDLIB_STR.to_owned(),220				bincode::deserialize(include_bytes!(concat!(env!("OUT_DIR"), "/stdlib.bincode")))221					.expect("deserialize stdlib"),222			)223			.unwrap();224		} else {225			self.add_file(PathBuf::from("std.jsonnet"), STDLIB_STR.to_owned())226				.unwrap();227		}228		let val = self.evaluate_file(&PathBuf::from("std.jsonnet")).unwrap();229		self.add_global("std".to_owned(), val);230		self.end_state();231		self232	}233234	pub fn create_default_context(&self) -> Result<Context> {235		let globals = self.0.globals.borrow();236		let mut new_bindings: HashMap<String, LazyBinding> = HashMap::new();237		for (name, value) in globals.iter() {238			new_bindings.insert(239				name.clone(),240				LazyBinding::Bound(resolved_lazy_val!(value.clone())),241			);242		}243		Context::new().extend_unbound(new_bindings, None, None, None)244	}245246	#[inline(always)]247	pub fn push<T>(&self, e: LocExpr, comment: String, f: impl FnOnce() -> Result<T>) -> Result<T> {248		{249			let mut stack = self.0.stack.borrow_mut();250			if stack.len() > self.0.settings.max_stack_frames {251				drop(stack);252				return self.error(Error::StackOverflow);253			} else {254				stack.push(StackTraceElement(e, comment));255			}256		}257		let result = f();258		self.0.stack.borrow_mut().pop();259		result260	}261	pub fn print_stack_trace(&self) {262		for e in self.stack_trace().0 {263			println!("{:?} - {:?}", e.0, e.1)264		}265	}266	pub fn stack_trace(&self) -> StackTrace {267		StackTrace(268			self.0269				.stack270				.borrow()271				.iter()272				.rev()273				.take(self.0.settings.max_stack_trace_size)274				.cloned()275				.collect(),276		)277	}278	pub fn error<T>(&self, err: Error) -> Result<T> {279		Err(LocError(err, self.stack_trace()))280	}281282	fn begin_state(&self) {283		EVAL_STATE.with(|v| v.borrow_mut().replace(self.clone()));284	}285	fn end_state(&self) {286		EVAL_STATE.with(|v| v.borrow_mut().take());287	}288}289290#[cfg(test)]291pub mod tests {292	use super::Val;293	use crate::EvaluationState;294	use jsonnet_parser::*;295	use std::path::PathBuf;296297	#[test]298	fn eval_state_stacktrace() {299		let state = EvaluationState::default();300		state301			.push(302				loc_expr!(303					Expr::Num(0.0),304					true,305					(PathBuf::from("test1.jsonnet"), 10, 20)306				),307				"outer".to_owned(),308				|| {309					state.push(310						loc_expr!(311							Expr::Num(0.0),312							true,313							(PathBuf::from("test2.jsonnet"), 30, 40)314						),315						"inner".to_owned(),316						|| {317							state.print_stack_trace();318							Ok(())319						},320					)?;321					Ok(())322				},323			)324			.unwrap();325	}326327	#[test]328	fn eval_state_standard() {329		let state = EvaluationState::default();330		state.with_stdlib();331		assert_eq!(332			state333				.parse_evaluate_raw(r#"std.assertEqual(std.base64("test"), "dGVzdA==")"#)334				.unwrap(),335			Val::Bool(true)336		);337	}338339	macro_rules! eval {340		($str: expr) => {341			EvaluationState::default()342				.with_stdlib()343				.parse_evaluate_raw($str)344				.unwrap()345		};346	}347	macro_rules! eval_json {348		($str: expr) => {{349			let evaluator = EvaluationState::default();350			evaluator.with_stdlib();351			let val = evaluator.parse_evaluate_raw($str).unwrap();352			evaluator.add_global("__tmp__to_yaml__".to_owned(), val);353			evaluator354				.parse_evaluate_raw("std.manifestJsonEx(__tmp__to_yaml__, \"\")")355				.unwrap()356				.try_cast_str("there should be json string")357				.unwrap()358				.clone()359				.replace("\n", "")360			}};361	}362363	/// Asserts given code returns `true`364	macro_rules! assert_eval {365		($str: expr) => {366			assert_eq!(eval!($str), Val::Bool(true))367		};368	}369370	/// Asserts given code returns `false`371	macro_rules! assert_eval_neg {372		($str: expr) => {373			assert_eq!(eval!($str), Val::Bool(false))374		};375	}376	macro_rules! assert_json {377		($str: expr, $out: expr) => {378			assert_eq!(eval_json!($str), $out.replace("\t", ""))379		};380	}381382	/// Sanity checking, before trusting to another tests383	#[test]384	fn equality_operator() {385		assert_eval!("2 == 2");386		assert_eval_neg!("2 != 2");387		assert_eval!("2 != 3");388		assert_eval_neg!("2 == 3");389		assert_eval!("'Hello' == 'Hello'");390		assert_eval_neg!("'Hello' != 'Hello'");391		assert_eval!("'Hello' != 'World'");392		assert_eval_neg!("'Hello' == 'World'");393	}394395	#[test]396	fn math_evaluation() {397		assert_eval!("2 + 2 * 2 == 6");398		assert_eval!("3 + (2 + 2 * 2) == 9");399	}400401	#[test]402	fn string_concat() {403		assert_eval!("'Hello' + 'World' == 'HelloWorld'");404		assert_eval!("'Hello' * 3 == 'HelloHelloHello'");405		assert_eval!("'Hello' + 'World' * 3 == 'HelloWorldWorldWorld'");406	}407408	#[test]409	fn function_contexts() {410		assert_eval!(411			r#"412				local k = {413					t(name = self.h): [self.h, name],414					h: 3,415				};416				local f = {417					t: k.t(),418					h: 4,419				};420				f.t[0] == f.t[1]421			"#422		);423	}424425	#[test]426	fn local() {427		assert_eval!("local a = 2; local b = 3; a + b == 5");428		assert_eval!("local a = 1, b = a + 1; a + b == 3");429		assert_eval!("local a = 1; local a = 2; a == 2");430	}431432	#[test]433	fn object_lazyness() {434		assert_json!("local a = {a:error 'test'}; {}", r#"{}"#);435	}436437	/// FIXME: This test gets stackoverflow in debug build438	#[test]439	fn object_inheritance() {440		assert_json!("{a: self.b} + {b:3}", r#"{"a": 3,"b": 3}"#);441	}442443	#[test]444	fn test_object() {445		assert_json!("{a:2}", r#"{"a": 2}"#);446		assert_json!("{a:2+2}", r#"{"a": 4}"#);447		assert_json!("{a:2}+{b:2}", r#"{"a": 2,"b": 2}"#);448		assert_json!("{b:3}+{b:2}", r#"{"b": 2}"#);449		assert_json!("{b:3}+{b+:2}", r#"{"b": 5}"#);450		assert_json!("local test='a'; {[test]:2}", r#"{"a": 2}"#);451		assert_json!(452			r#"453				{454					name: "Alice",455					welcome: "Hello " + self.name + "!",456				}457			"#,458			r#"{"name": "Alice","welcome": "Hello Alice!"}"#459		);460		assert_json!(461			r#"462				{463					name: "Alice",464					welcome: "Hello " + self.name + "!",465				} + {466					name: "Bob"467				}468			"#,469			r#"{"name": "Bob","welcome": "Hello Bob!"}"#470		);471	}472473	#[test]474	fn functions() {475		assert_json!(r#"local a = function(b, c = 2) b + c; a(2)"#, "4");476		assert_json!(477			r#"local a = function(b, c = "Dear") b + c + d, d = "World"; a("Hello")"#,478			r#""HelloDearWorld""#479		);480	}481482	#[test]483	fn local_methods() {484		assert_json!(r#"local a(b, c = 2) = b + c; a(2)"#, "4");485		assert_json!(486			r#"local a(b, c = "Dear") = b + c + d, d = "World"; a("Hello")"#,487			r#""HelloDearWorld""#488		);489	}490491	#[test]492	fn object_locals() {493		assert_json!(r#"{local a = 3, b: a}"#, r#"{"b": 3}"#);494		assert_json!(r#"{local a = 3, local c = a, b: c}"#, r#"{"b": 3}"#);495		assert_json!(496			r#"{local a = function (b) {[b]:4}, test: a("test")}"#,497			r#"{"test": {"test": 4}}"#498		);499	}500501	#[test]502	fn direct_self() {503		println!(504			"{:#?}",505			eval!(506				r#"507					{508						local me = self,509						a: 3,510						b(): me.a,511					}512				"#513			)514		);515	}516517	#[test]518	fn indirect_self() {519		// `self` assigned to `me` was lost when being520		// referenced from field521		eval!(522			r#"{523				local me = self,524				a: 3,525				b: me.a,526			}.b"#527		);528	}529530	// We can't trust other tests (And official jsonnet testsuite), if assert is not working correctly531	#[test]532	fn std_assert_ok() {533		eval!("std.assertEqual(4.5 << 2, 16)");534	}535536	#[test]537	#[should_panic]538	fn std_assert_failure() {539		eval!("std.assertEqual(4.5 << 2, 15)");540	}541542	#[test]543	fn string_is_string() {544		assert_eq!(545			eval!("local arr = 'hello'; (!std.isArray(arr)) && (!std.isString(arr))"),546			Val::Bool(false)547		);548	}549550	#[test]551	fn base64_works() {552		assert_json!(r#"std.base64("test")"#, r#""dGVzdA==""#);553	}554555	#[test]556	fn utf8_chars() {557		assert_json!(558			r#"local c="😎";{c:std.codepoint(c),l:std.length(c)}"#,559			r#"{"c": 128526,"l": 1}"#560		)561	}562563	#[test]564	fn json() {565		assert_json!(566			r#"std.manifestJsonEx({a:3, b:4, c:6},"")"#,567			r#""{\n\"a\": 3,\n\"b\": 4,\n\"c\": 6\n}""#568		);569	}570571	#[test]572	fn test() {573		assert_json!(574			r#"[[a, b] for a in [1,2,3] for b in [4,5,6]]"#,575			"[[1,4],[1,5],[1,6],[2,4],[2,5],[2,6],[3,4],[3,5],[3,6]]"576		);577	}578579	#[test]580	fn sjsonnet() {581		eval!(582			r#"583			local x0 = {k: 1};584			local x1 = {k: x0.k + x0.k};585			local x2 = {k: x1.k + x1.k};586			local x3 = {k: x2.k + x2.k};587			local x4 = {k: x3.k + x3.k};588			local x5 = {k: x4.k + x4.k};589			local x6 = {k: x5.k + x5.k};590			local x7 = {k: x6.k + x6.k};591			local x8 = {k: x7.k + x7.k};592			local x9 = {k: x8.k + x8.k};593			local x10 = {k: x9.k + x9.k};594			local x11 = {k: x10.k + x10.k};595			local x12 = {k: x11.k + x11.k};596			local x13 = {k: x12.k + x12.k};597			local x14 = {k: x13.k + x13.k};598			local x15 = {k: x14.k + x14.k};599			local x16 = {k: x15.k + x15.k};600			local x17 = {k: x16.k + x16.k};601			local x18 = {k: x17.k + x17.k};602			local x19 = {k: x18.k + x18.k};603			local x20 = {k: x19.k + x19.k};604			local x21 = {k: x20.k + x20.k};605			x21.k606		"#607		);608	}609}