difftreelog
feat(bindings) snippet evaluation
in: master
2 files changed
bindings/jsonnet/src/lib.rsdiffbeforeafterboth--- a/bindings/jsonnet/src/lib.rs
+++ b/bindings/jsonnet/src/lib.rs
@@ -306,10 +306,42 @@
}
})
}
+
+/// # Safety
+///
+/// This function is safe, if received v is a pointer to normal C string
#[no_mangle]
-pub extern "C" fn jsonnet_evaluate_snippet() {
- todo!()
+pub unsafe extern "C" fn jsonnet_evaluate_snippet(
+ vm: &EvaluationState,
+ filename: *const c_char,
+ snippet: *const c_char,
+ error: &mut c_int,
+) -> *const c_char {
+ vm.run_in_state(|| {
+ use std::fmt::Write;
+ let filename = CStr::from_ptr(filename);
+ let snippet = CStr::from_ptr(snippet);
+ match vm.evaluate_snippet_to_json(
+ &PathBuf::from(filename.to_str().unwrap()),
+ &snippet.to_str().unwrap(),
+ ) {
+ Ok(v) => {
+ *error = 0;
+ CString::new(&*v as &str).unwrap().into_raw()
+ }
+ Err(e) => {
+ *error = 1;
+ let mut out = String::new();
+ writeln!(out, "{:?}", e.0).unwrap();
+ for i in (e.1).0.iter() {
+ writeln!(out, "{:?} ---- {}", i.0, i.1).unwrap();
+ }
+ CString::new(&out as &str).unwrap().into_raw()
+ }
+ }
+ })
}
+
#[no_mangle]
pub extern "C" fn jsonnet_evaluate_file_multi() {
todo!()
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#![allow(macro_expanded_macro_exports_accessed_by_absolute_paths)]67extern crate test;89mod ctx;10mod dynamic;11mod error;12mod evaluate;13mod function;14mod import;15mod map;16mod obj;17mod val;1819pub use ctx::*;20pub use dynamic::*;21pub use error::*;22pub use evaluate::*;23pub use function::parse_function_call;24pub use import::*;25use jrsonnet_parser::*;26pub use obj::*;27use std::{cell::{Ref, RefCell, RefMut}, collections::HashMap, fmt::Debug, path::PathBuf, rc::Rc};28pub use val::*;2930type BindableFn = dyn Fn(Option<ObjValue>, Option<ObjValue>) -> Result<LazyVal>;31#[derive(Clone)]32pub enum LazyBinding {33 Bindable(Rc<BindableFn>),34 Bound(LazyVal),35}3637impl Debug for LazyBinding {38 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {39 write!(f, "LazyBinding")40 }41}42impl LazyBinding {43 pub fn evaluate(&self, this: Option<ObjValue>, super_obj: Option<ObjValue>) -> Result<LazyVal> {44 match self {45 LazyBinding::Bindable(v) => v(this, super_obj),46 LazyBinding::Bound(v) => Ok(v.clone()),47 }48 }49}5051struct EvaluationSettings {52 max_stack_frames: usize,53 max_stack_trace_size: usize,54 ext_vars: HashMap<Rc<str>, Val>,55 globals: HashMap<Rc<str>, Val>,56 import_resolver: Box<dyn ImportResolver>,57}58impl Default for EvaluationSettings {59 fn default() -> Self {60 EvaluationSettings {61 max_stack_frames: 200,62 max_stack_trace_size: 20,63 globals: Default::default(),64 ext_vars: Default::default(),65 import_resolver: Box::new(DummyImportResolver),66 }67 }68}6970#[derive(Default)]71struct EvaluationData {72 /// Used for stack-overflows and stacktraces73 stack: Vec<StackTraceElement>,74 /// Contains file source codes and evaluated results for imports and pretty75 /// printing stacktraces76 files: HashMap<Rc<PathBuf>, FileData>,77 str_files: HashMap<Rc<PathBuf>, Rc<str>>,78}7980pub struct FileData(Rc<str>, LocExpr, Option<Val>);81#[derive(Default)]82pub struct EvaluationStateInternals {83 data: RefCell<EvaluationData>,84 settings: RefCell<EvaluationSettings>,85}8687thread_local! {88 /// Contains state for currently executing file89 /// Global state is fine there90 pub(crate) static EVAL_STATE: RefCell<Option<EvaluationState>> = RefCell::new(None)91}92pub(crate) fn with_state<T>(f: impl FnOnce(&EvaluationState) -> T) -> T {93 EVAL_STATE.with(|s| f(s.borrow().as_ref().unwrap()))94}95pub fn create_error(err: Error) -> LocError {96 with_state(|s| s.error(err))97}98pub fn create_error_result<T>(err: Error) -> Result<T> {99 Err(with_state(|s| s.error(err)))100}101pub(crate) fn push<T>(102 e: &Option<ExprLocation>,103 comment: &str,104 f: impl FnOnce() -> Result<T>,105) -> Result<T> {106 if e.is_some() {107 with_state(|s| s.push(e.clone().unwrap(), comment.to_owned(), f))108 } else {109 f()110 }111}112113/// Maintains stack trace and import resolution114#[derive(Default, Clone)]115pub struct EvaluationState(Rc<EvaluationStateInternals>);116impl EvaluationState {117 fn data(&self) -> Ref<EvaluationData> {118 self.0.data.borrow()119 }120 fn data_mut(&self) -> RefMut<EvaluationData> {121 self.0.data.borrow_mut()122 }123 fn settings(&self) -> Ref<EvaluationSettings> {124 self.0.settings.borrow()125 }126 fn settings_mut(&self) -> RefMut<EvaluationSettings> {127 self.0.settings.borrow_mut()128 }129130 pub fn set_import_resolver(&self, resolver: Box<dyn ImportResolver>) {131 self.settings_mut().import_resolver = resolver;132 }133 pub fn import_resolver(&self) -> Ref<dyn ImportResolver> {134 Ref::map(self.settings(), |s|&*s.import_resolver)135 }136137 pub fn evaluate_file_to_json(138 &self,139 path: &PathBuf,140 ) -> std::result::Result<Rc<str>, LocError> {141 self.import_file(&PathBuf::new(), &path).and_then(|v|v.into_json(4))142 }143 pub fn add_file(144 &self,145 name: Rc<PathBuf>,146 code: Rc<str>,147 ) -> std::result::Result<(), ParseError> {148 self.data_mut().files.insert(149 name.clone(),150 FileData(151 code.clone(),152 parse(153 &code,154 &ParserSettings {155 file_name: name,156 loc_data: true,157 },158 )?,159 None,160 ),161 );162163 Ok(())164 }165 pub fn add_parsed_file(166 &self,167 name: Rc<PathBuf>,168 code: Rc<str>,169 parsed: LocExpr,170 ) -> std::result::Result<(), ()> {171 self.data_mut()172 .files173 .insert(name, FileData(code, parsed, None));174175 Ok(())176 }177 pub fn get_source(&self, name: &PathBuf) -> Option<Rc<str>> {178 let ro_map = &self.data().files;179 ro_map.get(name).map(|value| value.0.clone())180 }181 pub fn evaluate_file(&self, name: &PathBuf) -> Result<Val> {182 self.run_in_state(|| {183 let expr: LocExpr = {184 let ro_map = &self.data().files;185 let value = ro_map186 .get(name)187 .unwrap_or_else(|| panic!("file not added: {:?}", name));188 if value.2.is_some() {189 return Ok(value.2.clone().unwrap());190 }191 value.1.clone()192 };193 let value = evaluate(self.create_default_context()?, &expr)?;194 {195 self.0196 .data.borrow_mut()197 .files198 .get_mut(name)199 .unwrap()200 .2201 .replace(value.clone());202 }203 Ok(value)204 })205 }206 pub(crate) fn import_file(&self, from: &PathBuf, path: &PathBuf) -> Result<Val> {207 let file_path = self.settings().import_resolver.resolve_file(from, path)?;208 {209 let files = &self.data().files;210 if files.contains_key(&file_path) {211 return self.evaluate_file(&file_path);212 }213 }214 let contents = self.settings().import_resolver.load_file_contents(&file_path)?;215 self.add_file(file_path.clone(), contents).map_err(|e| {216 create_error(Error::ImportSyntaxError(e))217 })?;218 self.evaluate_file(&file_path)219 }220 pub(crate) fn import_file_str(&self, from: &PathBuf, path: &PathBuf) -> Result<Rc<str>> {221 let path = self.settings().import_resolver.resolve_file(from, path)?;222 if !self.data().str_files.contains_key(&path) {223 let file_str = self.settings().import_resolver.load_file_contents(&path)?;224 self.data_mut()225 .str_files226 .insert(path.clone(), file_str);227 }228 Ok(self.data().str_files.get(&path).cloned().unwrap())229 }230231 pub fn parse_evaluate_raw(&self, code: &str) -> Result<Val> {232 let parsed = parse(233 &code,234 &ParserSettings {235 file_name: Rc::new(PathBuf::from("raw.jsonnet")),236 loc_data: true,237 },238 )239 .unwrap();240 self.evaluate_raw(parsed)241 }242243 pub fn evaluate_raw(&self, code: LocExpr) -> Result<Val> {244 self.run_in_state(|| evaluate(self.create_default_context()?, &code))245 }246247 pub fn add_global(&self, name: Rc<str>, value: Val) {248 self.settings_mut().globals.insert(name, value);249 }250 pub fn add_ext_var(&self, name: Rc<str>, value: Val) {251 self.settings_mut().ext_vars.insert(name, value);252 }253 pub fn set_max_trace(&self, max_trace: usize) {254 self.settings_mut().max_stack_trace_size = max_trace;255 }256 pub fn set_max_stack(&self, max_stack: usize) {257 self.settings_mut().max_stack_frames = max_stack;258 }259260 pub fn with_stdlib(&self) -> &Self {261 let std_path = Rc::new(PathBuf::from("std.jsonnet"));262 self.run_in_state(|| {263 use jrsonnet_stdlib::STDLIB_STR;264 let mut parsed = false;265 #[cfg(feature = "codegenerated-stdlib")]266 if !parsed {267 parsed = true;268 #[allow(clippy::all)]269 let stdlib = {270 use jrsonnet_parser::*;271 include!(concat!(env!("OUT_DIR"), "/stdlib.rs"))272 };273 self.add_parsed_file(std_path.clone(), STDLIB_STR.to_owned().into(), stdlib)274 .unwrap();275 }276277 #[cfg(feature = "serialized-stdlib")]278 if !parsed {279 parsed = true;280 self.add_parsed_file(281 std_path.clone(),282 STDLIB_STR.to_owned().into(),283 bincode::deserialize(include_bytes!(concat!(284 env!("OUT_DIR"),285 "/stdlib.bincode"286 )))287 .expect("deserialize stdlib"),288 )289 .unwrap();290 }291292 if !parsed {293 self.add_file(std_path, STDLIB_STR.to_owned().into())294 .unwrap();295 }296 let val = self.evaluate_file(&PathBuf::from("std.jsonnet")).unwrap();297 self.add_global("std".into(), val);298 });299 self300 }301302 pub fn create_default_context(&self) -> Result<Context> {303 let globals = &self.settings().globals;304 let mut new_bindings: HashMap<Rc<str>, LazyBinding> = HashMap::new();305 for (name, value) in globals.iter() {306 new_bindings.insert(307 name.clone(),308 LazyBinding::Bound(resolved_lazy_val!(value.clone())),309 );310 }311 Context::new().extend_unbound(new_bindings, None, None, None)312 }313314 /// Executes code, creating new stack frame315 pub fn push<T>(316 &self,317 e: ExprLocation,318 comment: String,319 f: impl FnOnce() -> Result<T>,320 ) -> Result<T> {321 {322 let mut data = self.data_mut();323 let stack = &mut data.stack;324 if stack.len() > self.settings().max_stack_frames {325 // Error creation uses data, so i drop guard here326 drop(data);327 return Err(self.error(Error::StackOverflow));328 } else {329 stack.push(StackTraceElement(e, comment));330 }331 }332 let result = f();333 self.data_mut().stack.pop();334 result335 }336337 /// Returns current stack trace338 pub fn stack_trace(&self) -> StackTrace {339 StackTrace(340 self.data()341 .stack342 .iter()343 .rev()344 .take(self.settings().max_stack_trace_size)345 .cloned()346 .collect(),347 )348 }349350 /// Creates error with stack trace351 pub fn error(&self, err: Error) -> LocError {352 LocError(err, self.stack_trace())353 }354355 /// Runs passed function in state (required, if function needs to modify stack trace)356 pub fn run_in_state<T>(&self, f: impl FnOnce() -> T) -> T {357 EVAL_STATE.with(|v| {358 let has_state = v.borrow().is_some();359 if !has_state {360 v.borrow_mut().replace(self.clone());361 }362 let result = f();363 if !has_state {364 v.borrow_mut().take();365 }366 result367 })368 }369}370371#[cfg(test)]372pub mod tests {373 use super::Val;374 use crate::EvaluationState;375 use jrsonnet_parser::*;376 use std::{path::PathBuf, rc::Rc};377378 #[test]379 fn eval_state_stacktrace() {380 let state = EvaluationState::default();381 state382 .push(383 ExprLocation(Rc::new(PathBuf::from("test1.jsonnet")), 10, 20),384 "outer".to_owned(),385 || {386 state.push(387 ExprLocation(Rc::new(PathBuf::from("test2.jsonnet")), 30, 40),388 "inner".to_owned(),389 || {390 Ok(())391 },392 )?;393 Ok(())394 },395 )396 .unwrap();397 }398399 #[test]400 fn eval_state_standard() {401 let state = EvaluationState::default();402 state.with_stdlib();403 assert_eq!(404 state405 .parse_evaluate_raw(r#"std.assertEqual(std.base64("test"), "dGVzdA==")"#)406 .unwrap(),407 Val::Bool(true)408 );409 }410411 macro_rules! eval {412 ($str: expr) => {413 EvaluationState::default()414 .with_stdlib()415 .parse_evaluate_raw($str)416 .unwrap()417 };418 }419 macro_rules! eval_json {420 ($str: expr) => {{421 let evaluator = EvaluationState::default();422 evaluator.with_stdlib();423 evaluator.run_in_state(||{424 evaluator425 .parse_evaluate_raw($str)426 .unwrap()427 .into_json(0)428 .unwrap()429 .replace("\n", "")430 })431 }}432 }433434 /// Asserts given code returns `true`435 macro_rules! assert_eval {436 ($str: expr) => {437 assert_eq!(eval!($str), Val::Bool(true))438 };439 }440441 /// Asserts given code returns `false`442 macro_rules! assert_eval_neg {443 ($str: expr) => {444 assert_eq!(eval!($str), Val::Bool(false))445 };446 }447 macro_rules! assert_json {448 ($str: expr, $out: expr) => {449 assert_eq!(eval_json!($str), $out.replace("\t", ""))450 };451 }452453 /// Sanity checking, before trusting to another tests454 #[test]455 fn equality_operator() {456 assert_eval!("2 == 2");457 assert_eval_neg!("2 != 2");458 assert_eval!("2 != 3");459 assert_eval_neg!("2 == 3");460 assert_eval!("'Hello' == 'Hello'");461 assert_eval_neg!("'Hello' != 'Hello'");462 assert_eval!("'Hello' != 'World'");463 assert_eval_neg!("'Hello' == 'World'");464 }465466 #[test]467 fn math_evaluation() {468 assert_eval!("2 + 2 * 2 == 6");469 assert_eval!("3 + (2 + 2 * 2) == 9");470 }471472 #[test]473 fn string_concat() {474 assert_eval!("'Hello' + 'World' == 'HelloWorld'");475 assert_eval!("'Hello' * 3 == 'HelloHelloHello'");476 assert_eval!("'Hello' + 'World' * 3 == 'HelloWorldWorldWorld'");477 }478479 #[test]480 fn faster_join() {481 assert_eval!("std.join([0,0], [[1,2],[3,4],[5,6]]) == [1,2,0,0,3,4,0,0,5,6]");482 assert_eval!("std.join(',', ['1','2','3','4']) == '1,2,3,4'");483 }484485 #[test]486 fn function_contexts() {487 assert_eval!(488 r#"489 local k = {490 t(name = self.h): [self.h, name],491 h: 3,492 };493 local f = {494 t: k.t(),495 h: 4,496 };497 f.t[0] == f.t[1]498 "#499 );500 }501502 #[test]503 fn local() {504 assert_eval!("local a = 2; local b = 3; a + b == 5");505 assert_eval!("local a = 1, b = a + 1; a + b == 3");506 assert_eval!("local a = 1; local a = 2; a == 2");507 }508509 #[test]510 fn object_lazyness() {511 assert_json!("local a = {a:error 'test'}; {}", r#"{}"#);512 }513514 #[test]515 fn object_inheritance() {516 assert_json!("{a: self.b} + {b:3}", r#"{"a": 3,"b": 3}"#);517 }518519 #[test]520 fn object_assertion_success() {521 eval!("{assert \"a\" in self} + {a:2}");522 }523524 #[test]525 fn object_assertion_error() {526 eval!("{assert \"a\" in self}");527 }528529 #[test]530 fn lazy_args() {531 eval!("local test(a) = 2; test(error '3')");532 }533534 #[test]535 #[should_panic]536 fn tailstrict_args() {537 eval!("local test(a) = 2; test(error '3') tailstrict");538 }539540 #[test]541 #[should_panic]542 fn no_binding_error() {543 eval!("a");544 }545546 #[test]547 fn test_object() {548 assert_json!("{a:2}", r#"{"a": 2}"#);549 assert_json!("{a:2+2}", r#"{"a": 4}"#);550 assert_json!("{a:2}+{b:2}", r#"{"a": 2,"b": 2}"#);551 assert_json!("{b:3}+{b:2}", r#"{"b": 2}"#);552 assert_json!("{b:3}+{b+:2}", r#"{"b": 5}"#);553 assert_json!("local test='a'; {[test]:2}", r#"{"a": 2}"#);554 assert_json!(555 r#"556 {557 name: "Alice",558 welcome: "Hello " + self.name + "!",559 }560 "#,561 r#"{"name": "Alice","welcome": "Hello Alice!"}"#562 );563 assert_json!(564 r#"565 {566 name: "Alice",567 welcome: "Hello " + self.name + "!",568 } + {569 name: "Bob"570 }571 "#,572 r#"{"name": "Bob","welcome": "Hello Bob!"}"#573 );574 }575576 #[test]577 fn functions() {578 assert_json!(r#"local a = function(b, c = 2) b + c; a(2)"#, "4");579 assert_json!(580 r#"local a = function(b, c = "Dear") b + c + d, d = "World"; a("Hello")"#,581 r#""HelloDearWorld""#582 );583 }584585 #[test]586 fn local_methods() {587 assert_json!(r#"local a(b, c = 2) = b + c; a(2)"#, "4");588 assert_json!(589 r#"local a(b, c = "Dear") = b + c + d, d = "World"; a("Hello")"#,590 r#""HelloDearWorld""#591 );592 }593594 #[test]595 fn object_locals() {596 assert_json!(r#"{local a = 3, b: a}"#, r#"{"b": 3}"#);597 assert_json!(r#"{local a = 3, local c = a, b: c}"#, r#"{"b": 3}"#);598 assert_json!(599 r#"{local a = function (b) {[b]:4}, test: a("test")}"#,600 r#"{"test": {"test": 4}}"#601 );602 }603604 #[test]605 fn object_comp() {606 assert_json!(607 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}"#,608 "{\"h1_2\": \"0a\",\"h1_3\": \"0a\",\"h1_4\": \"0a\",\"h2_3\": \"a1\",\"h2_4\": \"a1\",\"h3_2\": \"0a\",\"h3_4\": \"a1\"}"609 )610 }611612 #[test]613 fn direct_self() {614 println!(615 "{:#?}",616 eval!(617 r#"618 {619 local me = self,620 a: 3,621 b(): me.a,622 }623 "#624 )625 );626 }627628 #[test]629 fn indirect_self() {630 // `self` assigned to `me` was lost when being631 // referenced from field632 eval!(633 r#"{634 local me = self,635 a: 3,636 b: me.a,637 }.b"#638 );639 }640641 // We can't trust other tests (And official jsonnet testsuite), if assert is not working correctly642 #[test]643 fn std_assert_ok() {644 eval!("std.assertEqual(4.5 << 2, 16)");645 }646647 #[test]648 #[should_panic]649 fn std_assert_failure() {650 eval!("std.assertEqual(4.5 << 2, 15)");651 }652653 #[test]654 fn string_is_string() {655 assert_eq!(656 eval!("local arr = 'hello'; (!std.isArray(arr)) && (!std.isString(arr))"),657 Val::Bool(false)658 );659 }660661 #[test]662 fn base64_works() {663 assert_json!(r#"std.base64("test")"#, r#""dGVzdA==""#);664 }665666 #[test]667 fn utf8_chars() {668 assert_json!(669 r#"local c="😎";{c:std.codepoint(c),l:std.length(c)}"#,670 r#"{"c": 128526,"l": 1}"#671 )672 }673674 #[test]675 fn json() {676 assert_json!(677 r#"std.manifestJsonEx({a:3, b:4, c:6},"")"#,678 r#""{\n\"a\": 3,\n\"b\": 4,\n\"c\": 6\n}""#679 );680 }681682 #[test]683 fn test() {684 assert_json!(685 r#"[[a, b] for a in [1,2,3] for b in [4,5,6]]"#,686 "[[1,4],[1,5],[1,6],[2,4],[2,5],[2,6],[3,4],[3,5],[3,6]]"687 );688 }689690 #[test]691 fn sjsonnet() {692 eval!(693 r#"694 local x0 = {k: 1};695 local x1 = {k: x0.k + x0.k};696 local x2 = {k: x1.k + x1.k};697 local x3 = {k: x2.k + x2.k};698 local x4 = {k: x3.k + x3.k};699 local x5 = {k: x4.k + x4.k};700 local x6 = {k: x5.k + x5.k};701 local x7 = {k: x6.k + x6.k};702 local x8 = {k: x7.k + x7.k};703 local x9 = {k: x8.k + x8.k};704 local x10 = {k: x9.k + x9.k};705 local x11 = {k: x10.k + x10.k};706 local x12 = {k: x11.k + x11.k};707 local x13 = {k: x12.k + x12.k};708 local x14 = {k: x13.k + x13.k};709 local x15 = {k: x14.k + x14.k};710 local x16 = {k: x15.k + x15.k};711 local x17 = {k: x16.k + x16.k};712 local x18 = {k: x17.k + x17.k};713 local x19 = {k: x18.k + x18.k};714 local x20 = {k: x19.k + x19.k};715 local x21 = {k: x20.k + x20.k};716 x21.k717 "#718 );719 }720721 use test::Bencher;722723 // This test is commented out by default, because of huge compilation slowdown724 // #[bench]725 // fn bench_codegen(b: &mut Bencher) {726 // b.iter(|| {727 // #[allow(clippy::all)]728 // let stdlib = {729 // use jrsonnet_parser::*;730 // include!(concat!(env!("OUT_DIR"), "/stdlib.rs"))731 // };732 // stdlib733 // })734 // }735736 #[bench]737 fn bench_serialize(b: &mut Bencher) {738 b.iter(|| {739 bincode::deserialize::<jrsonnet_parser::LocExpr>(include_bytes!(concat!(740 env!("OUT_DIR"),741 "/stdlib.bincode"742 )))743 .expect("deserialize stdlib")744 })745 }746747 #[bench]748 fn bench_parse(b: &mut Bencher) {749 b.iter(|| {750 jrsonnet_parser::parse(751 jrsonnet_stdlib::STDLIB_STR,752 &jrsonnet_parser::ParserSettings {753 loc_data: true,754 file_name: Rc::new(PathBuf::from("std.jsonnet")),755 },756 )757 })758 }759}