difftreelog
feat(evaluator) add importStr
in: master
2 files changed
crates/jsonnet-evaluator/src/evaluate.rsdiffbeforeafterboth--- a/crates/jsonnet-evaluator/src/evaluate.rs
+++ b/crates/jsonnet-evaluator/src/evaluate.rs
@@ -1,6 +1,7 @@
use crate::{
context_creator, create_error, future_wrapper, lazy_val, push, with_state, Context,
ContextCreator, Error, FuncDesc, LazyBinding, LazyVal, ObjMember, ObjValue, Result, Val,
+ ValType,
};
use closure::closure;
use jsonnet_parser::{
@@ -726,9 +727,15 @@
lib_path.push(path);
with_state(|s| s.import_file(&lib_path))?
}
- _ => panic!(
- "evaluation not implemented: {:?}",
- LocExpr(expr.clone(), loc.clone())
- ),
+ ImportStr(path) => {
+ let mut file_path = loc
+ .clone()
+ .expect("imports can't be used without loc_data")
+ .0
+ .clone();
+ file_path.pop();
+ file_path.push(path);
+ Val::Str(with_state(|s| s.import_file_str(&file_path))?)
+ }
})
}
crates/jsonnet-evaluator/src/lib.rsdiffbeforeafterboth1#![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::*;2425type BindableFn = dyn Fn(Option<ObjValue>, Option<ObjValue>) -> Result<LazyVal>;26#[derive(Clone)]27pub enum LazyBinding {28 Bindable(Rc<BindableFn>),29 Bound(LazyVal),30}3132impl Debug for LazyBinding {33 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {34 write!(f, "LazyBinding")35 }36}37impl LazyBinding {38 pub fn evaluate(&self, this: Option<ObjValue>, super_obj: Option<ObjValue>) -> Result<LazyVal> {39 match self {40 LazyBinding::Bindable(v) => v(this, super_obj),41 LazyBinding::Bound(v) => Ok(v.clone()),42 }43 }44}4546pub struct EvaluationSettings {47 pub max_stack_frames: usize,48 pub max_stack_trace_size: usize,49 pub import_resolver: Box<dyn Fn(&PathBuf) -> String>,50}51impl Default for EvaluationSettings {52 fn default() -> Self {53 EvaluationSettings {54 max_stack_frames: 200,55 max_stack_trace_size: 20,56 import_resolver: Box::new(|path| {57 panic!("default EvaluationSettings have no support for import resolution, can't import {:?}", path)58 }),59 }60 }61}6263pub struct FileData(String, LocExpr, Option<Val>);64#[derive(Default)]65pub struct EvaluationStateInternals {66 /// Used for stack-overflows and stacktraces67 stack: RefCell<Vec<StackTraceElement>>,68 /// Contains file source codes and evaluated results for imports and pretty69 /// printing stacktraces70 files: RefCell<HashMap<PathBuf, FileData>>,71 str_files: RefCell<HashMap<PathBuf, String>>,72 globals: RefCell<HashMap<String, Val>>,7374 /// Values to use with std.extVar75 ext_vars: RefCell<HashMap<String, Val>>,7677 settings: EvaluationSettings,78}7980thread_local! {81 /// Contains state for currently executing file82 /// Global state is fine there83 pub(crate) static EVAL_STATE: RefCell<Option<EvaluationState>> = RefCell::new(None)84}85#[inline(always)]86pub(crate) fn with_state<T>(f: impl FnOnce(&EvaluationState) -> T) -> T {87 EVAL_STATE.with(88 #[inline(always)]89 |s| f(s.borrow().as_ref().unwrap()),90 )91}92pub(crate) fn create_error<T>(err: Error) -> Result<T> {93 with_state(|s| s.error(err))94}95#[inline(always)]96pub(crate) fn push<T>(e: LocExpr, comment: String, f: impl FnOnce() -> Result<T>) -> Result<T> {97 with_state(|s| s.push(e, comment, f))98}99100/// Maintains stack trace and import resolution101#[derive(Default, Clone)]102pub struct EvaluationState(Rc<EvaluationStateInternals>);103impl EvaluationState {104 pub fn new(settings: EvaluationSettings) -> Self {105 EvaluationState(Rc::new(EvaluationStateInternals {106 settings,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, path: &PathBuf) -> Result<Val> {175 if !self.0.files.borrow().contains_key(path) {176 let file_str = (self.0.settings.import_resolver)(path);177 self.add_file(path.clone(), file_str).unwrap();178 }179 self.evaluate_file_in_current_state(path)180 }181 pub(crate) fn import_file_str(&self, path: &PathBuf) -> Result<String> {182 if !self.0.str_files.borrow().contains_key(path) {183 let file_str = (self.0.settings.import_resolver)(path);184 self.0.str_files.borrow_mut().insert(path.clone(), file_str);185 }186 Ok(self.0.str_files.borrow().get(path).cloned().unwrap())187 }188189 pub fn parse_evaluate_raw(&self, code: &str) -> Result<Val> {190 let parsed = parse(191 &code,192 &ParserSettings {193 file_name: PathBuf::from("raw.jsonnet"),194 loc_data: true,195 },196 )197 .unwrap();198 self.evaluate_raw(parsed)199 }200201 pub fn evaluate_raw(&self, code: LocExpr) -> Result<Val> {202 self.begin_state();203 let value = evaluate(self.create_default_context()?, &code);204 self.end_state();205 value206 }207208 pub fn add_global(&self, name: String, value: Val) {209 self.0.globals.borrow_mut().insert(name, value);210 }211 pub fn add_ext_var(&self, name: String, value: Val) {212 self.0.ext_vars.borrow_mut().insert(name, value);213 }214215 pub fn with_stdlib(&self) -> &Self {216 self.begin_state();217 use jsonnet_stdlib::STDLIB_STR;218 if cfg!(feature = "serialized-stdlib") {219 self.add_parsed_file(220 PathBuf::from("std.jsonnet"),221 STDLIB_STR.to_owned(),222 bincode::deserialize(include_bytes!(concat!(env!("OUT_DIR"), "/stdlib.bincode")))223 .expect("deserialize stdlib"),224 )225 .unwrap();226 } else {227 self.add_file(PathBuf::from("std.jsonnet"), STDLIB_STR.to_owned())228 .unwrap();229 }230 let val = self.evaluate_file(&PathBuf::from("std.jsonnet")).unwrap();231 self.add_global("std".to_owned(), val);232 self.end_state();233 self234 }235236 pub fn create_default_context(&self) -> Result<Context> {237 let globals = self.0.globals.borrow();238 let mut new_bindings: HashMap<String, LazyBinding> = HashMap::new();239 for (name, value) in globals.iter() {240 new_bindings.insert(241 name.clone(),242 LazyBinding::Bound(resolved_lazy_val!(value.clone())),243 );244 }245 Context::new().extend_unbound(new_bindings, None, None, None)246 }247248 #[inline(always)]249 pub fn push<T>(&self, e: LocExpr, comment: String, f: impl FnOnce() -> Result<T>) -> Result<T> {250 {251 let mut stack = self.0.stack.borrow_mut();252 if stack.len() > self.0.settings.max_stack_frames {253 drop(stack);254 return self.error(Error::StackOverflow);255 } else {256 stack.push(StackTraceElement(e, comment));257 }258 }259 let result = f();260 self.0.stack.borrow_mut().pop();261 result262 }263 pub fn print_stack_trace(&self) {264 for e in self.stack_trace().0 {265 println!("{:?} - {:?}", e.0, e.1)266 }267 }268 pub fn stack_trace(&self) -> StackTrace {269 StackTrace(270 self.0271 .stack272 .borrow()273 .iter()274 .rev()275 .take(self.0.settings.max_stack_trace_size)276 .cloned()277 .collect(),278 )279 }280 pub fn error<T>(&self, err: Error) -> Result<T> {281 Err(LocError(err, self.stack_trace()))282 }283284 fn begin_state(&self) {285 EVAL_STATE.with(|v| v.borrow_mut().replace(self.clone()));286 }287 fn end_state(&self) {288 EVAL_STATE.with(|v| v.borrow_mut().take());289 }290}291292#[cfg(test)]293pub mod tests {294 use super::Val;295 use crate::EvaluationState;296 use jsonnet_parser::*;297 use std::path::PathBuf;298299 #[test]300 fn eval_state_stacktrace() {301 let state = EvaluationState::default();302 state303 .push(304 loc_expr!(305 Expr::Num(0.0),306 true,307 (PathBuf::from("test1.jsonnet"), 10, 20)308 ),309 "outer".to_owned(),310 || {311 state.push(312 loc_expr!(313 Expr::Num(0.0),314 true,315 (PathBuf::from("test2.jsonnet"), 30, 40)316 ),317 "inner".to_owned(),318 || {319 state.print_stack_trace();320 Ok(())321 },322 )?;323 Ok(())324 },325 )326 .unwrap();327 }328329 #[test]330 fn eval_state_standard() {331 let state = EvaluationState::default();332 state.with_stdlib();333 assert_eq!(334 state335 .parse_evaluate_raw(r#"std.assertEqual(std.base64("test"), "dGVzdA==")"#)336 .unwrap(),337 Val::Bool(true)338 );339 }340341 macro_rules! eval {342 ($str: expr) => {343 EvaluationState::default()344 .with_stdlib()345 .parse_evaluate_raw($str)346 .unwrap()347 };348 }349 macro_rules! eval_json {350 ($str: expr) => {{351 let evaluator = EvaluationState::default();352 evaluator.with_stdlib();353 let val = evaluator.parse_evaluate_raw($str).unwrap();354 evaluator.add_global("__tmp__to_yaml__".to_owned(), val);355 evaluator356 .parse_evaluate_raw("std.manifestJsonEx(__tmp__to_yaml__, \"\")")357 .unwrap()358 .try_cast_str("there should be json string")359 .unwrap()360 .clone()361 .replace("\n", "")362 }};363 }364365 /// Asserts given code returns `true`366 macro_rules! assert_eval {367 ($str: expr) => {368 assert_eq!(eval!($str), Val::Bool(true))369 };370 }371372 /// Asserts given code returns `false`373 macro_rules! assert_eval_neg {374 ($str: expr) => {375 assert_eq!(eval!($str), Val::Bool(false))376 };377 }378 macro_rules! assert_json {379 ($str: expr, $out: expr) => {380 assert_eq!(eval_json!($str), $out.replace("\t", ""))381 };382 }383384 /// Sanity checking, before trusting to another tests385 #[test]386 fn equality_operator() {387 assert_eval!("2 == 2");388 assert_eval_neg!("2 != 2");389 assert_eval!("2 != 3");390 assert_eval_neg!("2 == 3");391 assert_eval!("'Hello' == 'Hello'");392 assert_eval_neg!("'Hello' != 'Hello'");393 assert_eval!("'Hello' != 'World'");394 assert_eval_neg!("'Hello' == 'World'");395 }396397 #[test]398 fn math_evaluation() {399 assert_eval!("2 + 2 * 2 == 6");400 assert_eval!("3 + (2 + 2 * 2) == 9");401 }402403 #[test]404 fn string_concat() {405 assert_eval!("'Hello' + 'World' == 'HelloWorld'");406 assert_eval!("'Hello' * 3 == 'HelloHelloHello'");407 assert_eval!("'Hello' + 'World' * 3 == 'HelloWorldWorldWorld'");408 }409410 #[test]411 fn function_contexts() {412 assert_eval!(413 r#"414 local k = {415 t(name = self.h): [self.h, name],416 h: 3,417 };418 local f = {419 t: k.t(),420 h: 4,421 };422 f.t[0] == f.t[1]423 "#424 );425 }426427 #[test]428 fn local() {429 assert_eval!("local a = 2; local b = 3; a + b == 5");430 assert_eval!("local a = 1, b = a + 1; a + b == 3");431 assert_eval!("local a = 1; local a = 2; a == 2");432 }433434 #[test]435 fn object_lazyness() {436 assert_json!("local a = {a:error 'test'}; {}", r#"{}"#);437 }438439 /// FIXME: This test gets stackoverflow in debug build440 #[test]441 fn object_inheritance() {442 assert_json!("{a: self.b} + {b:3}", r#"{"a": 3,"b": 3}"#);443 }444445 #[test]446 fn test_object() {447 assert_json!("{a:2}", r#"{"a": 2}"#);448 assert_json!("{a:2+2}", r#"{"a": 4}"#);449 assert_json!("{a:2}+{b:2}", r#"{"a": 2,"b": 2}"#);450 assert_json!("{b:3}+{b:2}", r#"{"b": 2}"#);451 assert_json!("{b:3}+{b+:2}", r#"{"b": 5}"#);452 assert_json!("local test='a'; {[test]:2}", r#"{"a": 2}"#);453 assert_json!(454 r#"455 {456 name: "Alice",457 welcome: "Hello " + self.name + "!",458 }459 "#,460 r#"{"name": "Alice","welcome": "Hello Alice!"}"#461 );462 assert_json!(463 r#"464 {465 name: "Alice",466 welcome: "Hello " + self.name + "!",467 } + {468 name: "Bob"469 }470 "#,471 r#"{"name": "Bob","welcome": "Hello Bob!"}"#472 );473 }474475 #[test]476 fn functions() {477 assert_json!(r#"local a = function(b, c = 2) b + c; a(2)"#, "4");478 assert_json!(479 r#"local a = function(b, c = "Dear") b + c + d, d = "World"; a("Hello")"#,480 r#""HelloDearWorld""#481 );482 }483484 #[test]485 fn local_methods() {486 assert_json!(r#"local a(b, c = 2) = b + c; a(2)"#, "4");487 assert_json!(488 r#"local a(b, c = "Dear") = b + c + d, d = "World"; a("Hello")"#,489 r#""HelloDearWorld""#490 );491 }492493 #[test]494 fn object_locals() {495 assert_json!(r#"{local a = 3, b: a}"#, r#"{"b": 3}"#);496 assert_json!(r#"{local a = 3, local c = a, b: c}"#, r#"{"b": 3}"#);497 assert_json!(498 r#"{local a = function (b) {[b]:4}, test: a("test")}"#,499 r#"{"test": {"test": 4}}"#500 );501 }502503 #[test]504 fn object_comp() {505 assert_json!(506 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}"#,507 "{\"h1_2\": \"0a\",\"h1_3\": \"0a\",\"h1_4\": \"0a\",\"h2_3\": \"a1\",\"h2_4\": \"a1\",\"h3_2\": \"0a\",\"h3_4\": \"a1\"}"508 )509 }510511 #[test]512 fn direct_self() {513 println!(514 "{:#?}",515 eval!(516 r#"517 {518 local me = self,519 a: 3,520 b(): me.a,521 }522 "#523 )524 );525 }526527 #[test]528 fn indirect_self() {529 // `self` assigned to `me` was lost when being530 // referenced from field531 eval!(532 r#"{533 local me = self,534 a: 3,535 b: me.a,536 }.b"#537 );538 }539540 // We can't trust other tests (And official jsonnet testsuite), if assert is not working correctly541 #[test]542 fn std_assert_ok() {543 eval!("std.assertEqual(4.5 << 2, 16)");544 }545546 #[test]547 #[should_panic]548 fn std_assert_failure() {549 eval!("std.assertEqual(4.5 << 2, 15)");550 }551552 #[test]553 fn string_is_string() {554 assert_eq!(555 eval!("local arr = 'hello'; (!std.isArray(arr)) && (!std.isString(arr))"),556 Val::Bool(false)557 );558 }559560 #[test]561 fn base64_works() {562 assert_json!(r#"std.base64("test")"#, r#""dGVzdA==""#);563 }564565 #[test]566 fn utf8_chars() {567 assert_json!(568 r#"local c="😎";{c:std.codepoint(c),l:std.length(c)}"#,569 r#"{"c": 128526,"l": 1}"#570 )571 }572573 #[test]574 fn json() {575 assert_json!(576 r#"std.manifestJsonEx({a:3, b:4, c:6},"")"#,577 r#""{\n\"a\": 3,\n\"b\": 4,\n\"c\": 6\n}""#578 );579 }580581 #[test]582 fn test() {583 assert_json!(584 r#"[[a, b] for a in [1,2,3] for b in [4,5,6]]"#,585 "[[1,4],[1,5],[1,6],[2,4],[2,5],[2,6],[3,4],[3,5],[3,6]]"586 );587 }588589 #[test]590 fn sjsonnet() {591 eval!(592 r#"593 local x0 = {k: 1};594 local x1 = {k: x0.k + x0.k};595 local x2 = {k: x1.k + x1.k};596 local x3 = {k: x2.k + x2.k};597 local x4 = {k: x3.k + x3.k};598 local x5 = {k: x4.k + x4.k};599 local x6 = {k: x5.k + x5.k};600 local x7 = {k: x6.k + x6.k};601 local x8 = {k: x7.k + x7.k};602 local x9 = {k: x8.k + x8.k};603 local x10 = {k: x9.k + x9.k};604 local x11 = {k: x10.k + x10.k};605 local x12 = {k: x11.k + x11.k};606 local x13 = {k: x12.k + x12.k};607 local x14 = {k: x13.k + x13.k};608 local x15 = {k: x14.k + x14.k};609 local x16 = {k: x15.k + x15.k};610 local x17 = {k: x16.k + x16.k};611 local x18 = {k: x17.k + x17.k};612 local x19 = {k: x18.k + x18.k};613 local x20 = {k: x19.k + x19.k};614 local x21 = {k: x20.k + x20.k};615 x21.k616 "#617 );618 }619}