difftreelog
perf(evaluator) deserialize instead of parsing std
in: master
3 files changed
crates/jsonnet-evaluator/Cargo.tomldiffbeforeafterboth--- a/crates/jsonnet-evaluator/Cargo.toml
+++ b/crates/jsonnet-evaluator/Cargo.toml
@@ -6,7 +6,25 @@
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
+[features]
+default = ["serialized-stdlib"]
+serialized-stdlib = ["serde", "bincode"]
+
[dependencies]
jsonnet-parser = { path = "../jsonnet-parser" }
closure = "0.3.0"
-jsonnet-stdlib = { version = "0.1.0", path = "../jsonnet-stdlib" }
+jsonnet-stdlib = { path = "../jsonnet-stdlib" }
+
+[dependencies.serde]
+version = "1.0.111"
+optional = true
+
+[dependencies.bincode]
+version = "1.2.1"
+optional = true
+
+[build-dependencies]
+jsonnet-parser = { path = "../jsonnet-parser" }
+jsonnet-stdlib = { path = "../jsonnet-stdlib" }
+serde = "1.0.111"
+bincode = "1.2.1"
crates/jsonnet-evaluator/build.rsdiffbeforeafterboth--- /dev/null
+++ b/crates/jsonnet-evaluator/build.rs
@@ -0,0 +1,21 @@
+use bincode::serialize;
+use jsonnet_parser::{parse, ParserSettings};
+use jsonnet_stdlib::STDLIB_STR;
+use std::{env, fs::File, io::Write, path::Path};
+
+fn main() {
+ let parsed = parse(
+ STDLIB_STR,
+ &ParserSettings {
+ file_name: "std.jsonnet".to_owned(),
+ loc_data: true,
+ },
+ )
+ .expect("parse");
+
+ let out_dir = env::var("OUT_DIR").unwrap();
+ let dest_path = Path::new(&out_dir).join("stdlib.bincode");
+ let mut f = File::create(&dest_path).unwrap();
+ f.write_all(&serialize(&parsed).expect("serialize"))
+ .unwrap();
+}
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)]5mod ctx;6mod dynamic;7mod error;8mod evaluate;9mod obj;10mod val;1112use closure::closure;13pub use ctx::*;14pub use dynamic::*;15pub use error::*;16pub use evaluate::*;17use jsonnet_parser::*;18pub use obj::*;19use std::{cell::RefCell, collections::HashMap, rc::Rc};20pub use val::*;2122rc_fn_helper!(23 Binding,24 binding,25 dyn Fn(Option<ObjValue>, Option<ObjValue>) -> Result<Val>26);27rc_fn_helper!(28 LazyBinding,29 lazy_binding,30 dyn Fn(Option<ObjValue>, Option<ObjValue>) -> Result<LazyVal>31);32rc_fn_helper!(FunctionRhs, function_rhs, dyn Fn(Context) -> Result<Val>);33rc_fn_helper!(34 FunctionDefault,35 function_default,36 dyn Fn(Context, LocExpr) -> Result<Val>37);3839pub struct FileData(String, LocExpr, Option<Val>);40#[derive(Default)]41pub struct EvaluationStateInternals {42 /// Used for stack-overflows and stacktraces43 stack: RefCell<Vec<StackTraceElement>>,44 /// Contains file source codes and evaluated results for imports and pretty printing stacktraces45 files: RefCell<HashMap<String, FileData>>,46 globals: RefCell<HashMap<String, Val>>,47}4849thread_local! {50 pub static EVAL_STATE: RefCell<Option<EvaluationState>> = RefCell::new(None)51}52pub(crate) fn with_state<T>(f: impl FnOnce(&EvaluationState) -> T) -> T {53 EVAL_STATE.with(|s| f(s.borrow().as_ref().unwrap()))54}55pub(crate) fn create_error<T>(err: Error) -> Result<T> {56 with_state(|s| s.error(err))57}58pub(crate) fn push<T>(e: LocExpr, comment: String, f: impl FnOnce() -> T) -> T {59 with_state(|s| s.push(e, comment, f))60}6162#[derive(Default, Clone)]63pub struct EvaluationState(Rc<EvaluationStateInternals>);64impl EvaluationState {65 pub fn add_file(66 &self,67 name: String,68 code: String,69 ) -> std::result::Result<(), Box<dyn std::error::Error>> {70 self.0.files.borrow_mut().insert(71 name.clone(),72 FileData(73 code.clone(),74 parse(75 &code,76 &ParserSettings {77 file_name: name,78 loc_data: true,79 },80 )?,81 None,82 ),83 );8485 Ok(())86 }87 pub fn get_source(&self, name: &str) -> String {88 let ro_map = self.0.files.borrow();89 let value = ro_map90 .get(name)91 .unwrap_or_else(|| panic!("file not added: {:?}", name));92 value.0.clone()93 }94 pub fn evaluate_file(&self, name: &str) -> Result<Val> {95 self.begin_state();96 let expr: LocExpr = {97 let ro_map = self.0.files.borrow();98 let value = ro_map99 .get(name)100 .unwrap_or_else(|| panic!("file not added: {:?}", name));101 if value.2.is_some() {102 return Ok(value.2.clone().unwrap());103 }104 value.1.clone()105 };106 let value = evaluate(self.create_default_context()?, &expr)?;107 {108 self.0109 .files110 .borrow_mut()111 .get_mut(name)112 .unwrap()113 .2114 .replace(value.clone());115 }116 self.end_state();117 Ok(value)118 }119120 pub fn parse_evaluate_raw(&self, code: &str) -> Result<Val> {121 let parsed = parse(122 &code,123 &ParserSettings {124 file_name: "raw.jsonnet".to_owned(),125 loc_data: true,126 },127 );128 self.begin_state();129 let value = evaluate(self.create_default_context()?, &parsed.unwrap());130 self.end_state();131 value132 }133134 pub fn add_stdlib(&self) {135 self.begin_state();136 use jsonnet_stdlib::STDLIB_STR;137 self.add_file("std.jsonnet".to_owned(), STDLIB_STR.to_owned())138 .unwrap();139 let val = self.evaluate_file("std.jsonnet").unwrap();140 self.0.globals.borrow_mut().insert("std".to_owned(), val);141 self.end_state();142 }143144 pub fn create_default_context(&self) -> Result<Context> {145 let globals = self.0.globals.borrow();146 let mut new_bindings: HashMap<String, LazyBinding> = HashMap::new();147 for (name, value) in globals.iter() {148 new_bindings.insert(149 name.clone(),150 lazy_binding!(151 closure!(clone value, |_self, _super_obj| Ok(lazy_val!(closure!(clone value, ||Ok(value.clone())))))152 ),153 );154 }155 Context::new().extend(new_bindings, None, None, None)156 }157158 pub fn push<T>(&self, e: LocExpr, comment: String, f: impl FnOnce() -> T) -> T {159 self.0160 .stack161 .borrow_mut()162 .push(StackTraceElement(e, comment));163 let result = f();164 self.0.stack.borrow_mut().pop();165 result166 }167 pub fn print_stack_trace(&self) {168 for e in self.stack_trace().0 {169 println!("{:?} - {:?}", e.0, e.1)170 }171 }172 pub fn stack_trace(&self) -> StackTrace {173 StackTrace(self.0.stack.borrow().iter().rev().cloned().collect())174 }175 pub fn error<T>(&self, err: Error) -> Result<T> {176 Err(LocError(err, self.stack_trace()))177 }178179 fn begin_state(&self) {180 EVAL_STATE.with(|v| v.borrow_mut().replace(self.clone()));181 }182 fn end_state(&self) {183 EVAL_STATE.with(|v| v.borrow_mut().take());184 }185}186187#[cfg(test)]188pub mod tests {189 use super::Val;190 use crate::EvaluationState;191 use jsonnet_parser::*;192193 #[test]194 fn eval_state_stacktrace() {195 let state = EvaluationState::default();196 state.push(197 loc_expr!(Expr::Num(0.0), true, ("test1.jsonnet".to_owned(), 10, 20)),198 "outer".to_owned(),199 || {200 state.push(201 loc_expr!(Expr::Num(0.0), true, ("test2.jsonnet".to_owned(), 30, 40)),202 "inner".to_owned(),203 || state.print_stack_trace(),204 );205 },206 );207 }208209 #[test]210 fn eval_state_standard() {211 let state = EvaluationState::default();212 state.add_stdlib();213 assert_eq!(214 state215 .parse_evaluate_raw(r#"std.assertEqual(std.base64("test"), "dGVzdA==w")"#)216 .unwrap(),217 Val::Bool(true)218 );219 }220221 macro_rules! eval {222 ($str: expr) => {223 evaluate(224 Context::new(),225 EvaluationState::default(),226 &parse(227 $str,228 &ParserSettings {229 loc_data: true,230 file_name: "test.jsonnet".to_owned(),231 },232 )233 .unwrap(),234 )235 };236 }237238 macro_rules! eval_stdlib {239 ($str: expr) => {{240 let std = "local std = ".to_owned() + jsonnet_stdlib::STDLIB_STR + ";";241 evaluate(242 Context::new(),243 EvaluationState::default(),244 &parse(245 &(std + $str),246 &ParserSettings {247 loc_data: true,248 file_name: "test.jsonnet".to_owned(),249 },250 )251 .unwrap(),252 )253 }};254 }255256 macro_rules! assert_eval {257 ($str: expr) => {258 assert_eq!(259 evaluate(260 Context::new(),261 EvaluationState::default(),262 &parse(263 $str,264 &ParserSettings {265 loc_data: true,266 file_name: "test.jsonnet".to_owned(),267 }268 )269 .unwrap()270 ),271 Val::Bool(true)272 )273 };274 }275 macro_rules! assert_json {276 ($str: expr, $out: expr) => {277 assert_eq!(278 format!(279 "{}",280 evaluate(281 Context::new(),282 EvaluationState::default(),283 &parse(284 $str,285 &ParserSettings {286 loc_data: true,287 file_name: "test.jsonnet".to_owned(),288 }289 )290 .unwrap()291 )292 ),293 $out294 )295 };296 }297 macro_rules! assert_json_stdlib {298 ($str: expr, $out: expr) => {299 assert_eq!(format!("{}", eval_stdlib!($str)), $out)300 };301 }302 macro_rules! assert_eval_neg {303 ($str: expr) => {304 assert_eq!(305 evaluate(306 Context::new(),307 EvaluationState::default(),308 &parse(309 $str,310 &ParserSettings {311 loc_data: true,312 file_name: "test.jsonnet".to_owned(),313 }314 )315 .unwrap()316 ),317 Val::Bool(false)318 )319 };320 }321322 /*323 /// Sanity checking, before trusting to another tests324 #[test]325 fn equality_operator() {326 assert_eval!("2 == 2");327 assert_eval_neg!("2 != 2");328 assert_eval!("2 != 3");329 assert_eval_neg!("2 == 3");330 assert_eval!("'Hello' == 'Hello'");331 assert_eval_neg!("'Hello' != 'Hello'");332 assert_eval!("'Hello' != 'World'");333 assert_eval_neg!("'Hello' == 'World'");334 }335336 #[test]337 fn math_evaluation() {338 assert_eval!("2 + 2 * 2 == 6");339 assert_eval!("3 + (2 + 2 * 2) == 9");340 }341342 #[test]343 fn string_concat() {344 assert_eval!("'Hello' + 'World' == 'HelloWorld'");345 assert_eval!("'Hello' * 3 == 'HelloHelloHello'");346 assert_eval!("'Hello' + 'World' * 3 == 'HelloWorldWorldWorld'");347 }348349 #[test]350 fn local() {351 assert_eval!("local a = 2; local b = 3; a + b == 5");352 assert_eval!("local a = 1, b = a + 1; a + b == 3");353 assert_eval!("local a = 1; local a = 2; a == 2");354 }355356 #[test]357 fn object_lazyness() {358 assert_json!("local a = {a:error 'test'}; {}", r#"{}"#);359 }360361 #[test]362 fn object_inheritance() {363 assert_json!("{a: self.b} + {b:3}", r#"{"a":3,"b":3}"#);364 }365366 #[test]367 fn test_object() {368 assert_json!("{a:2}", r#"{"a":2}"#);369 assert_json!("{a:2+2}", r#"{"a":4}"#);370 assert_json!("{a:2}+{b:2}", r#"{"a":2,"b":2}"#);371 assert_json!("{b:3}+{b:2}", r#"{"b":2}"#);372 assert_json!("{b:3}+{b+:2}", r#"{"b":5}"#);373 assert_json!("local test='a'; {[test]:2}", r#"{"a":2}"#);374 assert_json!(375 r#"376 {377 name: "Alice",378 welcome: "Hello " + self.name + "!",379 }380 "#,381 r#"{"name":"Alice","welcome":"Hello Alice!"}"#382 );383 assert_json!(384 r#"385 {386 name: "Alice",387 welcome: "Hello " + self.name + "!",388 } + {389 name: "Bob"390 }391 "#,392 r#"{"name":"Bob","welcome":"Hello Bob!"}"#393 );394 }395396 #[test]397 fn functions() {398 assert_json!(r#"local a = function(b, c = 2) b + c; a(2)"#, "4");399 assert_json!(400 r#"local a = function(b, c = "Dear") b + c + d, d = "World"; a("Hello")"#,401 r#""HelloDearWorld""#402 );403 }404405 #[test]406 fn local_methods() {407 assert_json!(r#"local a(b, c = 2) = b + c; a(2)"#, "4");408 assert_json!(409 r#"local a(b, c = "Dear") = b + c + d, d = "World"; a("Hello")"#,410 r#""HelloDearWorld""#411 );412 }413414 #[test]415 fn object_locals() {416 assert_json!(r#"{local a = 3, b: a}"#, r#"{"b":3}"#);417 assert_json!(r#"{local a = 3, local c = a, b: c}"#, r#"{"b":3}"#);418 assert_json!(419 r#"{local a = function (b) {[b]:4}, test: a("test")}"#,420 r#"{"test":{"test":4}}"#421 );422 }423424 #[test]425 fn direct_self() {426 println!(427 "{:#?}",428 eval!(429 r#"430 {431 local me = self,432 a: 3,433 b(): me.a,434 }435 "#436 )437 );438 }439440 #[test]441 fn indirect_self() {442 // `self` assigned to `me` was lost when being443 // referenced from field444 eval_stdlib!(445 r#"{446 local me = self,447 a: 3,448 b: me.a,449 }.b"#450 );451 }452453 // We can't trust other tests (And official jsonnet testsuite), if assert is not working correctly454 #[test]455 fn std_assert_ok() {456 eval_stdlib!("std.assertEqual(4.5 << 2, 16)");457 }458459 #[test]460 #[should_panic]461 fn std_assert_failure() {462 eval_stdlib!("std.assertEqual(4.5 << 2, 15)");463 }464465 #[test]466 fn string_is_string() {467 assert_eq!(468 eval_stdlib!("local arr = 'hello'; (!std.isArray(arr)) && (!std.isString(arr))"),469 Val::Bool(false)470 );471 }472473 #[test]474 fn base64_works() {475 assert_json_stdlib!(r#"std.base64("test")"#, r#""dGVzdA==""#);476 }477478 #[test]479 fn utf8_chars() {480 assert_json_stdlib!(481 r#"local c="😎";{c:std.codepoint(c),l:std.length(c)}"#,482 r#"{"c":128526,"l":1}"#483 )484 }485486 #[test]487 fn json() {488 assert_json_stdlib!(489 r#"std.manifestJsonEx({a:3, b:4, c:6},"")"#,490 r#""{\n"a": 3,\n"b": 4,\n"c": 6\n}""#491 );492 }493494 #[test]495 fn test() {496 assert_json_stdlib!(497 r#"[[a, b] for a in [1,2,3] for b in [4,5,6]]"#,498 "[[1,4],[1,5],[1,6],[2,4],[2,5],[2,6],[3,4],[3,5],[3,6]]"499 );500 }501502 #[test]503 fn sjsonnet() {504 eval!(505 r#"506 local x0 = {k: 1};507 local x1 = {k: x0.k + x0.k};508 local x2 = {k: x1.k + x1.k};509 local x3 = {k: x2.k + x2.k};510 local x4 = {k: x3.k + x3.k};511 local x5 = {k: x4.k + x4.k};512 local x6 = {k: x5.k + x5.k};513 local x7 = {k: x6.k + x6.k};514 local x8 = {k: x7.k + x7.k};515 local x9 = {k: x8.k + x8.k};516 local x10 = {k: x9.k + x9.k};517 local x11 = {k: x10.k + x10.k};518 local x12 = {k: x11.k + x11.k};519 local x13 = {k: x12.k + x12.k};520 local x14 = {k: x13.k + x13.k};521 local x15 = {k: x14.k + x14.k};522 local x16 = {k: x15.k + x15.k};523 local x17 = {k: x16.k + x16.k};524 local x18 = {k: x17.k + x17.k};525 local x19 = {k: x18.k + x18.k};526 local x20 = {k: x19.k + x19.k};527 local x21 = {k: x20.k + x20.k};528 x21.k529 "#530 );531 }532 */533}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)]5mod ctx;6mod dynamic;7mod error;8mod evaluate;9mod obj;10mod val;1112use closure::closure;13pub use ctx::*;14pub use dynamic::*;15pub use error::*;16pub use evaluate::*;17use jsonnet_parser::*;18pub use obj::*;19use std::{cell::RefCell, collections::HashMap, rc::Rc};20pub use val::*;2122rc_fn_helper!(23 Binding,24 binding,25 dyn Fn(Option<ObjValue>, Option<ObjValue>) -> Result<Val>26);27rc_fn_helper!(28 LazyBinding,29 lazy_binding,30 dyn Fn(Option<ObjValue>, Option<ObjValue>) -> Result<LazyVal>31);32rc_fn_helper!(FunctionRhs, function_rhs, dyn Fn(Context) -> Result<Val>);33rc_fn_helper!(34 FunctionDefault,35 function_default,36 dyn Fn(Context, LocExpr) -> Result<Val>37);3839pub struct FileData(String, LocExpr, Option<Val>);40#[derive(Default)]41pub struct EvaluationStateInternals {42 /// Used for stack-overflows and stacktraces43 stack: RefCell<Vec<StackTraceElement>>,44 /// Contains file source codes and evaluated results for imports and pretty45 /// printing stacktraces46 files: RefCell<HashMap<String, FileData>>,47 globals: RefCell<HashMap<String, Val>>,48}4950thread_local! {51 pub static EVAL_STATE: RefCell<Option<EvaluationState>> = RefCell::new(None)52}53pub(crate) fn with_state<T>(f: impl FnOnce(&EvaluationState) -> T) -> T {54 EVAL_STATE.with(|s| f(s.borrow().as_ref().unwrap()))55}56pub(crate) fn create_error<T>(err: Error) -> Result<T> {57 with_state(|s| s.error(err))58}59pub(crate) fn push<T>(e: LocExpr, comment: String, f: impl FnOnce() -> T) -> T {60 with_state(|s| s.push(e, comment, f))61}6263#[derive(Default, Clone)]64pub struct EvaluationState(Rc<EvaluationStateInternals>);65impl EvaluationState {66 pub fn add_file(67 &self,68 name: String,69 code: String,70 ) -> std::result::Result<(), Box<dyn std::error::Error>> {71 self.0.files.borrow_mut().insert(72 name.clone(),73 FileData(74 code.clone(),75 parse(76 &code,77 &ParserSettings {78 file_name: name,79 loc_data: true,80 },81 )?,82 None,83 ),84 );8586 Ok(())87 }88 pub fn add_parsed_file(89 &self,90 name: String,91 code: String,92 parsed: LocExpr,93 ) -> std::result::Result<(), Box<dyn std::error::Error>> {94 self.095 .files96 .borrow_mut()97 .insert(name, FileData(code, parsed, None));9899 Ok(())100 }101 pub fn get_source(&self, name: &str) -> String {102 let ro_map = self.0.files.borrow();103 let value = ro_map104 .get(name)105 .unwrap_or_else(|| panic!("file not added: {:?}", name));106 value.0.clone()107 }108 pub fn evaluate_file(&self, name: &str) -> Result<Val> {109 self.begin_state();110 let expr: LocExpr = {111 let ro_map = self.0.files.borrow();112 let value = ro_map113 .get(name)114 .unwrap_or_else(|| panic!("file not added: {:?}", name));115 if value.2.is_some() {116 return Ok(value.2.clone().unwrap());117 }118 value.1.clone()119 };120 let value = evaluate(self.create_default_context()?, &expr)?;121 {122 self.0123 .files124 .borrow_mut()125 .get_mut(name)126 .unwrap()127 .2128 .replace(value.clone());129 }130 self.end_state();131 Ok(value)132 }133134 pub fn parse_evaluate_raw(&self, code: &str) -> Result<Val> {135 let parsed = parse(136 &code,137 &ParserSettings {138 file_name: "raw.jsonnet".to_owned(),139 loc_data: true,140 },141 );142 self.begin_state();143 let value = evaluate(self.create_default_context()?, &parsed.unwrap());144 self.end_state();145 value146 }147148 pub fn add_stdlib(&self) {149 self.begin_state();150 use jsonnet_stdlib::STDLIB_STR;151 if cfg!(feature = "serialized-stdlib") {152 self.add_parsed_file(153 "std.jsonnet".to_owned(),154 STDLIB_STR.to_owned(),155 bincode::deserialize(include_bytes!(concat!(env!("OUT_DIR"), "/stdlib.bincode"))).expect("deserialize stdlib"),156 ).unwrap();157 } else {158 self.add_file("std.jsonnet".to_owned(), STDLIB_STR.to_owned())159 .unwrap();160 }161 let val = self.evaluate_file("std.jsonnet").unwrap();162 self.0.globals.borrow_mut().insert("std".to_owned(), val);163 self.end_state();164 }165166 pub fn create_default_context(&self) -> Result<Context> {167 let globals = self.0.globals.borrow();168 let mut new_bindings: HashMap<String, LazyBinding> = HashMap::new();169 for (name, value) in globals.iter() {170 new_bindings.insert(171 name.clone(),172 lazy_binding!(173 closure!(clone value, |_self, _super_obj| Ok(lazy_val!(closure!(clone value, ||Ok(value.clone())))))174 ),175 );176 }177 Context::new().extend(new_bindings, None, None, None)178 }179180 pub fn push<T>(&self, e: LocExpr, comment: String, f: impl FnOnce() -> T) -> T {181 self.0182 .stack183 .borrow_mut()184 .push(StackTraceElement(e, comment));185 let result = f();186 self.0.stack.borrow_mut().pop();187 result188 }189 pub fn print_stack_trace(&self) {190 for e in self.stack_trace().0 {191 println!("{:?} - {:?}", e.0, e.1)192 }193 }194 pub fn stack_trace(&self) -> StackTrace {195 StackTrace(self.0.stack.borrow().iter().rev().cloned().collect())196 }197 pub fn error<T>(&self, err: Error) -> Result<T> {198 Err(LocError(err, self.stack_trace()))199 }200201 fn begin_state(&self) {202 EVAL_STATE.with(|v| v.borrow_mut().replace(self.clone()));203 }204 fn end_state(&self) {205 EVAL_STATE.with(|v| v.borrow_mut().take());206 }207}208209#[cfg(test)]210pub mod tests {211 use super::Val;212 use crate::EvaluationState;213 use jsonnet_parser::*;214215 #[test]216 fn eval_state_stacktrace() {217 let state = EvaluationState::default();218 state.push(219 loc_expr!(Expr::Num(0.0), true, ("test1.jsonnet".to_owned(), 10, 20)),220 "outer".to_owned(),221 || {222 state.push(223 loc_expr!(Expr::Num(0.0), true, ("test2.jsonnet".to_owned(), 30, 40)),224 "inner".to_owned(),225 || state.print_stack_trace(),226 );227 },228 );229 }230231 #[test]232 fn eval_state_standard() {233 let state = EvaluationState::default();234 state.add_stdlib();235 assert_eq!(236 state237 .parse_evaluate_raw(r#"std.assertEqual(std.base64("test"), "dGVzdA==w")"#)238 .unwrap(),239 Val::Bool(true)240 );241 }242243 macro_rules! eval {244 ($str: expr) => {245 evaluate(246 Context::new(),247 EvaluationState::default(),248 &parse(249 $str,250 &ParserSettings {251 loc_data: true,252 file_name: "test.jsonnet".to_owned(),253 },254 )255 .unwrap(),256 )257 };258 }259260 macro_rules! eval_stdlib {261 ($str: expr) => {{262 let std = "local std = ".to_owned() + jsonnet_stdlib::STDLIB_STR + ";";263 evaluate(264 Context::new(),265 EvaluationState::default(),266 &parse(267 &(std + $str),268 &ParserSettings {269 loc_data: true,270 file_name: "test.jsonnet".to_owned(),271 },272 )273 .unwrap(),274 )275 }};276 }277278 macro_rules! assert_eval {279 ($str: expr) => {280 assert_eq!(281 evaluate(282 Context::new(),283 EvaluationState::default(),284 &parse(285 $str,286 &ParserSettings {287 loc_data: true,288 file_name: "test.jsonnet".to_owned(),289 }290 )291 .unwrap()292 ),293 Val::Bool(true)294 )295 };296 }297 macro_rules! assert_json {298 ($str: expr, $out: expr) => {299 assert_eq!(300 format!(301 "{}",302 evaluate(303 Context::new(),304 EvaluationState::default(),305 &parse(306 $str,307 &ParserSettings {308 loc_data: true,309 file_name: "test.jsonnet".to_owned(),310 }311 )312 .unwrap()313 )314 ),315 $out316 )317 };318 }319 macro_rules! assert_json_stdlib {320 ($str: expr, $out: expr) => {321 assert_eq!(format!("{}", eval_stdlib!($str)), $out)322 };323 }324 macro_rules! assert_eval_neg {325 ($str: expr) => {326 assert_eq!(327 evaluate(328 Context::new(),329 EvaluationState::default(),330 &parse(331 $str,332 &ParserSettings {333 loc_data: true,334 file_name: "test.jsonnet".to_owned(),335 }336 )337 .unwrap()338 ),339 Val::Bool(false)340 )341 };342 }343344 /*345 /// Sanity checking, before trusting to another tests346 #[test]347 fn equality_operator() {348 assert_eval!("2 == 2");349 assert_eval_neg!("2 != 2");350 assert_eval!("2 != 3");351 assert_eval_neg!("2 == 3");352 assert_eval!("'Hello' == 'Hello'");353 assert_eval_neg!("'Hello' != 'Hello'");354 assert_eval!("'Hello' != 'World'");355 assert_eval_neg!("'Hello' == 'World'");356 }357358 #[test]359 fn math_evaluation() {360 assert_eval!("2 + 2 * 2 == 6");361 assert_eval!("3 + (2 + 2 * 2) == 9");362 }363364 #[test]365 fn string_concat() {366 assert_eval!("'Hello' + 'World' == 'HelloWorld'");367 assert_eval!("'Hello' * 3 == 'HelloHelloHello'");368 assert_eval!("'Hello' + 'World' * 3 == 'HelloWorldWorldWorld'");369 }370371 #[test]372 fn local() {373 assert_eval!("local a = 2; local b = 3; a + b == 5");374 assert_eval!("local a = 1, b = a + 1; a + b == 3");375 assert_eval!("local a = 1; local a = 2; a == 2");376 }377378 #[test]379 fn object_lazyness() {380 assert_json!("local a = {a:error 'test'}; {}", r#"{}"#);381 }382383 #[test]384 fn object_inheritance() {385 assert_json!("{a: self.b} + {b:3}", r#"{"a":3,"b":3}"#);386 }387388 #[test]389 fn test_object() {390 assert_json!("{a:2}", r#"{"a":2}"#);391 assert_json!("{a:2+2}", r#"{"a":4}"#);392 assert_json!("{a:2}+{b:2}", r#"{"a":2,"b":2}"#);393 assert_json!("{b:3}+{b:2}", r#"{"b":2}"#);394 assert_json!("{b:3}+{b+:2}", r#"{"b":5}"#);395 assert_json!("local test='a'; {[test]:2}", r#"{"a":2}"#);396 assert_json!(397 r#"398 {399 name: "Alice",400 welcome: "Hello " + self.name + "!",401 }402 "#,403 r#"{"name":"Alice","welcome":"Hello Alice!"}"#404 );405 assert_json!(406 r#"407 {408 name: "Alice",409 welcome: "Hello " + self.name + "!",410 } + {411 name: "Bob"412 }413 "#,414 r#"{"name":"Bob","welcome":"Hello Bob!"}"#415 );416 }417418 #[test]419 fn functions() {420 assert_json!(r#"local a = function(b, c = 2) b + c; a(2)"#, "4");421 assert_json!(422 r#"local a = function(b, c = "Dear") b + c + d, d = "World"; a("Hello")"#,423 r#""HelloDearWorld""#424 );425 }426427 #[test]428 fn local_methods() {429 assert_json!(r#"local a(b, c = 2) = b + c; a(2)"#, "4");430 assert_json!(431 r#"local a(b, c = "Dear") = b + c + d, d = "World"; a("Hello")"#,432 r#""HelloDearWorld""#433 );434 }435436 #[test]437 fn object_locals() {438 assert_json!(r#"{local a = 3, b: a}"#, r#"{"b":3}"#);439 assert_json!(r#"{local a = 3, local c = a, b: c}"#, r#"{"b":3}"#);440 assert_json!(441 r#"{local a = function (b) {[b]:4}, test: a("test")}"#,442 r#"{"test":{"test":4}}"#443 );444 }445446 #[test]447 fn direct_self() {448 println!(449 "{:#?}",450 eval!(451 r#"452 {453 local me = self,454 a: 3,455 b(): me.a,456 }457 "#458 )459 );460 }461462 #[test]463 fn indirect_self() {464 // `self` assigned to `me` was lost when being465 // referenced from field466 eval_stdlib!(467 r#"{468 local me = self,469 a: 3,470 b: me.a,471 }.b"#472 );473 }474475 // We can't trust other tests (And official jsonnet testsuite), if assert is not working correctly476 #[test]477 fn std_assert_ok() {478 eval_stdlib!("std.assertEqual(4.5 << 2, 16)");479 }480481 #[test]482 #[should_panic]483 fn std_assert_failure() {484 eval_stdlib!("std.assertEqual(4.5 << 2, 15)");485 }486487 #[test]488 fn string_is_string() {489 assert_eq!(490 eval_stdlib!("local arr = 'hello'; (!std.isArray(arr)) && (!std.isString(arr))"),491 Val::Bool(false)492 );493 }494495 #[test]496 fn base64_works() {497 assert_json_stdlib!(r#"std.base64("test")"#, r#""dGVzdA==""#);498 }499500 #[test]501 fn utf8_chars() {502 assert_json_stdlib!(503 r#"local c="😎";{c:std.codepoint(c),l:std.length(c)}"#,504 r#"{"c":128526,"l":1}"#505 )506 }507508 #[test]509 fn json() {510 assert_json_stdlib!(511 r#"std.manifestJsonEx({a:3, b:4, c:6},"")"#,512 r#""{\n"a": 3,\n"b": 4,\n"c": 6\n}""#513 );514 }515516 #[test]517 fn test() {518 assert_json_stdlib!(519 r#"[[a, b] for a in [1,2,3] for b in [4,5,6]]"#,520 "[[1,4],[1,5],[1,6],[2,4],[2,5],[2,6],[3,4],[3,5],[3,6]]"521 );522 }523524 #[test]525 fn sjsonnet() {526 eval!(527 r#"528 local x0 = {k: 1};529 local x1 = {k: x0.k + x0.k};530 local x2 = {k: x1.k + x1.k};531 local x3 = {k: x2.k + x2.k};532 local x4 = {k: x3.k + x3.k};533 local x5 = {k: x4.k + x4.k};534 local x6 = {k: x5.k + x5.k};535 local x7 = {k: x6.k + x6.k};536 local x8 = {k: x7.k + x7.k};537 local x9 = {k: x8.k + x8.k};538 local x10 = {k: x9.k + x9.k};539 local x11 = {k: x10.k + x10.k};540 local x12 = {k: x11.k + x11.k};541 local x13 = {k: x12.k + x12.k};542 local x14 = {k: x13.k + x13.k};543 local x15 = {k: x14.k + x14.k};544 local x16 = {k: x15.k + x15.k};545 local x17 = {k: x16.k + x16.k};546 local x18 = {k: x17.k + x17.k};547 local x19 = {k: x18.k + x18.k};548 local x20 = {k: x19.k + x19.k};549 local x21 = {k: x20.k + x20.k};550 x21.k551 "#552 );553 }554 */555}