difftreelog
feat expose and document evaluator settings
in: master
2 files changed
bindings/jsonnet/src/lib.rsdiffbeforeafterboth--- a/bindings/jsonnet/src/lib.rs
+++ b/bindings/jsonnet/src/lib.rs
@@ -68,13 +68,13 @@
pub extern "C" fn jsonnet_make() -> Box<EvaluationState> {
let state = EvaluationState::default();
state.with_stdlib();
- state.set_import_resolver(Box::new(NativeImportResolver::default()));
+ state.settings_mut().import_resolver = Box::new(NativeImportResolver::default());
Box::new(state)
}
#[no_mangle]
pub extern "C" fn jsonnet_max_stack(vm: &EvaluationState, v: c_uint) {
- vm.set_max_stack(v as usize);
+ vm.settings_mut().max_stack = v as usize;
}
// jrsonnet currently have no GC, so these functions is no-op
@@ -273,7 +273,7 @@
pub unsafe extern "C" fn jsonnet_jpath_add(vm: &EvaluationState, v: *const c_char) {
let cstr = CStr::from_ptr(v);
let path = PathBuf::from(cstr.to_str().unwrap());
- let any_resolver = vm.import_resolver();
+ let any_resolver = &vm.settings().import_resolver;
let resolver = any_resolver
.as_any()
.downcast_ref::<NativeImportResolver>()
crates/jrsonnet-evaluator/src/lib.rsdiffbeforeafterboth1#![feature(box_syntax, box_patterns)]2#![feature(type_alias_impl_trait)]3#![feature(debug_non_exhaustive)]4#![feature(test)]5#![feature(stmt_expr_attributes)]6#![allow(macro_expanded_macro_exports_accessed_by_absolute_paths)]78extern crate test;910mod ctx;11mod dynamic;12mod error;13mod evaluate;14mod function;15mod import;16mod map;17mod obj;18mod val;19pub mod trace;2021pub use ctx::*;22pub use dynamic::*;23pub use error::*;24pub use evaluate::*;25pub use function::parse_function_call;26pub use import::*;27use jrsonnet_parser::*;28pub use obj::*;29use std::{cell::{Ref, RefCell, RefMut}, collections::HashMap, fmt::Debug, path::PathBuf, rc::Rc};30pub use val::*;31use trace::{offset_to_location, CodeLocation};3233type BindableFn = dyn Fn(Option<ObjValue>, Option<ObjValue>) -> Result<LazyVal>;34#[derive(Clone)]35pub enum LazyBinding {36 Bindable(Rc<BindableFn>),37 Bound(LazyVal),38}3940impl Debug for LazyBinding {41 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {42 write!(f, "LazyBinding")43 }44}45impl LazyBinding {46 pub fn evaluate(&self, this: Option<ObjValue>, super_obj: Option<ObjValue>) -> Result<LazyVal> {47 match self {48 LazyBinding::Bindable(v) => v(this, super_obj),49 LazyBinding::Bound(v) => Ok(v.clone()),50 }51 }52}5354struct EvaluationSettings {55 max_stack_frames: usize,56 max_stack_trace_size: usize,57 ext_vars: HashMap<Rc<str>, Val>,58 globals: HashMap<Rc<str>, Val>,59 import_resolver: Box<dyn ImportResolver>,60}61impl Default for EvaluationSettings {62 fn default() -> Self {63 EvaluationSettings {64 max_stack_frames: 200,65 max_stack_trace_size: 20,66 globals: Default::default(),67 ext_vars: Default::default(),68 import_resolver: Box::new(DummyImportResolver),69 }70 }71}7273#[derive(Default)]74struct EvaluationData {75 /// Used for stack overflow detection, stacktrace is now populated on unwind76 stack_depth: usize,77 /// Contains file source codes and evaluated results for imports and pretty78 /// printing stacktraces79 files: HashMap<Rc<PathBuf>, FileData>,80 str_files: HashMap<Rc<PathBuf>, Rc<str>>,81}8283pub struct FileData(Rc<str>, LocExpr, Option<Val>);84#[derive(Default)]85pub struct EvaluationStateInternals {86 data: RefCell<EvaluationData>,87 settings: RefCell<EvaluationSettings>,88}8990thread_local! {91 /// Contains state for currently executing file92 /// Global state is fine there93 pub(crate) static EVAL_STATE: RefCell<Option<EvaluationState>> = RefCell::new(None)94}95pub(crate) fn with_state<T>(f: impl FnOnce(&EvaluationState) -> T) -> T {96 EVAL_STATE.with(|s| f(s.borrow().as_ref().unwrap()))97}98pub fn create_error(err: Error) -> LocError {99 with_state(|s| s.error(err))100}101pub fn create_error_result<T>(err: Error) -> Result<T> {102 Err(with_state(|s| s.error(err)))103}104pub(crate) fn push<T>(105 e: &Option<ExprLocation>,106 frame_desc: impl FnOnce() -> String,107 f: impl FnOnce() -> Result<T>,108) -> Result<T> {109 if let Some(v) = e {110 with_state(|s| s.push(&v, frame_desc, f))111 } else {112 f()113 }114}115116/// Maintains stack trace and import resolution117#[derive(Default, Clone)]118pub struct EvaluationState(Rc<EvaluationStateInternals>);119impl EvaluationState {120 fn data(&self) -> Ref<EvaluationData> {121 self.0.data.borrow()122 }123 fn data_mut(&self) -> RefMut<EvaluationData> {124 self.0.data.borrow_mut()125 }126 fn settings(&self) -> Ref<EvaluationSettings> {127 self.0.settings.borrow()128 }129 fn settings_mut(&self) -> RefMut<EvaluationSettings> {130 self.0.settings.borrow_mut()131 }132133 pub fn set_import_resolver(&self, resolver: Box<dyn ImportResolver>) {134 self.settings_mut().import_resolver = resolver;135 }136 pub fn import_resolver(&self) -> Ref<dyn ImportResolver> {137 Ref::map(self.settings(), |s|&*s.import_resolver)138 }139140 pub fn evaluate_file_to_json(141 &self,142 path: &PathBuf,143 ) -> std::result::Result<Rc<str>, LocError> {144 self.import_file(&PathBuf::new(), &path).and_then(|v|v.into_json(4))145 }146 pub fn evaluate_snippet_to_json(147 &self,148 path: &PathBuf,149 snippet: &str,150 ) -> std::result::Result<Rc<str>, LocError> {151 self.parse_evaluate_raw_with_source(Rc::new(path.clone()), snippet).and_then(|v|v.into_json(4))152 }153154 pub fn add_file(155 &self,156 name: Rc<PathBuf>,157 code: Rc<str>,158 ) -> std::result::Result<(), ParseError> {159 self.data_mut().files.insert(160 name.clone(),161 FileData(162 code.clone(),163 parse(164 &code,165 &ParserSettings {166 file_name: name,167 loc_data: true,168 },169 )?,170 None,171 ),172 );173174 Ok(())175 }176 pub fn add_parsed_file(177 &self,178 name: Rc<PathBuf>,179 code: Rc<str>,180 parsed: LocExpr,181 ) -> std::result::Result<(), ()> {182 self.data_mut()183 .files184 .insert(name, FileData(code, parsed, None));185186 Ok(())187 }188 pub fn get_source(&self, name: &PathBuf) -> Option<Rc<str>> {189 let ro_map = &self.data().files;190 ro_map.get(name).map(|value| value.0.clone())191 }192 pub fn map_source_locations(&self, file: &PathBuf, locs: &[usize]) -> Vec<CodeLocation> {193 offset_to_location(&self.get_source(file).unwrap(), locs)194 }195196 pub fn evaluate_file(&self, name: &PathBuf) -> Result<Val> {197 self.run_in_state(|| {198 let expr: LocExpr = {199 let ro_map = &self.data().files;200 let value = ro_map201 .get(name)202 .unwrap_or_else(|| panic!("file not added: {:?}", name));203 if value.2.is_some() {204 return Ok(value.2.clone().unwrap());205 }206 value.1.clone()207 };208 let value = evaluate(self.create_default_context()?, &expr)?;209 {210 self.0211 .data.borrow_mut()212 .files213 .get_mut(name)214 .unwrap()215 .2216 .replace(value.clone());217 }218 Ok(value)219 })220 }221 pub(crate) fn import_file(&self, from: &PathBuf, path: &PathBuf) -> Result<Val> {222 let file_path = self.settings().import_resolver.resolve_file(from, path)?;223 {224 let files = &self.data().files;225 if files.contains_key(&file_path) {226 return self.evaluate_file(&file_path);227 }228 }229 let contents = self.settings().import_resolver.load_file_contents(&file_path)?;230 self.add_file(file_path.clone(), contents).map_err(|e| {231 create_error(Error::ImportSyntaxError(e))232 })?;233 self.evaluate_file(&file_path)234 }235 pub(crate) fn import_file_str(&self, from: &PathBuf, path: &PathBuf) -> Result<Rc<str>> {236 let path = self.settings().import_resolver.resolve_file(from, path)?;237 if !self.data().str_files.contains_key(&path) {238 let file_str = self.settings().import_resolver.load_file_contents(&path)?;239 self.data_mut()240 .str_files241 .insert(path.clone(), file_str);242 }243 Ok(self.data().str_files.get(&path).cloned().unwrap())244 }245246 pub fn parse_evaluate_raw_with_source(&self, source: Rc<PathBuf>, code: &str) -> Result<Val> {247 let parsed = parse(248 &code,249 &ParserSettings {250 file_name: source,251 loc_data: true,252 },253 )254 .unwrap();255 self.evaluate_raw(parsed)256 }257 pub fn parse_evaluate_raw(&self, code: &str) -> Result<Val> {258 self.parse_evaluate_raw_with_source(Rc::new(PathBuf::from("raw.jsonnet")), code)259 }260261 pub fn evaluate_raw(&self, code: LocExpr) -> Result<Val> {262 self.run_in_state(|| evaluate(self.create_default_context()?, &code))263 }264265 /// Adds standard library global variable (std) to this evaluator266 pub fn with_stdlib(&self) -> &Self {267 use jrsonnet_stdlib::STDLIB_STR;268 let std_path = Rc::new(PathBuf::from("std.jsonnet"));269 self.run_in_state(|| {270 self.add_parsed_file(271 std_path.clone(),272 STDLIB_STR.to_owned().into(),273 builtin::get_parsed_stdlib(),274 )275 .unwrap();276 let val = self.evaluate_file(&std_path).unwrap();277 self.settings_mut().globals.insert("std".into(), val);278 });279 self280 }281282 pub fn create_default_context(&self) -> Result<Context> {283 let globals = &self.settings().globals;284 let mut new_bindings: HashMap<Rc<str>, LazyBinding> = HashMap::new();285 for (name, value) in globals.iter() {286 new_bindings.insert(287 name.clone(),288 LazyBinding::Bound(resolved_lazy_val!(value.clone())),289 );290 }291 Context::new().extend_unbound(new_bindings, None, None, None)292 }293294 /// Executes code, creating new stack frame295 pub fn push<T>(296 &self,297 e: &ExprLocation,298 frame_desc: impl FnOnce() -> String,299 f: impl FnOnce() -> Result<T>,300 ) -> Result<T> {301 {302 let mut data = self.data_mut();303 let stack_depth = &mut data.stack_depth;304 if *stack_depth > self.settings().max_stack_frames {305 // Error creation uses data, so i drop guard here306 drop(data);307 return Err(self.error(Error::StackOverflow));308 } else {309 *stack_depth+=1;310 }311 }312 let result = f();313 self.data_mut().stack_depth -= 1;314 if let Err(mut err) = result {315 (err.1).0.push(StackTraceElement(e.clone(), frame_desc()));316 return Err(err);317 }318 result319 }320321 /// Creates error with stack trace322 pub fn error(&self, err: Error) -> LocError {323 LocError(err, StackTrace(vec![]))324 }325326 /// Runs passed function in state (required, if function needs to modify stack trace)327 pub fn run_in_state<T>(&self, f: impl FnOnce() -> T) -> T {328 EVAL_STATE.with(|v| {329 let has_state = v.borrow().is_some();330 if !has_state {331 v.borrow_mut().replace(self.clone());332 }333 let result = f();334 if !has_state {335 v.borrow_mut().take();336 }337 result338 })339 }340}341342#[cfg(test)]343pub mod tests {344 use super::Val;345 use crate::{create_error, EvaluationState, primitive_equals};346 use jrsonnet_parser::*;347 use std::{path::PathBuf, rc::Rc};348349 #[test]350 fn eval_state_stacktrace() {351 let state = EvaluationState::default();352 state.run_in_state(||{353 state354 .push(355 &ExprLocation(Rc::new(PathBuf::from("test1.jsonnet")), 10, 20),356 || "outer".to_owned(),357 || {358 state.push(359 &ExprLocation(Rc::new(PathBuf::from("test2.jsonnet")), 30, 40),360 || "inner".to_owned(),361 || {362 Err(create_error(crate::error::Error::RuntimeError("".into())))363 },364 )?;365 Ok(())366 },367 )368 .unwrap();369 });370 }371372 #[test]373 fn eval_state_standard() {374 let state = EvaluationState::default();375 state.with_stdlib();376 assert!(377 primitive_equals(378 &state.parse_evaluate_raw(r#"std.assertEqual(std.base64("test"), "dGVzdA==")"#).unwrap(),379 &Val::Bool(true),380 ).unwrap()381 );382 }383384 macro_rules! eval {385 ($str: expr) => {386 EvaluationState::default()387 .with_stdlib()388 .parse_evaluate_raw($str)389 .unwrap()390 };391 }392 macro_rules! eval_json {393 ($str: expr) => {{394 let evaluator = EvaluationState::default();395 evaluator.with_stdlib();396 evaluator.run_in_state(||{397 evaluator398 .parse_evaluate_raw($str)399 .unwrap()400 .into_json(0)401 .unwrap()402 .replace("\n", "")403 })404 }}405 }406407 /// Asserts given code returns `true`408 macro_rules! assert_eval {409 ($str: expr) => {410 assert!(primitive_equals(&eval!($str), &Val::Bool(true)).unwrap())411 };412 }413414 /// Asserts given code returns `false`415 macro_rules! assert_eval_neg {416 ($str: expr) => {417 assert!(primitive_equals(&eval!($str), &Val::Bool(false)).unwrap())418 };419 }420 macro_rules! assert_json {421 ($str: expr, $out: expr) => {422 assert_eq!(eval_json!($str), $out.replace("\t", ""))423 };424 }425426 /// Sanity checking, before trusting to another tests427 #[test]428 fn equality_operator() {429 assert_eval!("2 == 2");430 assert_eval_neg!("2 != 2");431 assert_eval!("2 != 3");432 assert_eval_neg!("2 == 3");433 assert_eval!("'Hello' == 'Hello'");434 assert_eval_neg!("'Hello' != 'Hello'");435 assert_eval!("'Hello' != 'World'");436 assert_eval_neg!("'Hello' == 'World'");437 }438439 #[test]440 fn math_evaluation() {441 assert_eval!("2 + 2 * 2 == 6");442 assert_eval!("3 + (2 + 2 * 2) == 9");443 }444445 #[test]446 fn string_concat() {447 assert_eval!("'Hello' + 'World' == 'HelloWorld'");448 assert_eval!("'Hello' * 3 == 'HelloHelloHello'");449 assert_eval!("'Hello' + 'World' * 3 == 'HelloWorldWorldWorld'");450 }451452 #[test]453 fn faster_join() {454 assert_eval!("std.join([0,0], [[1,2],[3,4],[5,6]]) == [1,2,0,0,3,4,0,0,5,6]");455 assert_eval!("std.join(',', ['1','2','3','4']) == '1,2,3,4'");456 }457458 #[test]459 fn function_contexts() {460 assert_eval!(461 r#"462 local k = {463 t(name = self.h): [self.h, name],464 h: 3,465 };466 local f = {467 t: k.t(),468 h: 4,469 };470 f.t[0] == f.t[1]471 "#472 );473 }474475 #[test]476 fn local() {477 assert_eval!("local a = 2; local b = 3; a + b == 5");478 assert_eval!("local a = 1, b = a + 1; a + b == 3");479 assert_eval!("local a = 1; local a = 2; a == 2");480 }481482 #[test]483 fn object_lazyness() {484 assert_json!("local a = {a:error 'test'}; {}", r#"{}"#);485 }486487 #[test]488 fn object_inheritance() {489 assert_json!("{a: self.b} + {b:3}", r#"{"a": 3,"b": 3}"#);490 }491492 #[test]493 fn object_assertion_success() {494 eval!("{assert \"a\" in self} + {a:2}");495 }496497 #[test]498 fn object_assertion_error() {499 eval!("{assert \"a\" in self}");500 }501502 #[test]503 fn lazy_args() {504 eval!("local test(a) = 2; test(error '3')");505 }506507 #[test]508 #[should_panic]509 fn tailstrict_args() {510 eval!("local test(a) = 2; test(error '3') tailstrict");511 }512513 #[test]514 #[should_panic]515 fn no_binding_error() {516 eval!("a");517 }518519 #[test]520 fn test_object() {521 assert_json!("{a:2}", r#"{"a": 2}"#);522 assert_json!("{a:2+2}", r#"{"a": 4}"#);523 assert_json!("{a:2}+{b:2}", r#"{"a": 2,"b": 2}"#);524 assert_json!("{b:3}+{b:2}", r#"{"b": 2}"#);525 assert_json!("{b:3}+{b+:2}", r#"{"b": 5}"#);526 assert_json!("local test='a'; {[test]:2}", r#"{"a": 2}"#);527 assert_json!(528 r#"529 {530 name: "Alice",531 welcome: "Hello " + self.name + "!",532 }533 "#,534 r#"{"name": "Alice","welcome": "Hello Alice!"}"#535 );536 assert_json!(537 r#"538 {539 name: "Alice",540 welcome: "Hello " + self.name + "!",541 } + {542 name: "Bob"543 }544 "#,545 r#"{"name": "Bob","welcome": "Hello Bob!"}"#546 );547 }548549 #[test]550 fn functions() {551 assert_json!(r#"local a = function(b, c = 2) b + c; a(2)"#, "4");552 assert_json!(553 r#"local a = function(b, c = "Dear") b + c + d, d = "World"; a("Hello")"#,554 r#""HelloDearWorld""#555 );556 }557558 #[test]559 fn local_methods() {560 assert_json!(r#"local a(b, c = 2) = b + c; a(2)"#, "4");561 assert_json!(562 r#"local a(b, c = "Dear") = b + c + d, d = "World"; a("Hello")"#,563 r#""HelloDearWorld""#564 );565 }566567 #[test]568 fn object_locals() {569 assert_json!(r#"{local a = 3, b: a}"#, r#"{"b": 3}"#);570 assert_json!(r#"{local a = 3, local c = a, b: c}"#, r#"{"b": 3}"#);571 assert_json!(572 r#"{local a = function (b) {[b]:4}, test: a("test")}"#,573 r#"{"test": {"test": 4}}"#574 );575 }576577 #[test]578 fn object_comp() {579 assert_json!(580 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}"#,581 "{\"h1_2\": \"0a\",\"h1_3\": \"0a\",\"h1_4\": \"0a\",\"h2_3\": \"a1\",\"h2_4\": \"a1\",\"h3_2\": \"0a\",\"h3_4\": \"a1\"}"582 )583 }584585 #[test]586 fn direct_self() {587 println!(588 "{:#?}",589 eval!(590 r#"591 {592 local me = self,593 a: 3,594 b(): me.a,595 }596 "#597 )598 );599 }600601 #[test]602 fn indirect_self() {603 // `self` assigned to `me` was lost when being604 // referenced from field605 eval!(606 r#"{607 local me = self,608 a: 3,609 b: me.a,610 }.b"#611 );612 }613614 // We can't trust other tests (And official jsonnet testsuite), if assert is not working correctly615 #[test]616 fn std_assert_ok() {617 eval!("std.assertEqual(4.5 << 2, 16)");618 }619620 #[test]621 #[should_panic]622 fn std_assert_failure() {623 eval!("std.assertEqual(4.5 << 2, 15)");624 }625626 #[test]627 fn string_is_string() {628 assert!(629 primitive_equals(630 &eval!("local arr = 'hello'; (!std.isArray(arr)) && (!std.isString(arr))"),631 &Val::Bool(false),632 ).unwrap()633 );634 }635636 #[test]637 fn base64_works() {638 assert_json!(r#"std.base64("test")"#, r#""dGVzdA==""#);639 }640641 #[test]642 fn utf8_chars() {643 assert_json!(644 r#"local c="😎";{c:std.codepoint(c),l:std.length(c)}"#,645 r#"{"c": 128526,"l": 1}"#646 )647 }648649 #[test]650 fn json() {651 assert_json!(652 r#"std.manifestJsonEx({a:3, b:4, c:6},"")"#,653 r#""{\n\"a\": 3,\n\"b\": 4,\n\"c\": 6\n}""#654 );655 }656657 #[test]658 fn test() {659 assert_json!(660 r#"[[a, b] for a in [1,2,3] for b in [4,5,6]]"#,661 "[[1,4],[1,5],[1,6],[2,4],[2,5],[2,6],[3,4],[3,5],[3,6]]"662 );663 }664665 #[test]666 fn sjsonnet() {667 eval!(668 r#"669 local x0 = {k: 1};670 local x1 = {k: x0.k + x0.k};671 local x2 = {k: x1.k + x1.k};672 local x3 = {k: x2.k + x2.k};673 local x4 = {k: x3.k + x3.k};674 local x5 = {k: x4.k + x4.k};675 local x6 = {k: x5.k + x5.k};676 local x7 = {k: x6.k + x6.k};677 local x8 = {k: x7.k + x7.k};678 local x9 = {k: x8.k + x8.k};679 local x10 = {k: x9.k + x9.k};680 local x11 = {k: x10.k + x10.k};681 local x12 = {k: x11.k + x11.k};682 local x13 = {k: x12.k + x12.k};683 local x14 = {k: x13.k + x13.k};684 local x15 = {k: x14.k + x14.k};685 local x16 = {k: x15.k + x15.k};686 local x17 = {k: x16.k + x16.k};687 local x18 = {k: x17.k + x17.k};688 local x19 = {k: x18.k + x18.k};689 local x20 = {k: x19.k + x19.k};690 local x21 = {k: x20.k + x20.k};691 x21.k692 "#693 );694 }695696 use test::Bencher;697698 // This test is commented out by default, because of huge compilation slowdown699 // #[bench]700 // fn bench_codegen(b: &mut Bencher) {701 // b.iter(|| {702 // #[allow(clippy::all)]703 // let stdlib = {704 // use jrsonnet_parser::*;705 // include!(concat!(env!("OUT_DIR"), "/stdlib.rs"))706 // };707 // stdlib708 // })709 // }710711 #[bench]712 fn bench_serialize(b: &mut Bencher) {713 b.iter(|| {714 bincode::deserialize::<jrsonnet_parser::LocExpr>(include_bytes!(concat!(715 env!("OUT_DIR"),716 "/stdlib.bincode"717 )))718 .expect("deserialize stdlib")719 })720 }721722 #[bench]723 fn bench_parse(b: &mut Bencher) {724 b.iter(|| {725 jrsonnet_parser::parse(726 jrsonnet_stdlib::STDLIB_STR,727 &jrsonnet_parser::ParserSettings {728 loc_data: true,729 file_name: Rc::new(PathBuf::from("std.jsonnet")),730 },731 )732 })733 }734735 #[test]736 fn equality(){737 println!("{:?}", jrsonnet_parser::parse("{ x: 1, y: 2 } == { x: 1, y: 2 }", &ParserSettings::default()));738 assert_eval!("{ x: 1, y: 2 } == { x: 1, y: 2 }")739 }740}