difftreelog
feat CLI
in: master
6 files changed
Cargo.lockdiffbeforeafterboth--- a/Cargo.lock
+++ b/Cargo.lock
@@ -1,12 +1,110 @@
# This file is automatically @generated by Cargo.
# It is not intended for manual editing.
[[package]]
+name = "annotate-snippets"
+version = "0.8.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "d78ea013094e5ea606b1c05fe35f1dd7ea1eb1ea259908d040b25bd5ec677ee5"
+
+[[package]]
+name = "atty"
+version = "0.2.14"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "d9b39be18770d11421cdb1b9947a45dd3f37e93092cbf377614828a319d5fee8"
+dependencies = [
+ "hermit-abi",
+ "libc",
+ "winapi 0.3.8",
+]
+
+[[package]]
+name = "autocfg"
+version = "1.0.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "f8aac770f1885fd7e387acedd76065302551364496e46b3dd00860b2f8359b9d"
+
+[[package]]
+name = "bitflags"
+version = "1.2.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "cf1de2fe8c75bc145a2f577add951f8134889b4795d47466a54a5c846d691693"
+
+[[package]]
+name = "clap"
+version = "3.0.0-beta.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "860643c53f980f0d38a5e25dfab6c3c93b2cb3aa1fe192643d17a293c6c41936"
+dependencies = [
+ "atty",
+ "bitflags",
+ "clap_derive",
+ "indexmap",
+ "lazy_static",
+ "os_str_bytes",
+ "strsim",
+ "term_size 1.0.0-beta1",
+ "termcolor",
+ "textwrap",
+ "unicode-width",
+ "vec_map",
+]
+
+[[package]]
+name = "clap_derive"
+version = "3.0.0-beta.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "fb51c9e75b94452505acd21d929323f5a5c6c4735a852adbd39ef5fb1b014f30"
+dependencies = [
+ "heck",
+ "proc-macro-error",
+ "proc-macro2",
+ "quote",
+ "syn",
+]
+
+[[package]]
name = "closure"
version = "0.3.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "d6173fd61b610d15a7566dd7b7620775627441c4ab9dac8906e17cb93a24b782"
[[package]]
+name = "heck"
+version = "0.3.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "20564e78d53d2bb135c343b3f47714a56af2061f1c928fdb541dc7b9fdd94205"
+dependencies = [
+ "unicode-segmentation",
+]
+
+[[package]]
+name = "hermit-abi"
+version = "0.1.13"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "91780f809e750b0a89f5544be56617ff6b1227ee485bcb06ebe10cdf89bd3b71"
+dependencies = [
+ "libc",
+]
+
+[[package]]
+name = "indexmap"
+version = "1.4.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "c398b2b113b55809ceb9ee3e753fcbac793f1956663f3c36549c1346015c2afe"
+dependencies = [
+ "autocfg",
+]
+
+[[package]]
+name = "jsonnet"
+version = "0.1.0"
+dependencies = [
+ "annotate-snippets",
+ "clap",
+ "jsonnet-evaluator",
+]
+
+[[package]]
name = "jsonnet-evaluator"
version = "0.1.0"
dependencies = [
@@ -28,6 +126,34 @@
version = "0.1.0"
[[package]]
+name = "kernel32-sys"
+version = "0.2.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "7507624b29483431c0ba2d82aece8ca6cdba9382bff4ddd0f7490560c056098d"
+dependencies = [
+ "winapi 0.2.8",
+ "winapi-build",
+]
+
+[[package]]
+name = "lazy_static"
+version = "1.4.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "e2abad23fbc42b3700f2f279844dc832adb2b2eb069b2df918f455c4e18cc646"
+
+[[package]]
+name = "libc"
+version = "0.2.71"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "9457b06509d27052635f90d6466700c65095fdf75409b3fbdd903e988b886f49"
+
+[[package]]
+name = "os_str_bytes"
+version = "2.3.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "06de47b848347d8c4c94219ad8ecd35eb90231704b067e67e6ae2e36ee023510"
+
+[[package]]
name = "peg"
version = "0.6.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
@@ -55,6 +181,32 @@
checksum = "0c1a2897e69d986c7986747ebad425cf03746ec5e3e09bb3b2600f91301ba864"
[[package]]
+name = "proc-macro-error"
+version = "0.4.12"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "18f33027081eba0a6d8aba6d1b1c3a3be58cbb12106341c2d5759fcd9b5277e7"
+dependencies = [
+ "proc-macro-error-attr",
+ "proc-macro2",
+ "quote",
+ "syn",
+ "version_check",
+]
+
+[[package]]
+name = "proc-macro-error-attr"
+version = "0.4.12"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "8a5b4b77fdb63c1eca72173d68d24501c54ab1269409f6b672c85deb18af69de"
+dependencies = [
+ "proc-macro2",
+ "quote",
+ "syn",
+ "syn-mid",
+ "version_check",
+]
+
+[[package]]
name = "proc-macro2"
version = "1.0.12"
source = "registry+https://github.com/rust-lang/crates.io-index"
@@ -73,7 +225,142 @@
]
[[package]]
+name = "strsim"
+version = "0.10.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "73473c0e59e6d5812c5dfe2a064a6444949f089e20eec9a2e5506596494e4623"
+
+[[package]]
+name = "syn"
+version = "1.0.21"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "4696caa4048ac7ce2bcd2e484b3cef88c1004e41b8e945a277e2c25dc0b72060"
+dependencies = [
+ "proc-macro2",
+ "quote",
+ "unicode-xid",
+]
+
+[[package]]
+name = "syn-mid"
+version = "0.5.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "7be3539f6c128a931cf19dcee741c1af532c7fd387baa739c03dd2e96479338a"
+dependencies = [
+ "proc-macro2",
+ "quote",
+ "syn",
+]
+
+[[package]]
+name = "term_size"
+version = "0.3.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "1e4129646ca0ed8f45d09b929036bafad5377103edd06e50bf574b353d2b08d9"
+dependencies = [
+ "libc",
+ "winapi 0.3.8",
+]
+
+[[package]]
+name = "term_size"
+version = "1.0.0-beta1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "a8a17d8699e154863becdf18e4fd28bd0be27ca72856f54daf75c00f2566898f"
+dependencies = [
+ "kernel32-sys",
+ "libc",
+ "winapi 0.2.8",
+]
+
+[[package]]
+name = "termcolor"
+version = "1.1.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "bb6bfa289a4d7c5766392812c0a1f4c1ba45afa1ad47803c11e1f407d846d75f"
+dependencies = [
+ "winapi-util",
+]
+
+[[package]]
+name = "textwrap"
+version = "0.11.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "d326610f408c7a4eb6f51c37c330e496b08506c9457c9d34287ecc38809fb060"
+dependencies = [
+ "term_size 0.3.2",
+ "unicode-width",
+]
+
+[[package]]
+name = "unicode-segmentation"
+version = "1.6.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "e83e153d1053cbb5a118eeff7fd5be06ed99153f00dbcd8ae310c5fb2b22edc0"
+
+[[package]]
+name = "unicode-width"
+version = "0.1.7"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "caaa9d531767d1ff2150b9332433f32a24622147e5ebb1f26409d5da67afd479"
+
+[[package]]
name = "unicode-xid"
version = "0.2.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "826e7639553986605ec5979c7dd957c7895e93eabed50ab2ffa7f6128a75097c"
+
+[[package]]
+name = "vec_map"
+version = "0.8.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "f1bddf1187be692e79c5ffeab891132dfb0f236ed36a43c7ed39f1165ee20191"
+
+[[package]]
+name = "version_check"
+version = "0.9.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "b5a972e5669d67ba988ce3dc826706fb0a8b01471c088cb0b6110b805cc36aed"
+
+[[package]]
+name = "winapi"
+version = "0.2.8"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "167dc9d6949a9b857f3451275e911c3f44255842c1f7a76f33c55103a909087a"
+
+[[package]]
+name = "winapi"
+version = "0.3.8"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "8093091eeb260906a183e6ae1abdba2ef5ef2257a21801128899c3fc699229c6"
+dependencies = [
+ "winapi-i686-pc-windows-gnu",
+ "winapi-x86_64-pc-windows-gnu",
+]
+
+[[package]]
+name = "winapi-build"
+version = "0.1.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "2d315eee3b34aca4797b2da6b13ed88266e6d612562a0c46390af8299fc699bc"
+
+[[package]]
+name = "winapi-i686-pc-windows-gnu"
+version = "0.4.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "ac3b87c63620426dd9b991e5ce0329eff545bccbbb34f3be09ff6fb6ab51b7b6"
+
+[[package]]
+name = "winapi-util"
+version = "0.1.5"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "70ec6ce85bb158151cae5e5c87f95a8e97d2c0c4b001223f33a334e3ce5de178"
+dependencies = [
+ "winapi 0.3.8",
+]
+
+[[package]]
+name = "winapi-x86_64-pc-windows-gnu"
+version = "0.4.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "712e227841d057c1ee1cd2fb22fa7e5a5461ae8e48fa2ca79ec42cfc1931183f"
Cargo.tomldiffbeforeafterboth--- a/Cargo.toml
+++ b/Cargo.toml
@@ -3,4 +3,5 @@
"crates/jsonnet-parser",
"crates/jsonnet-evaluator",
"crates/jsonnet-stdlib",
+ "cmds/jsonnet"
]
cmds/jsonnet/Cargo.tomldiffbeforeafterboth--- /dev/null
+++ b/cmds/jsonnet/Cargo.toml
@@ -0,0 +1,16 @@
+[package]
+name = "jsonnet"
+version = "0.1.0"
+authors = ["Лач <iam@lach.pw>"]
+edition = "2018"
+
+# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
+
+[dependencies]
+jsonnet-evaluator = { path = "../../crates/jsonnet-evaluator" }
+annotate-snippets = "0.8.0"
+
+[dependencies.clap]
+version = "3.0.0-beta.1"
+default-features = false
+features = ["std", "derive", "suggestions", "color", "unstable", "wrap_help"]
cmds/jsonnet/src/main.rsdiffbeforeafterboth--- /dev/null
+++ b/cmds/jsonnet/src/main.rs
@@ -0,0 +1,64 @@
+use clap::Clap;
+
+#[derive(Clap)]
+#[clap(version = "0.1.0", author = "Lach <iam@lach.pw>")]
+struct Opts {
+ #[clap(about = "File to compile")]
+ input: String,
+ #[clap(long, about = "Disable global std variable")]
+ no_stdlib: bool,
+}
+
+fn main() {
+ let opts: Opts = Opts::parse();
+ let evaluator = jsonnet_evaluator::EvaluationState::default();
+ if !opts.no_stdlib {
+ evaluator.add_stdlib();
+ }
+ evaluator
+ .add_file(
+ opts.input.clone(),
+ String::from_utf8(std::fs::read(opts.input.clone()).unwrap()).unwrap(),
+ )
+ .unwrap();
+ let result = evaluator.evaluate_file(&opts.input.clone());
+ match result {
+ Ok(v) => println!("{:?}", v),
+ Err(err) => {
+ use annotate_snippets::{
+ display_list::{DisplayList, FormatOptions},
+ snippet::{Annotation, AnnotationType, Slice, Snippet, SourceAnnotation},
+ };
+ for item in (err.1).0.iter() {
+ let source = (item.0).1.clone().unwrap();
+ let code = evaluator.get_source(&source.0);
+ let snippet = Snippet {
+ opt: FormatOptions {
+ color: true,
+ ..Default::default()
+ },
+ title: Some(Annotation {
+ label: Some(&item.1),
+ id: None,
+ annotation_type: AnnotationType::Error,
+ }),
+ footer: vec![],
+ slices: vec![Slice {
+ source: &code,
+ line_start: 1,
+ origin: Some(&source.0),
+ fold: true,
+ annotations: vec![SourceAnnotation {
+ label: &"Example error annotation",
+ annotation_type: AnnotationType::Error,
+ range: (source.1, source.2),
+ }],
+ }],
+ };
+
+ let dl = DisplayList::from(snippet);
+ println!("{}", dl);
+ }
+ }
+ }
+}
crates/jsonnet-evaluator/src/evaluate.rsdiffbeforeafterboth--- a/crates/jsonnet-evaluator/src/evaluate.rs
+++ b/crates/jsonnet-evaluator/src/evaluate.rs
@@ -77,6 +77,7 @@
(Val::Str(v1), Val::Str(v2)) => Val::Str(v1.to_owned() + &v2),
(Val::Str(v1), Val::Num(v2)) => Val::Str(format!("{}{}", v1, v2)),
(Val::Num(v1), Val::Str(v2)) => Val::Str(format!("{}{}", v1, v2)),
+ (Val::Str(v1), v2) => Val::Str(format!("{}{:?}", v1, v2)),
(Val::Obj(v1), Val::Obj(v2)) => Val::Obj(v2.with_super(v1.clone())),
(Val::Arr(a), Val::Arr(b)) => Val::Arr([&a[..], &b[..]].concat()),
(Val::Num(v1), Val::Num(v2)) => Val::Num(v1 + v2),
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 evaluate_file(&self, name: &str) -> Result<Val> {88 self.begin_state();89 let expr: LocExpr = {90 let ro_map = self.0.files.borrow();91 let value = ro_map92 .get(name)93 .unwrap_or_else(|| panic!("file not added: {:?}", name));94 if value.2.is_some() {95 return Ok(value.2.clone().unwrap());96 }97 value.1.clone()98 };99 let value = evaluate(self.create_default_context()?, &expr)?;100 {101 self.0102 .files103 .borrow_mut()104 .get_mut(name)105 .unwrap()106 .2107 .replace(value.clone());108 }109 self.end_state();110 Ok(value)111 }112113 pub fn parse_evaluate_raw(&self, code: &str) -> Result<Val> {114 let parsed = parse(115 &code,116 &ParserSettings {117 file_name: "raw.jsonnet".to_owned(),118 loc_data: true,119 },120 );121 self.begin_state();122 let value = evaluate(self.create_default_context()?, &parsed.unwrap());123 self.end_state();124 value125 }126127 pub fn add_stdlib(&self) {128 self.begin_state();129 use jsonnet_stdlib::STDLIB_STR;130 self.add_file("std.jsonnet".to_owned(), STDLIB_STR.to_owned())131 .unwrap();132 let val = self.evaluate_file("std.jsonnet").unwrap();133 self.0.globals.borrow_mut().insert("std".to_owned(), val);134 self.end_state();135 }136137 pub fn create_default_context(&self) -> Result<Context> {138 let globals = self.0.globals.borrow();139 let mut new_bindings: HashMap<String, LazyBinding> = HashMap::new();140 for (name, value) in globals.iter() {141 new_bindings.insert(142 name.clone(),143 lazy_binding!(144 closure!(clone value, |_self, _super_obj| Ok(lazy_val!(closure!(clone value, ||Ok(value.clone())))))145 ),146 );147 }148 Context::new().extend(new_bindings, None, None, None)149 }150151 pub fn push<T>(&self, e: LocExpr, comment: String, f: impl FnOnce() -> T) -> T {152 self.0153 .stack154 .borrow_mut()155 .push(StackTraceElement(e, comment));156 let result = f();157 self.0.stack.borrow_mut().pop();158 result159 }160 pub fn print_stack_trace(&self) {161 for e in self.stack_trace().0 {162 println!("{:?} - {:?}", e.0, e.1)163 }164 }165 pub fn stack_trace(&self) -> StackTrace {166 StackTrace(self.0.stack.borrow().iter().rev().cloned().collect())167 }168 pub fn error<T>(&self, err: Error) -> Result<T> {169 Err(LocError(err, self.stack_trace()))170 }171172 fn begin_state(&self) {173 EVAL_STATE.with(|v| v.borrow_mut().replace(self.clone()));174 }175 fn end_state(&self) {176 EVAL_STATE.with(|v| v.borrow_mut().take());177 }178}179180#[cfg(test)]181pub mod tests {182 use super::Val;183 use crate::EvaluationState;184 use jsonnet_parser::*;185186 #[test]187 fn eval_state_stacktrace() {188 let state = EvaluationState::default();189 state.push(190 loc_expr!(Expr::Num(0.0), true, ("test1.jsonnet".to_owned(), 10, 20)),191 "outer".to_owned(),192 || {193 state.push(194 loc_expr!(Expr::Num(0.0), true, ("test2.jsonnet".to_owned(), 30, 40)),195 "inner".to_owned(),196 || state.print_stack_trace(),197 );198 },199 );200 }201202 #[test]203 fn eval_state_standard() {204 let state = EvaluationState::default();205 state.add_stdlib();206 assert_eq!(207 state208 .parse_evaluate_raw(r#"std.assertEqual(std.base64("test"), "dGVzdA==w")"#)209 .unwrap(),210 Val::Bool(true)211 );212 }213214 macro_rules! eval {215 ($str: expr) => {216 evaluate(217 Context::new(),218 EvaluationState::default(),219 &parse(220 $str,221 &ParserSettings {222 loc_data: true,223 file_name: "test.jsonnet".to_owned(),224 },225 )226 .unwrap(),227 )228 };229 }230231 macro_rules! eval_stdlib {232 ($str: expr) => {{233 let std = "local std = ".to_owned() + jsonnet_stdlib::STDLIB_STR + ";";234 evaluate(235 Context::new(),236 EvaluationState::default(),237 &parse(238 &(std + $str),239 &ParserSettings {240 loc_data: true,241 file_name: "test.jsonnet".to_owned(),242 },243 )244 .unwrap(),245 )246 }};247 }248249 macro_rules! assert_eval {250 ($str: expr) => {251 assert_eq!(252 evaluate(253 Context::new(),254 EvaluationState::default(),255 &parse(256 $str,257 &ParserSettings {258 loc_data: true,259 file_name: "test.jsonnet".to_owned(),260 }261 )262 .unwrap()263 ),264 Val::Bool(true)265 )266 };267 }268 macro_rules! assert_json {269 ($str: expr, $out: expr) => {270 assert_eq!(271 format!(272 "{}",273 evaluate(274 Context::new(),275 EvaluationState::default(),276 &parse(277 $str,278 &ParserSettings {279 loc_data: true,280 file_name: "test.jsonnet".to_owned(),281 }282 )283 .unwrap()284 )285 ),286 $out287 )288 };289 }290 macro_rules! assert_json_stdlib {291 ($str: expr, $out: expr) => {292 assert_eq!(format!("{}", eval_stdlib!($str)), $out)293 };294 }295 macro_rules! assert_eval_neg {296 ($str: expr) => {297 assert_eq!(298 evaluate(299 Context::new(),300 EvaluationState::default(),301 &parse(302 $str,303 &ParserSettings {304 loc_data: true,305 file_name: "test.jsonnet".to_owned(),306 }307 )308 .unwrap()309 ),310 Val::Bool(false)311 )312 };313 }314315 /*316 /// Sanity checking, before trusting to another tests317 #[test]318 fn equality_operator() {319 assert_eval!("2 == 2");320 assert_eval_neg!("2 != 2");321 assert_eval!("2 != 3");322 assert_eval_neg!("2 == 3");323 assert_eval!("'Hello' == 'Hello'");324 assert_eval_neg!("'Hello' != 'Hello'");325 assert_eval!("'Hello' != 'World'");326 assert_eval_neg!("'Hello' == 'World'");327 }328329 #[test]330 fn math_evaluation() {331 assert_eval!("2 + 2 * 2 == 6");332 assert_eval!("3 + (2 + 2 * 2) == 9");333 }334335 #[test]336 fn string_concat() {337 assert_eval!("'Hello' + 'World' == 'HelloWorld'");338 assert_eval!("'Hello' * 3 == 'HelloHelloHello'");339 assert_eval!("'Hello' + 'World' * 3 == 'HelloWorldWorldWorld'");340 }341342 #[test]343 fn local() {344 assert_eval!("local a = 2; local b = 3; a + b == 5");345 assert_eval!("local a = 1, b = a + 1; a + b == 3");346 assert_eval!("local a = 1; local a = 2; a == 2");347 }348349 #[test]350 fn object_lazyness() {351 assert_json!("local a = {a:error 'test'}; {}", r#"{}"#);352 }353354 #[test]355 fn object_inheritance() {356 assert_json!("{a: self.b} + {b:3}", r#"{"a":3,"b":3}"#);357 }358359 #[test]360 fn test_object() {361 assert_json!("{a:2}", r#"{"a":2}"#);362 assert_json!("{a:2+2}", r#"{"a":4}"#);363 assert_json!("{a:2}+{b:2}", r#"{"a":2,"b":2}"#);364 assert_json!("{b:3}+{b:2}", r#"{"b":2}"#);365 assert_json!("{b:3}+{b+:2}", r#"{"b":5}"#);366 assert_json!("local test='a'; {[test]:2}", r#"{"a":2}"#);367 assert_json!(368 r#"369 {370 name: "Alice",371 welcome: "Hello " + self.name + "!",372 }373 "#,374 r#"{"name":"Alice","welcome":"Hello Alice!"}"#375 );376 assert_json!(377 r#"378 {379 name: "Alice",380 welcome: "Hello " + self.name + "!",381 } + {382 name: "Bob"383 }384 "#,385 r#"{"name":"Bob","welcome":"Hello Bob!"}"#386 );387 }388389 #[test]390 fn functions() {391 assert_json!(r#"local a = function(b, c = 2) b + c; a(2)"#, "4");392 assert_json!(393 r#"local a = function(b, c = "Dear") b + c + d, d = "World"; a("Hello")"#,394 r#""HelloDearWorld""#395 );396 }397398 #[test]399 fn local_methods() {400 assert_json!(r#"local a(b, c = 2) = b + c; a(2)"#, "4");401 assert_json!(402 r#"local a(b, c = "Dear") = b + c + d, d = "World"; a("Hello")"#,403 r#""HelloDearWorld""#404 );405 }406407 #[test]408 fn object_locals() {409 assert_json!(r#"{local a = 3, b: a}"#, r#"{"b":3}"#);410 assert_json!(r#"{local a = 3, local c = a, b: c}"#, r#"{"b":3}"#);411 assert_json!(412 r#"{local a = function (b) {[b]:4}, test: a("test")}"#,413 r#"{"test":{"test":4}}"#414 );415 }416417 #[test]418 fn direct_self() {419 println!(420 "{:#?}",421 eval!(422 r#"423 {424 local me = self,425 a: 3,426 b(): me.a,427 }428 "#429 )430 );431 }432433 #[test]434 fn indirect_self() {435 // `self` assigned to `me` was lost when being436 // referenced from field437 eval_stdlib!(438 r#"{439 local me = self,440 a: 3,441 b: me.a,442 }.b"#443 );444 }445446 // We can't trust other tests (And official jsonnet testsuite), if assert is not working correctly447 #[test]448 fn std_assert_ok() {449 eval_stdlib!("std.assertEqual(4.5 << 2, 16)");450 }451452 #[test]453 #[should_panic]454 fn std_assert_failure() {455 eval_stdlib!("std.assertEqual(4.5 << 2, 15)");456 }457458 #[test]459 fn string_is_string() {460 assert_eq!(461 eval_stdlib!("local arr = 'hello'; (!std.isArray(arr)) && (!std.isString(arr))"),462 Val::Bool(false)463 );464 }465466 #[test]467 fn base64_works() {468 assert_json_stdlib!(r#"std.base64("test")"#, r#""dGVzdA==""#);469 }470471 #[test]472 fn utf8_chars() {473 assert_json_stdlib!(474 r#"local c="😎";{c:std.codepoint(c),l:std.length(c)}"#,475 r#"{"c":128526,"l":1}"#476 )477 }478479 #[test]480 fn json() {481 assert_json_stdlib!(482 r#"std.manifestJsonEx({a:3, b:4, c:6},"")"#,483 r#""{\n"a": 3,\n"b": 4,\n"c": 6\n}""#484 );485 }486487 #[test]488 fn test() {489 assert_json_stdlib!(490 r#"[[a, b] for a in [1,2,3] for b in [4,5,6]]"#,491 "[[1,4],[1,5],[1,6],[2,4],[2,5],[2,6],[3,4],[3,5],[3,6]]"492 );493 }494495 #[test]496 fn sjsonnet() {497 eval!(498 r#"499 local x0 = {k: 1};500 local x1 = {k: x0.k + x0.k};501 local x2 = {k: x1.k + x1.k};502 local x3 = {k: x2.k + x2.k};503 local x4 = {k: x3.k + x3.k};504 local x5 = {k: x4.k + x4.k};505 local x6 = {k: x5.k + x5.k};506 local x7 = {k: x6.k + x6.k};507 local x8 = {k: x7.k + x7.k};508 local x9 = {k: x8.k + x8.k};509 local x10 = {k: x9.k + x9.k};510 local x11 = {k: x10.k + x10.k};511 local x12 = {k: x11.k + x11.k};512 local x13 = {k: x12.k + x12.k};513 local x14 = {k: x13.k + x13.k};514 local x15 = {k: x14.k + x14.k};515 local x16 = {k: x15.k + x15.k};516 local x17 = {k: x16.k + x16.k};517 local x18 = {k: x17.k + x17.k};518 local x19 = {k: x18.k + x18.k};519 local x20 = {k: x19.k + x19.k};520 local x21 = {k: x20.k + x20.k};521 x21.k522 "#523 );524 }525 */526}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 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}