difftreelog
test update for split stdlib
in: master
100 files changed
Cargo.lockdiffbeforeafterboth--- a/Cargo.lock
+++ b/Cargo.lock
@@ -517,18 +517,18 @@
[[package]]
name = "serde"
-version = "1.0.137"
+version = "1.0.142"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "61ea8d54c77f8315140a05f4c7237403bf38b72704d031543aa1d16abbf517d1"
+checksum = "e590c437916fb6b221e1d00df6e3294f3fccd70ca7e92541c475d6ed6ef5fee2"
dependencies = [
"serde_derive",
]
[[package]]
name = "serde_derive"
-version = "1.0.137"
+version = "1.0.142"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "1f26faba0c3959972377d3b2d306ee9f71faee9714294e41bb777f83f88578be"
+checksum = "34b5b8d809babe02f538c2cfec6f2c1ed10804c0e5a6a041a049a4f5588ccc2e"
dependencies = [
"proc-macro2",
"quote",
@@ -620,6 +620,16 @@
]
[[package]]
+name = "tests"
+version = "0.1.0"
+dependencies = [
+ "jrsonnet-evaluator",
+ "jrsonnet-gcmodule",
+ "jrsonnet-stdlib",
+ "serde",
+]
+
+[[package]]
name = "textwrap"
version = "0.15.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
Cargo.tomldiffbeforeafterboth--- a/Cargo.toml
+++ b/Cargo.toml
@@ -1,5 +1,5 @@
[workspace]
-members = ["crates/*", "bindings/jsonnet", "cmds/jrsonnet"]
+members = ["crates/*", "bindings/jsonnet", "cmds/jrsonnet", "tests"]
[profile.test]
opt-level = 1
crates/jrsonnet-evaluator/src/ctx.rsdiffbeforeafterboth--- a/crates/jrsonnet-evaluator/src/ctx.rs
+++ b/crates/jrsonnet-evaluator/src/ctx.rs
@@ -139,29 +139,47 @@
}
}
-#[derive(Default)]
pub struct ContextBuilder {
bindings: GcHashMap<IStr, Thunk<Val>>,
+ extend: Option<Context>,
}
+
impl ContextBuilder {
pub fn new() -> Self {
- Self::default()
+ Self::with_capacity(0)
}
pub fn with_capacity(capacity: usize) -> Self {
Self {
bindings: GcHashMap::with_capacity(capacity),
+ extend: None,
}
}
+ pub fn extend(parent: Context) -> Self {
+ Self {
+ bindings: GcHashMap::new(),
+ extend: Some(parent),
+ }
+ }
pub fn bind(&mut self, name: IStr, value: Thunk<Val>) -> &mut Self {
self.bindings.insert(name, value);
self
}
pub fn build(self) -> Context {
- Context(Cc::new(ContextInternals {
- bindings: LayeredHashMap::new(self.bindings),
- dollar: None,
- sup: None,
- this: None,
- }))
+ if let Some(parent) = self.extend {
+ parent.extend(self.bindings, None, None, None)
+ } else {
+ Context(Cc::new(ContextInternals {
+ bindings: LayeredHashMap::new(self.bindings),
+ dollar: None,
+ sup: None,
+ this: None,
+ }))
+ }
+ }
+}
+
+impl Default for ContextBuilder {
+ fn default() -> Self {
+ Self::new()
}
}
crates/jrsonnet-evaluator/src/dynamic.rsdiffbeforeafterboth--- a/crates/jrsonnet-evaluator/src/dynamic.rs
+++ b/crates/jrsonnet-evaluator/src/dynamic.rs
@@ -2,6 +2,7 @@
use jrsonnet_gcmodule::{Cc, Trace};
+// TODO: Replace with OnceCell once in std
#[derive(Clone, Trace)]
pub struct Pending<V: Trace + 'static>(pub Cc<RefCell<Option<V>>>);
impl<T: Trace + 'static> Pending<T> {
crates/jrsonnet-evaluator/tests/as_native.rsdiffbeforeafterboth--- a/crates/jrsonnet-evaluator/tests/as_native.rs
+++ /dev/null
@@ -1,19 +0,0 @@
-use jrsonnet_evaluator::{error::Result, State};
-
-mod common;
-
-#[test]
-fn as_native() -> Result<()> {
- let s = State::default();
- s.with_stdlib();
-
- let val = s.evaluate_snippet("snip".to_owned(), r#"function(a, b) a + b"#.into())?;
- let func = val.as_func().expect("this is function");
-
- let native = func.into_native::<((u32, u32), u32)>();
-
- ensure_eq!(native(s.clone(), 1, 2)?, 3);
- ensure_eq!(native(s, 3, 4)?, 7);
-
- Ok(())
-}
crates/jrsonnet-evaluator/tests/builtin.rsdiffbeforeafterboth--- a/crates/jrsonnet-evaluator/tests/builtin.rs
+++ /dev/null
@@ -1,100 +0,0 @@
-mod common;
-
-use jrsonnet_evaluator::{
- error::Result,
- function::{builtin, builtin::Builtin, CallLocation, FuncVal},
- tb,
- typed::Typed,
- State, Val,
-};
-use jrsonnet_gcmodule::Cc;
-
-#[builtin]
-fn a() -> Result<u32> {
- Ok(1)
-}
-
-#[test]
-fn basic_function() -> Result<()> {
- let s = State::default();
- let a: a = a {};
- let v = u32::from_untyped(
- a.call(
- s.clone(),
- s.create_default_context(),
- CallLocation::native(),
- &(),
- )?,
- s,
- )?;
-
- ensure_eq!(v, 1);
- Ok(())
-}
-
-#[builtin]
-fn native_add(a: u32, b: u32) -> Result<u32> {
- Ok(a + b)
-}
-
-#[test]
-fn call_from_code() -> Result<()> {
- let s = State::default();
- s.with_stdlib();
- s.settings_mut().globals.insert(
- "nativeAdd".into(),
- Val::Func(FuncVal::StaticBuiltin(native_add::INST)),
- );
-
- let v = s.evaluate_snippet(
- "snip".to_owned(),
- "
- assert nativeAdd(1, 2) == 3;
- assert nativeAdd(100, 200) == 300;
- null
- "
- .into(),
- )?;
- ensure_val_eq!(s, v, Val::Null);
- Ok(())
-}
-
-#[builtin(fields(
- a: u32
-))]
-fn curried_add(this: &curried_add, b: u32) -> Result<u32> {
- Ok(this.a + b)
-}
-
-#[builtin]
-fn curry_add(a: u32) -> Result<FuncVal> {
- Ok(FuncVal::Builtin(Cc::new(tb!(curried_add { a }))))
-}
-
-#[test]
-fn nonstatic_builtin() -> Result<()> {
- let s = State::default();
- s.with_stdlib();
- s.settings_mut().globals.insert(
- "curryAdd".into(),
- Val::Func(FuncVal::StaticBuiltin(curry_add::INST)),
- );
-
- let v = s.evaluate_snippet(
- "snip".to_owned(),
- "
- local a = curryAdd(1);
- local b = curryAdd(4);
-
- assert a(2) == 3;
- assert a(200) == 201;
-
- assert b(2) == 6;
- assert b(200) == 204;
- null
- "
- .into(),
- )?;
- ensure_val_eq!(s, v, Val::Null);
- Ok(())
-}
crates/jrsonnet-evaluator/tests/common.rsdiffbeforeafterboth--- a/crates/jrsonnet-evaluator/tests/common.rs
+++ /dev/null
@@ -1,78 +0,0 @@
-use jrsonnet_evaluator::{
- error::Result,
- function::{builtin, FuncVal},
- throw_runtime, ObjValueBuilder, State, Thunk, Val,
-};
-
-#[macro_export]
-macro_rules! ensure_eq {
- ($a:expr, $b:expr $(,)?) => {{
- let a = &$a;
- let b = &$b;
- if a != b {
- ::jrsonnet_evaluator::throw_runtime!("assertion failed: a != b\na={:#?}\nb={:#?}", a, b)
- }
- }};
-}
-
-#[macro_export]
-macro_rules! ensure {
- ($v:expr $(,)?) => {
- if !$v {
- ::jrsonnet_evaluator::throw_runtime!("assertion failed: {}", stringify!($v))
- }
- };
-}
-
-#[macro_export]
-macro_rules! ensure_val_eq {
- ($s:expr, $a:expr, $b:expr) => {{
- if !::jrsonnet_evaluator::val::equals($s.clone(), &$a.clone(), &$b.clone())? {
- ::jrsonnet_evaluator::throw_runtime!(
- "assertion failed: a != b\na={:#?}\nb={:#?}",
- $a.to_json(
- $s.clone(),
- 2,
- #[cfg(feature = "exp-preserve-order")]
- false
- )?,
- $b.to_json(
- $s.clone(),
- 2,
- #[cfg(feature = "exp-preserve-order")]
- false
- )?,
- )
- }
- }};
-}
-
-#[builtin]
-fn assert_throw(s: State, lazy: Thunk<Val>, message: String) -> Result<bool> {
- match lazy.evaluate(s) {
- Ok(_) => {
- throw_runtime!("expected argument to throw on evaluation, but it returned instead")
- }
- Err(e) => {
- let error = format!("{}", e.error());
- ensure_eq!(message, error);
- }
- }
- Ok(true)
-}
-
-#[allow(dead_code)]
-pub fn with_test(s: &State) {
- let mut bobj = ObjValueBuilder::new();
- bobj.member("assertThrow".into())
- .hide()
- .value(
- s.clone(),
- Val::Func(FuncVal::StaticBuiltin(assert_throw::INST)),
- )
- .expect("no error");
-
- s.settings_mut()
- .globals
- .insert("test".into(), Val::Obj(bobj.build()));
-}
crates/jrsonnet-evaluator/tests/golden.rsdiffbeforeafterboth--- a/crates/jrsonnet-evaluator/tests/golden.rs
+++ /dev/null
@@ -1,69 +0,0 @@
-use std::{
- fs, io,
- path::{Path, PathBuf},
-};
-
-use jrsonnet_evaluator::{
- trace::{CompactFormat, PathResolver},
- FileImportResolver, State,
-};
-
-mod common;
-
-fn run(root: &Path, file: &Path) -> String {
- let s = State::default();
- s.set_trace_format(Box::new(CompactFormat {
- resolver: PathResolver::Relative(root.to_owned()),
- padding: 3,
- }));
- s.with_stdlib();
- common::with_test(&s);
- s.set_import_resolver(Box::new(FileImportResolver::default()));
-
- let v = match s.import(file.to_owned()) {
- Ok(v) => v,
- Err(e) => return s.stringify_err(&e),
- };
- match v.to_json(
- s.clone(),
- 3,
- #[cfg(feature = "exp-preserve-order")]
- false,
- ) {
- Ok(v) => v.to_string(),
- Err(e) => s.stringify_err(&e),
- }
-}
-
-#[test]
-fn test() -> io::Result<()> {
- let mut root = PathBuf::from(env!("CARGO_MANIFEST_DIR"));
- root.push("tests/golden");
-
- for entry in fs::read_dir(&root)? {
- let entry = entry?;
- if !entry.path().extension().map_or(false, |e| e == "jsonnet") {
- continue;
- }
-
- let result = run(&root, &entry.path());
-
- let mut golden_path = entry.path();
- golden_path.set_extension("jsonnet.golden");
-
- if !golden_path.exists() {
- fs::write(golden_path, &result)?;
- } else {
- let golden = fs::read_to_string(golden_path)?;
-
- assert_eq!(
- result,
- golden,
- "golden didn't match for {}",
- entry.path().display()
- )
- }
- }
-
- Ok(())
-}
crates/jrsonnet-evaluator/tests/golden/array_comp.jsonnetdiffbeforeafterboth--- a/crates/jrsonnet-evaluator/tests/golden/array_comp.jsonnet
+++ /dev/null
@@ -1 +0,0 @@
-[[a, b] for a in [1, 2, 3] for b in [4, 5, 6]]
crates/jrsonnet-evaluator/tests/golden/array_comp.jsonnet.goldendiffbeforeafterboth--- a/crates/jrsonnet-evaluator/tests/golden/array_comp.jsonnet.golden
+++ /dev/null
@@ -1,38 +0,0 @@
-[
- [
- 1,
- 4
- ],
- [
- 1,
- 5
- ],
- [
- 1,
- 6
- ],
- [
- 2,
- 4
- ],
- [
- 2,
- 5
- ],
- [
- 2,
- 6
- ],
- [
- 3,
- 4
- ],
- [
- 3,
- 5
- ],
- [
- 3,
- 6
- ]
-]
\ No newline at end of file
crates/jrsonnet-evaluator/tests/golden/builtin_json.jsonnetdiffbeforeafterboth--- a/crates/jrsonnet-evaluator/tests/golden/builtin_json.jsonnet
+++ /dev/null
@@ -1 +0,0 @@
-std.manifestJsonEx({ a: 3, b: 4, c: 6 }, '')
crates/jrsonnet-evaluator/tests/golden/builtin_json.jsonnet.goldendiffbeforeafterboth--- a/crates/jrsonnet-evaluator/tests/golden/builtin_json.jsonnet.golden
+++ /dev/null
@@ -1 +0,0 @@
-"{\n\"a\": 3,\n\"b\": 4,\n\"c\": 6\n}"
\ No newline at end of file
crates/jrsonnet-evaluator/tests/golden/builtin_json_minified.jsonnetdiffbeforeafterboth--- a/crates/jrsonnet-evaluator/tests/golden/builtin_json_minified.jsonnet
+++ /dev/null
@@ -1 +0,0 @@
-std.manifestJsonMinified({ a: 3, b: 4, c: 6 })
crates/jrsonnet-evaluator/tests/golden/builtin_json_minified.jsonnet.goldendiffbeforeafterboth--- a/crates/jrsonnet-evaluator/tests/golden/builtin_json_minified.jsonnet.golden
+++ /dev/null
@@ -1 +0,0 @@
-"{\"a\":3,\"b\":4,\"c\":6}"
\ No newline at end of file
crates/jrsonnet-evaluator/tests/golden/builtin_parseJson.jsonnetdiffbeforeafterboth--- a/crates/jrsonnet-evaluator/tests/golden/builtin_parseJson.jsonnet
+++ /dev/null
@@ -1 +0,0 @@
-std.parseJson('{"a": -1,"b": 1,"c": 3.141,"d": []}')
crates/jrsonnet-evaluator/tests/golden/builtin_parseJson.jsonnet.goldendiffbeforeafterboth--- a/crates/jrsonnet-evaluator/tests/golden/builtin_parseJson.jsonnet.golden
+++ /dev/null
@@ -1,6 +0,0 @@
-{
- "a": -1,
- "b": 1,
- "c": 3.141,
- "d": [ ]
-}
\ No newline at end of file
crates/jrsonnet-evaluator/tests/golden/issue23.jsonnetdiffbeforeafterboth--- a/crates/jrsonnet-evaluator/tests/golden/issue23.jsonnet
+++ /dev/null
@@ -1 +0,0 @@
-import 'issue23.jsonnet'
crates/jrsonnet-evaluator/tests/golden/issue23.jsonnet.goldendiffbeforeafterboth--- a/crates/jrsonnet-evaluator/tests/golden/issue23.jsonnet.golden
+++ /dev/null
@@ -1,2 +0,0 @@
-infinite recursion detected
- issue23.jsonnet:1:1-26: import "issue23.jsonnet"
\ No newline at end of file
crates/jrsonnet-evaluator/tests/golden/issue40.jsonnetdiffbeforeafterboth--- a/crates/jrsonnet-evaluator/tests/golden/issue40.jsonnet
+++ /dev/null
@@ -1,9 +0,0 @@
-local conf = {
- n: '',
-};
-
-local result = conf {
- assert std.isNumber(self.n) : 'is number',
-};
-
-std.manifestJsonEx(result, '')
crates/jrsonnet-evaluator/tests/golden/issue40.jsonnet.goldendiffbeforeafterboth--- a/crates/jrsonnet-evaluator/tests/golden/issue40.jsonnet.golden
+++ /dev/null
@@ -1,3 +0,0 @@
-assert failed: is number
- issue40.jsonnet:6:10-31: assertion failure
- issue40.jsonnet:9:1-32: function <builtin_manifest_json_ex> call
\ No newline at end of file
crates/jrsonnet-evaluator/tests/golden/missing_binding.jsonnetdiffbeforeafterboth--- a/crates/jrsonnet-evaluator/tests/golden/missing_binding.jsonnet
+++ /dev/null
@@ -1 +0,0 @@
-sta
crates/jrsonnet-evaluator/tests/golden/missing_binding.jsonnet.goldendiffbeforeafterboth--- a/crates/jrsonnet-evaluator/tests/golden/missing_binding.jsonnet.golden
+++ /dev/null
@@ -1,3 +0,0 @@
-variable is not defined: sta
-There is variable with similar name present: std
- missing_binding.jsonnet:1:1-5: variable <sta> access
\ No newline at end of file
crates/jrsonnet-evaluator/tests/golden/object_comp.jsonnetdiffbeforeafterboth--- a/crates/jrsonnet-evaluator/tests/golden/object_comp.jsonnet
+++ /dev/null
@@ -1 +0,0 @@
-{ 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 }
crates/jrsonnet-evaluator/tests/golden/object_comp.jsonnet.goldendiffbeforeafterboth--- a/crates/jrsonnet-evaluator/tests/golden/object_comp.jsonnet.golden
+++ /dev/null
@@ -1,9 +0,0 @@
-{
- "h1_2": "0a",
- "h1_3": "0a",
- "h1_4": "0a",
- "h2_3": "a1",
- "h2_4": "a1",
- "h3_2": "0a",
- "h3_4": "a1"
-}
\ No newline at end of file
crates/jrsonnet-evaluator/tests/golden/test_assertThrow.jsonnetdiffbeforeafterboth--- a/crates/jrsonnet-evaluator/tests/golden/test_assertThrow.jsonnet
+++ /dev/null
@@ -1,2 +0,0 @@
-// Test that test.assertThrow will return error, if body is not errored
-test.assertThrow(1, '1')
crates/jrsonnet-evaluator/tests/golden/test_assertThrow.jsonnet.goldendiffbeforeafterboth--- a/crates/jrsonnet-evaluator/tests/golden/test_assertThrow.jsonnet.golden
+++ /dev/null
@@ -1,2 +0,0 @@
-runtime error: expected argument to throw on evaluation, but it returned instead
- test_assertThrow.jsonnet:2:1-26: function <assert_throw> call
\ No newline at end of file
crates/jrsonnet-evaluator/tests/sanity.rsdiffbeforeafterboth--- a/crates/jrsonnet-evaluator/tests/sanity.rs
+++ /dev/null
@@ -1,41 +0,0 @@
-use jrsonnet_evaluator::{error::Result, throw_runtime, State, Val};
-
-mod common;
-
-#[test]
-fn assert_positive() -> Result<()> {
- let s = State::default();
- s.with_stdlib();
-
- let v = s.evaluate_snippet("snip".to_owned(), "assert 1 == 1: 'fail'; null".into())?;
- ensure_val_eq!(s, v, Val::Null);
- let v = s.evaluate_snippet("snip".to_owned(), "std.assertEqual(1, 1)".into())?;
- ensure_val_eq!(s, v, Val::Bool(true));
-
- Ok(())
-}
-
-#[test]
-fn assert_negative() -> Result<()> {
- let s = State::default();
- s.with_stdlib();
-
- {
- let e = match s.evaluate_snippet("snip".to_owned(), "assert 1 == 2: 'fail'; null".into()) {
- Ok(_) => throw_runtime!("assertion should fail"),
- Err(e) => e,
- };
- let e = s.stringify_err(&e);
- ensure!(e.starts_with("assert failed: fail\n"));
- }
- {
- let e = match s.evaluate_snippet("snip".to_owned(), "std.assertEqual(1, 2)".into()) {
- Ok(_) => throw_runtime!("assertion should fail"),
- Err(e) => e,
- };
- let e = s.stringify_err(&e);
- ensure!(e.starts_with("runtime error: Assertion failed. 1 != 2"))
- }
-
- Ok(())
-}
crates/jrsonnet-evaluator/tests/suite.rsdiffbeforeafterboth--- a/crates/jrsonnet-evaluator/tests/suite.rs
+++ /dev/null
@@ -1,46 +0,0 @@
-use std::{
- fs, io,
- path::{Path, PathBuf},
-};
-
-use jrsonnet_evaluator::{
- trace::{CompactFormat, PathResolver},
- FileImportResolver, State, Val,
-};
-
-mod common;
-
-fn run(root: &Path, file: &Path) {
- let s = State::default();
- s.set_trace_format(Box::new(CompactFormat {
- resolver: PathResolver::Relative(root.to_owned()),
- padding: 3,
- }));
- s.with_stdlib();
- common::with_test(&s);
- s.set_import_resolver(Box::new(FileImportResolver::default()));
-
- match s.import(file.to_owned()) {
- Ok(Val::Bool(true)) => {}
- Ok(Val::Bool(false)) => panic!("test {} returned false", file.display()),
- Ok(_) => panic!("test {} returned wrong type as result", file.display()),
- Err(e) => panic!("test {} failed:\n{}", file.display(), s.stringify_err(&e)),
- };
-}
-
-#[test]
-fn test() -> io::Result<()> {
- let mut root = PathBuf::from(env!("CARGO_MANIFEST_DIR"));
- root.push("tests/suite");
-
- for entry in fs::read_dir(&root)? {
- let entry = entry?;
- if !entry.path().extension().map_or(false, |e| e == "jsonnet") {
- continue;
- }
-
- run(&root, &entry.path());
- }
-
- Ok(())
-}
crates/jrsonnet-evaluator/tests/suite/builtin_ascii.jsonnetdiffbeforeafterboth--- a/crates/jrsonnet-evaluator/tests/suite/builtin_ascii.jsonnet
+++ /dev/null
@@ -1,3 +0,0 @@
-std.assertEqual(std.asciiUpper('aBc😀'), 'ABC😀') &&
-std.assertEqual(std.asciiLower('aBc😀'), 'abc😀') &&
-true
crates/jrsonnet-evaluator/tests/suite/builtin_base64.jsonnetdiffbeforeafterboth--- a/crates/jrsonnet-evaluator/tests/suite/builtin_base64.jsonnet
+++ /dev/null
@@ -1,2 +0,0 @@
-std.assertEqual(std.base64('test'), 'dGVzdA==') &&
-true
crates/jrsonnet-evaluator/tests/suite/builtin_chars.jsonnetdiffbeforeafterboth--- a/crates/jrsonnet-evaluator/tests/suite/builtin_chars.jsonnet
+++ /dev/null
@@ -1,3 +0,0 @@
-local c = '😎';
-std.assertEqual({ c: std.codepoint(c), l: std.length(c) }, { c: 128526, l: 1 }) &&
-true
crates/jrsonnet-evaluator/tests/suite/builtin_constant.jsonnetdiffbeforeafterboth--- a/crates/jrsonnet-evaluator/tests/suite/builtin_constant.jsonnet
+++ /dev/null
@@ -1,3 +0,0 @@
-local std2 = std; local std = std2 { primitiveEquals(a, b):: false };
-// In jsonnet, this expression was failing because of being desugared to std.primitiveEquals(1, 1)
-std.assertEqual(1 == 1, true)
crates/jrsonnet-evaluator/tests/suite/builtin_count.jsonnetdiffbeforeafterboth--- a/crates/jrsonnet-evaluator/tests/suite/builtin_count.jsonnet
+++ /dev/null
@@ -1,4 +0,0 @@
-std.assertEqual(std.count([], ''), 0) &&
-std.assertEqual(std.count(['a', 'b', 'a'], 'd'), 0) &&
-std.assertEqual(std.count(['a', 'b', 'a'], 'a'), 2) &&
-true
crates/jrsonnet-evaluator/tests/suite/builtin_join.jsonnetdiffbeforeafterboth--- a/crates/jrsonnet-evaluator/tests/suite/builtin_join.jsonnet
+++ /dev/null
@@ -1,4 +0,0 @@
-std.assertEqual(std.join([0, 0], [[1, 2], [3, 4], [5, 6]]), [1, 2, 0, 0, 3, 4, 0, 0, 5, 6]) &&
-std.assertEqual(std.join(',', ['1', '2', '3', '4']), '1,2,3,4') &&
-std.assertEqual(std.join(',', ['1', null, '2', null, '3']), '1,2,3') &&
-true
crates/jrsonnet-evaluator/tests/suite/builtin_member.jsonnetdiffbeforeafterboth--- a/crates/jrsonnet-evaluator/tests/suite/builtin_member.jsonnet
+++ /dev/null
@@ -1,7 +0,0 @@
-!std.member('', '') &&
-std.member('abc', 'a') &&
-!std.member('abc', 'd') &&
-!std.member([], '') &&
-std.member(['a', 'b', 'c'], 'a') &&
-!std.member(['a', 'b', 'c'], 'd') &&
-true
crates/jrsonnet-evaluator/tests/suite/function_args.jsonnetdiffbeforeafterboth--- a/crates/jrsonnet-evaluator/tests/suite/function_args.jsonnet
+++ /dev/null
@@ -1,3 +0,0 @@
-std.assertEqual(local a = function(b, c=2) b + c; a(2), 4) &&
-std.assertEqual(local a = function(b, c='Dear') b + c + d, d = 'World'; a('Hello'), 'HelloDearWorld') &&
-true
crates/jrsonnet-evaluator/tests/suite/function_context.jsonnetdiffbeforeafterboth--- a/crates/jrsonnet-evaluator/tests/suite/function_context.jsonnet
+++ /dev/null
@@ -1,10 +0,0 @@
-local k = {
- t(name=self.h): [self.h, name],
- h: 3,
-};
-local f = {
- t: k.t(),
- h: 4,
-};
-std.assertEqual(f.t[0], f.t[1]) &&
-true
crates/jrsonnet-evaluator/tests/suite/function_lazy_args.jsonnetdiffbeforeafterboth--- a/crates/jrsonnet-evaluator/tests/suite/function_lazy_args.jsonnet
+++ /dev/null
@@ -1,5 +0,0 @@
-local fun(a) = 2;
-std.assertEqual(fun(error '3'), 2) &&
-// But in tailstrict mode arguments are evaluated eagerly
-test.assertThrow(fun(error '3') tailstrict, 'runtime error: 3') &&
-true
crates/jrsonnet-evaluator/tests/suite/local.jsonnetdiffbeforeafterboth--- a/crates/jrsonnet-evaluator/tests/suite/local.jsonnet
+++ /dev/null
@@ -1,4 +0,0 @@
-std.assertEqual(local a = 2; local b = 3; a + b, 5) &&
-std.assertEqual(local a = 1, b = a + 1; a + b, 3) &&
-std.assertEqual(local a = 1; local a = 2; a, 2) &&
-true
crates/jrsonnet-evaluator/tests/suite/math.jsonnetdiffbeforeafterboth--- a/crates/jrsonnet-evaluator/tests/suite/math.jsonnet
+++ /dev/null
@@ -1,3 +0,0 @@
-std.assertEqual(2 + 2 * 2, 6) &&
-std.assertEqual(3 + (2 + 2 * 2), 9) &&
-true
crates/jrsonnet-evaluator/tests/suite/object_assertion.jsonnetdiffbeforeafterboth--- a/crates/jrsonnet-evaluator/tests/suite/object_assertion.jsonnet
+++ /dev/null
@@ -1,3 +0,0 @@
-std.assertEqual({ assert 'a' in self : 'missing a' } + { a: 2 }, { a: 2 }) &&
-test.assertThrow({ assert 'a' in self : 'missing a', b: 1 }.b, 'assert failed: missing a') &&
-true
crates/jrsonnet-evaluator/tests/suite/object_comp_self.jsonnetdiffbeforeafterboth--- a/crates/jrsonnet-evaluator/tests/suite/object_comp_self.jsonnet
+++ /dev/null
@@ -1,8 +0,0 @@
-std.assertEqual(std.objectFields({
- a: {
- [name]: name
- for name in std.objectFields(self)
- },
- b: 2,
- c: 3,
-}.a), ['a', 'b', 'c'])
crates/jrsonnet-evaluator/tests/suite/object_context.jsonnetdiffbeforeafterboth--- a/crates/jrsonnet-evaluator/tests/suite/object_context.jsonnet
+++ /dev/null
@@ -1,13 +0,0 @@
-// `self` assigned to `me` was lost when being
-// referenced from field
-std.assertEqual({
- local me = self,
- a: 3,
- b: me.a,
-}.b, 3) &&
-std.assertEqual({
- local me = self,
- a: 3,
- b(): me.a,
-}.b(), 3) &&
-true
crates/jrsonnet-evaluator/tests/suite/object_fields.jsonnetdiffbeforeafterboth--- a/crates/jrsonnet-evaluator/tests/suite/object_fields.jsonnet
+++ /dev/null
@@ -1,4 +0,0 @@
-local a = 'a', b = null;
-std.assertEqual({ [a]: 2 }, { a: 2 }) &&
-std.assertEqual({ [b]: 2 }, {}) &&
-true
crates/jrsonnet-evaluator/tests/suite/object_inheritance.jsonnetdiffbeforeafterboth--- a/crates/jrsonnet-evaluator/tests/suite/object_inheritance.jsonnet
+++ /dev/null
@@ -1,17 +0,0 @@
-std.assertEqual({ a: self.b } + { b: 3 }, { a: 3, b: 3 }) &&
-std.assertEqual(
- {
- name: 'Alice',
- welcome: 'Hello ' + self.name + '!',
- },
- { name: 'Alice', welcome: 'Hello Alice!' },
-) &&
-std.assertEqual(
- {
- name: 'Alice',
- welcome: 'Hello ' + self.name + '!',
- } + {
- name: 'Bob',
- }, { name: 'Bob', welcome: 'Hello Bob!' }
-) &&
-true
crates/jrsonnet-evaluator/tests/suite/object_locals.jsonnetdiffbeforeafterboth--- a/crates/jrsonnet-evaluator/tests/suite/object_locals.jsonnet
+++ /dev/null
@@ -1,4 +0,0 @@
-std.assertEqual({ local a = 3, b: a }, { b: 3 }) &&
-std.assertEqual({ local a = 3, local c = a, b: c }, { b: 3 }) &&
-std.assertEqual({ local a = function(b) { [b]: 4 }, test: a('test') }, { test: { test: 4 } }) &&
-true
crates/jrsonnet-evaluator/tests/suite/object_super_standalone.jsonnetdiffbeforeafterboth--- a/crates/jrsonnet-evaluator/tests/suite/object_super_standalone.jsonnet
+++ /dev/null
@@ -1,11 +0,0 @@
-local obj = {
- a: 1,
- b: 2,
- c: 3,
-};
-local test = obj + {
- fields: std.objectFields(super),
- d: 5,
-};
-std.assertEqual(test.fields, ['a', 'b', 'c']) &&
-true
crates/jrsonnet-evaluator/tests/suite/sjsonnet_issue_127.jsonnetdiffbeforeafterboth--- a/crates/jrsonnet-evaluator/tests/suite/sjsonnet_issue_127.jsonnet
+++ /dev/null
@@ -1,6 +0,0 @@
-local myFunc = function(a)
- if (a) then "a" else "b";
-
-local b = "aaa";
-
-std.assertEqual(myFunc(b == [] || b == ['e']), "b")
crates/jrsonnet-evaluator/tests/suite/string_concat.jsonnetdiffbeforeafterboth--- a/crates/jrsonnet-evaluator/tests/suite/string_concat.jsonnet
+++ /dev/null
@@ -1,4 +0,0 @@
-std.assertEqual('Hello' + 'World', 'HelloWorld') &&
-std.assertEqual('Hello' * 3, 'HelloHelloHello') &&
-std.assertEqual('Hello' + 'World' * 3, 'HelloWorldWorldWorld') &&
-true
crates/jrsonnet-evaluator/tests/typed_obj.rsdiffbeforeafterboth--- a/crates/jrsonnet-evaluator/tests/typed_obj.rs
+++ /dev/null
@@ -1,194 +0,0 @@
-mod common;
-
-use std::fmt::Debug;
-
-use jrsonnet_evaluator::{error::Result, typed::Typed, State};
-
-#[derive(Clone, Typed, PartialEq, Debug)]
-struct A {
- a: u32,
- b: u16,
-}
-
-fn test_roundtrip<T: Typed + PartialEq + Debug + Clone>(value: T, s: State) -> Result<()> {
- let untyped = T::into_untyped(value.clone(), s.clone())?;
- let value2 = T::from_untyped(untyped.clone(), s.clone())?;
- ensure_eq!(value, value2);
- let untyped2 = T::into_untyped(value2, s.clone())?;
- ensure_val_eq!(s, untyped, untyped2);
-
- Ok(())
-}
-
-#[test]
-fn simple_object() -> Result<()> {
- let s = State::default();
- s.with_stdlib();
- let a = A::from_untyped(
- s.evaluate_snippet("snip".to_owned(), "{a: 1, b: 2}".into())?,
- s.clone(),
- )?;
- ensure_eq!(a, A { a: 1, b: 2 });
- test_roundtrip(a, s)?;
- Ok(())
-}
-
-#[derive(Clone, Typed, PartialEq, Debug)]
-struct B {
- a: u32,
- #[typed(rename = "c")]
- b: u16,
-}
-
-#[test]
-fn renamed_field() -> Result<()> {
- let s = State::default();
- s.with_stdlib();
- let b = B::from_untyped(
- s.evaluate_snippet("snip".to_owned(), "{a: 1, c: 2}".into())?,
- s.clone(),
- )?;
- ensure_eq!(b, B { a: 1, b: 2 });
- ensure_eq!(
- &B::into_untyped(b.clone(), s.clone())?.to_string(s.clone())? as &str,
- r#"{"a": 1, "c": 2}"#,
- );
- test_roundtrip(b, s)?;
- Ok(())
-}
-
-#[derive(Clone, Typed, PartialEq, Debug)]
-struct ObjectKind {
- #[typed(rename = "apiVersion")]
- api_version: String,
- #[typed(rename = "kind")]
- kind: String,
-}
-
-#[derive(Clone, Typed, PartialEq, Debug)]
-struct Object {
- #[typed(flatten)]
- kind: ObjectKind,
- b: u16,
-}
-
-#[test]
-fn flattened_object() -> Result<()> {
- let s = State::default();
- s.with_stdlib();
- let obj = Object::from_untyped(
- s.evaluate_snippet(
- "snip".to_owned(),
- "{apiVersion: 'ver', kind: 'kind', b: 2}".into(),
- )?,
- s.clone(),
- )?;
- ensure_eq!(
- obj,
- Object {
- kind: ObjectKind {
- api_version: "ver".into(),
- kind: "kind".into(),
- },
- b: 2
- }
- );
- ensure_eq!(
- &Object::into_untyped(obj.clone(), s.clone())?.to_string(s.clone())? as &str,
- r#"{"apiVersion": "ver", "b": 2, "kind": "kind"}"#,
- );
- test_roundtrip(obj, s)?;
- Ok(())
-}
-
-#[derive(Clone, Typed, PartialEq, Debug)]
-struct C {
- a: Option<u32>,
- b: u16,
-}
-
-#[test]
-fn optional_field_some() -> Result<()> {
- let s = State::default();
- s.with_stdlib();
- let c = C::from_untyped(
- s.evaluate_snippet("snip".to_owned(), "{a: 1, b: 2}".into())?,
- s.clone(),
- )?;
- ensure_eq!(c, C { a: Some(1), b: 2 });
- ensure_eq!(
- &C::into_untyped(c.clone(), s.clone())?.to_string(s.clone())? as &str,
- r#"{"a": 1, "b": 2}"#,
- );
- test_roundtrip(c, s)?;
- Ok(())
-}
-
-#[test]
-fn optional_field_none() -> Result<()> {
- let s = State::default();
- s.with_stdlib();
- let c = C::from_untyped(
- s.evaluate_snippet("snip".to_owned(), "{b: 2}".into())?,
- s.clone(),
- )?;
- ensure_eq!(c, C { a: None, b: 2 });
- ensure_eq!(
- &C::into_untyped(c.clone(), s.clone())?.to_string(s.clone())? as &str,
- r#"{"b": 2}"#,
- );
- test_roundtrip(c, s)?;
- Ok(())
-}
-
-#[derive(Clone, Typed, PartialEq, Debug)]
-struct D {
- #[typed(flatten(ok))]
- e: Option<E>,
- b: u16,
-}
-
-#[derive(Clone, Typed, PartialEq, Debug)]
-struct E {
- v: u32,
-}
-
-#[test]
-fn flatten_optional_some() -> Result<()> {
- let s = State::default();
- s.with_stdlib();
- let d = D::from_untyped(
- s.evaluate_snippet("snip".to_owned(), "{b: 2, v:1}".into())?,
- s.clone(),
- )?;
- ensure_eq!(
- d,
- D {
- e: Some(E { v: 1 }),
- b: 2
- }
- );
- ensure_eq!(
- &D::into_untyped(d.clone(), s.clone())?.to_string(s.clone())? as &str,
- r#"{"b": 2, "v": 1}"#,
- );
- test_roundtrip(d, s)?;
- Ok(())
-}
-
-#[test]
-fn flatten_optional_none() -> Result<()> {
- let s = State::default();
- s.with_stdlib();
- let d = D::from_untyped(
- s.evaluate_snippet("snip".to_owned(), "{b: 2, v: '1'}".into())?,
- s.clone(),
- )?;
- ensure_eq!(d, D { e: None, b: 2 });
- ensure_eq!(
- &D::into_untyped(d.clone(), s.clone())?.to_string(s.clone())? as &str,
- r#"{"b": 2}"#,
- );
- test_roundtrip(d, s)?;
- Ok(())
-}
crates/jrsonnet-parser/src/lib.rsdiffbeforeafterboth1#![allow(clippy::redundant_closure_call, clippy::derive_partial_eq_without_eq)]23use std::rc::Rc;45use peg::parser;6mod expr;7pub use expr::*;8pub use jrsonnet_interner::IStr;9pub use peg;10mod location;11mod source;12mod unescape;13pub use location::CodeLocation;14pub use source::{Source, SourcePath};1516pub struct ParserSettings {17 pub file_name: Source,18}1920macro_rules! expr_bin {21 ($a:ident $op:ident $b:ident) => {22 Expr::BinaryOp($a, $op, $b)23 };24}25macro_rules! expr_un {26 ($op:ident $a:ident) => {27 Expr::UnaryOp($op, $a)28 };29}3031parser! {32 grammar jsonnet_parser() for str {33 use peg::ParseLiteral;3435 rule eof() = quiet!{![_]} / expected!("<eof>")36 rule eol() = "\n" / eof()3738 /// Standard C-like comments39 rule comment()40 = "//" (!eol()[_])* eol()41 / "/*" ("\\*/" / "\\\\" / (!("*/")[_]))* "*/"42 / "#" (!eol()[_])* eol()4344 rule single_whitespace() = quiet!{([' ' | '\r' | '\n' | '\t'] / comment())} / expected!("<whitespace>")45 rule _() = quiet!{([' ' | '\r' | '\n' | '\t']+) / comment()}* / expected!("<whitespace>")4647 /// For comma-delimited elements48 rule comma() = quiet!{_ "," _} / expected!("<comma>")49 rule alpha() -> char = c:$(['_' | 'a'..='z' | 'A'..='Z']) {c.chars().next().unwrap()}50 rule digit() -> char = d:$(['0'..='9']) {d.chars().next().unwrap()}51 rule end_of_ident() = !['0'..='9' | '_' | 'a'..='z' | 'A'..='Z']52 /// Sequence of digits53 rule uint_str() -> &'input str = a:$(digit()+) { a }54 /// Number in scientific notation format55 rule number() -> f64 = quiet!{a:$(uint_str() ("." uint_str())? (['e'|'E'] (s:['+'|'-'])? uint_str())?) {? a.parse().map_err(|_| "<number>") }} / expected!("<number>")5657 /// Reserved word followed by any non-alphanumberic58 rule reserved() = ("assert" / "else" / "error" / "false" / "for" / "function" / "if" / "import" / "importstr" / "importbin" / "in" / "local" / "null" / "tailstrict" / "then" / "self" / "super" / "true") end_of_ident()59 rule id() -> IStr = v:$(quiet!{ !reserved() alpha() (alpha() / digit())*} / expected!("<identifier>")) { v.into() }6061 rule keyword(id: &'static str) -> ()62 = ##parse_string_literal(id) end_of_ident()6364 pub rule param(s: &ParserSettings) -> expr::Param = name:destruct(s) expr:(_ "=" _ expr:expr(s){expr})? { expr::Param(name, expr) }65 pub rule params(s: &ParserSettings) -> expr::ParamsDesc66 = params:param(s) ** comma() comma()? { expr::ParamsDesc(Rc::new(params)) }67 / { expr::ParamsDesc(Rc::new(Vec::new())) }6869 pub rule arg(s: &ParserSettings) -> (Option<IStr>, LocExpr)70 = quiet! { name:(s:id() _ "=" !['='] _ {s})? expr:expr(s) {(name, expr)} }71 / expected!("<argument>")7273 pub rule args(s: &ParserSettings) -> expr::ArgsDesc74 = args:arg(s)**comma() comma()? {?75 let unnamed_count = args.iter().take_while(|(n, _)| n.is_none()).count();76 let mut unnamed = Vec::with_capacity(unnamed_count);77 let mut named = Vec::with_capacity(args.len() - unnamed_count);78 let mut named_started = false;79 for (name, value) in args {80 if let Some(name) = name {81 named_started = true;82 named.push((name, value));83 } else {84 if named_started {85 return Err("<named argument>")86 }87 unnamed.push(value);88 }89 }90 Ok(expr::ArgsDesc::new(unnamed, named))91 }9293 pub rule destruct_rest() -> expr::DestructRest94 = "..." into:(_ into:id() {into})? {if let Some(into) = into {95 expr::DestructRest::Keep(into)96 } else {expr::DestructRest::Drop}}97 pub rule destruct_array(s: &ParserSettings) -> expr::Destruct98 = "[" _ start:destruct(s)**comma() rest:(99 comma() _ rest:destruct_rest()? end:(100 comma() end:destruct(s)**comma() (_ comma())? {end}101 / comma()? {Vec::new()}102 ) {(rest, end)}103 / comma()? {(None, Vec::new())}104 ) _ "]" {?105 #[cfg(feature = "exp-destruct")] return Ok(expr::Destruct::Array {106 start,107 rest: rest.0,108 end: rest.1,109 });110 #[cfg(not(feature = "exp-destruct"))] Err("experimental destructuring was not enabled")111 }112 pub rule destruct_object(s: &ParserSettings) -> expr::Destruct113 = "{" _114 fields:(name:id() into:(_ ":" _ into:destruct(s) {into})? default:(_ "=" _ v:expr(s) {v})? {(name, into, default)})**comma()115 rest:(116 comma() rest:destruct_rest()? {rest}117 / comma()? {None}118 )119 _ "}" {?120 #[cfg(feature = "exp-destruct")] return Ok(expr::Destruct::Object {121 fields,122 rest,123 });124 #[cfg(not(feature = "exp-destruct"))] Err("experimental destructuring was not enabled")125 }126 pub rule destruct(s: &ParserSettings) -> expr::Destruct127 = v:id() {expr::Destruct::Full(v)}128 / "?" {?129 #[cfg(feature = "exp-destruct")] return Ok(expr::Destruct::Skip);130 #[cfg(not(feature = "exp-destruct"))] Err("experimental destructuring was not enabled")131 }132 / arr:destruct_array(s) {arr}133 / obj:destruct_object(s) {obj}134135 pub rule bind(s: &ParserSettings) -> expr::BindSpec136 = into:destruct(s) _ "=" _ expr:expr(s) {expr::BindSpec::Field{into, value: expr}}137 / name:id() _ "(" _ params:params(s) _ ")" _ "=" _ expr:expr(s) {expr::BindSpec::Function{name, params, value: expr}}138139 pub rule assertion(s: &ParserSettings) -> expr::AssertStmt140 = keyword("assert") _ cond:expr(s) msg:(_ ":" _ e:expr(s) {e})? { expr::AssertStmt(cond, msg) }141142 pub rule whole_line() -> &'input str143 = str:$((!['\n'][_])* "\n") {str}144 pub rule string_block() -> String145 = "|||" (!['\n']single_whitespace())* "\n"146 empty_lines:$(['\n']*)147 prefix:[' ' | '\t']+ first_line:whole_line()148 lines:("\n" {"\n"} / [' ' | '\t']*<{prefix.len()}> s:whole_line() {s})*149 [' ' | '\t']*<, {prefix.len() - 1}> "|||"150 {let mut l = empty_lines.to_owned(); l.push_str(first_line); l.extend(lines); l}151152 rule hex_char()153 = quiet! { ['0'..='9' | 'a'..='f' | 'A'..='F'] } / expected!("<hex char>")154155 rule string_char(c: rule<()>)156 = (!['\\']!c()[_])+157 / "\\\\"158 / "\\u" hex_char() hex_char() hex_char() hex_char()159 / "\\x" hex_char() hex_char()160 / ['\\'] (quiet! { ['b' | 'f' | 'n' | 'r' | 't' | '"' | '\''] } / expected!("<escape character>"))161 pub rule string() -> String162 = ['"'] str:$(string_char(<"\"">)*) ['"'] {? unescape::unescape(str).ok_or("<escaped string>")}163 / ['\''] str:$(string_char(<"\'">)*) ['\''] {? unescape::unescape(str).ok_or("<escaped string>")}164 / quiet!{ "@'" str:$(("''" / (!['\''][_]))*) "'" {str.replace("''", "'")}165 / "@\"" str:$(("\"\"" / (!['"'][_]))*) "\"" {str.replace("\"\"", "\"")}166 / string_block() } / expected!("<string>")167168 pub rule field_name(s: &ParserSettings) -> expr::FieldName169 = name:id() {expr::FieldName::Fixed(name)}170 / name:string() {expr::FieldName::Fixed(name.into())}171 / "[" _ expr:expr(s) _ "]" {expr::FieldName::Dyn(expr)}172 pub rule visibility() -> expr::Visibility173 = ":::" {expr::Visibility::Unhide}174 / "::" {expr::Visibility::Hidden}175 / ":" {expr::Visibility::Normal}176 pub rule field(s: &ParserSettings) -> expr::FieldMember177 = name:field_name(s) _ plus:"+"? _ visibility:visibility() _ value:expr(s) {expr::FieldMember{178 name,179 plus: plus.is_some(),180 params: None,181 visibility,182 value,183 }}184 / name:field_name(s) _ "(" _ params:params(s) _ ")" _ visibility:visibility() _ value:expr(s) {expr::FieldMember{185 name,186 plus: false,187 params: Some(params),188 visibility,189 value,190 }}191 pub rule obj_local(s: &ParserSettings) -> BindSpec192 = keyword("local") _ bind:bind(s) {bind}193 pub rule member(s: &ParserSettings) -> expr::Member194 = bind:obj_local(s) {expr::Member::BindStmt(bind)}195 / assertion:assertion(s) {expr::Member::AssertStmt(assertion)}196 / field:field(s) {expr::Member::Field(field)}197 pub rule objinside(s: &ParserSettings) -> expr::ObjBody198 = pre_locals:(b: obj_local(s) comma() {b})* "[" _ key:expr(s) _ "]" _ plus:"+"? _ ":" _ value:expr(s) post_locals:(comma() b:obj_local(s) {b})* _ ("," _)? forspec:forspec(s) others:(_ rest:compspec(s) {rest})? {199 let mut compspecs = vec![CompSpec::ForSpec(forspec)];200 compspecs.extend(others.unwrap_or_default());201 expr::ObjBody::ObjComp(expr::ObjComp{202 pre_locals,203 key,204 plus: plus.is_some(),205 value,206 post_locals,207 compspecs,208 })209 }210 / members:(member(s) ** comma()) comma()? {expr::ObjBody::MemberList(members)}211 pub rule ifspec(s: &ParserSettings) -> IfSpecData212 = keyword("if") _ expr:expr(s) {IfSpecData(expr)}213 pub rule forspec(s: &ParserSettings) -> ForSpecData214 = keyword("for") _ id:id() _ keyword("in") _ cond:expr(s) {ForSpecData(id, cond)}215 pub rule compspec(s: &ParserSettings) -> Vec<expr::CompSpec>216 = s:(i:ifspec(s) { expr::CompSpec::IfSpec(i) } / f:forspec(s) {expr::CompSpec::ForSpec(f)} ) ** _ {s}217 pub rule local_expr(s: &ParserSettings) -> Expr218 = keyword("local") _ binds:bind(s) ** comma() (_ ",")? _ ";" _ expr:expr(s) { Expr::LocalExpr(binds, expr) }219 pub rule string_expr(s: &ParserSettings) -> Expr220 = s:string() {Expr::Str(s.into())}221 pub rule obj_expr(s: &ParserSettings) -> Expr222 = "{" _ body:objinside(s) _ "}" {Expr::Obj(body)}223 pub rule array_expr(s: &ParserSettings) -> Expr224 = "[" _ elems:(expr(s) ** comma()) _ comma()? "]" {Expr::Arr(elems)}225 pub rule array_comp_expr(s: &ParserSettings) -> Expr226 = "[" _ expr:expr(s) _ comma()? _ forspec:forspec(s) _ others:(others: compspec(s) _ {others})? "]" {227 let mut specs = vec![CompSpec::ForSpec(forspec)];228 specs.extend(others.unwrap_or_default());229 Expr::ArrComp(expr, specs)230 }231 pub rule number_expr(s: &ParserSettings) -> Expr232 = n:number() { expr::Expr::Num(n) }233 pub rule var_expr(s: &ParserSettings) -> Expr234 = n:id() { expr::Expr::Var(n) }235 pub rule id_loc(s: &ParserSettings) -> LocExpr236 = a:position!() n:id() b:position!() { LocExpr(Rc::new(expr::Expr::Str(n)), ExprLocation(s.file_name.clone(), a as u32,b as u32)) }237 pub rule if_then_else_expr(s: &ParserSettings) -> Expr238 = cond:ifspec(s) _ keyword("then") _ cond_then:expr(s) cond_else:(_ keyword("else") _ e:expr(s) {e})? {Expr::IfElse{239 cond,240 cond_then,241 cond_else,242 }}243244 pub rule literal(s: &ParserSettings) -> Expr245 = v:(246 keyword("null") {LiteralType::Null}247 / keyword("true") {LiteralType::True}248 / keyword("false") {LiteralType::False}249 / keyword("self") {LiteralType::This}250 / keyword("$") {LiteralType::Dollar}251 / keyword("super") {LiteralType::Super}252 ) {Expr::Literal(v)}253254 pub rule expr_basic(s: &ParserSettings) -> Expr255 = literal(s)256257 / string_expr(s) / number_expr(s)258 / array_expr(s)259 / obj_expr(s)260 / array_expr(s)261 / array_comp_expr(s)262263 / keyword("importstr") _ path:string() {Expr::ImportStr(path.into())}264 / keyword("importbin") _ path:string() {Expr::ImportBin(path.into())}265 / keyword("import") _ path:string() {Expr::Import(path.into())}266267 / var_expr(s)268 / local_expr(s)269 / if_then_else_expr(s)270271 / keyword("function") _ "(" _ params:params(s) _ ")" _ expr:expr(s) {Expr::Function(params, expr)}272 / assertion:assertion(s) _ ";" _ expr:expr(s) { Expr::AssertExpr(assertion, expr) }273274 / keyword("error") _ expr:expr(s) { Expr::ErrorStmt(expr) }275276 rule slice_part(s: &ParserSettings) -> Option<LocExpr>277 = _ e:(e:expr(s) _{e})? {e}278 pub rule slice_desc(s: &ParserSettings) -> SliceDesc279 = start:slice_part(s) ":" pair:(end:slice_part(s) step:(":" e:slice_part(s){e})? {(end, step.flatten())})? {280 let (end, step) = if let Some((end, step)) = pair {281 (end, step)282 }else{283 (None, None)284 };285286 SliceDesc { start, end, step }287 }288289 rule binop(x: rule<()>) -> ()290 = quiet!{ x() } / expected!("<binary op>")291 rule unaryop(x: rule<()>) -> ()292 = quiet!{ x() } / expected!("<unary op>")293294295 use BinaryOpType::*;296 use UnaryOpType::*;297 rule expr(s: &ParserSettings) -> LocExpr298 = precedence! {299 start:position!() v:@ end:position!() { LocExpr(Rc::new(v), ExprLocation(s.file_name.clone(), start as u32, end as u32)) }300 --301 a:(@) _ binop(<"||">) _ b:@ {expr_bin!(a Or b)}302 --303 a:(@) _ binop(<"&&">) _ b:@ {expr_bin!(a And b)}304 --305 a:(@) _ binop(<"|">) _ b:@ {expr_bin!(a BitOr b)}306 --307 a:@ _ binop(<"^">) _ b:(@) {expr_bin!(a BitXor b)}308 --309 a:(@) _ binop(<"&">) _ b:@ {expr_bin!(a BitAnd b)}310 --311 a:(@) _ binop(<"==">) _ b:@ {expr_bin!(a Eq b)}312 a:(@) _ binop(<"!=">) _ b:@ {expr_bin!(a Neq b)}313 --314 a:(@) _ binop(<"<">) _ b:@ {expr_bin!(a Lt b)}315 a:(@) _ binop(<">">) _ b:@ {expr_bin!(a Gt b)}316 a:(@) _ binop(<"<=">) _ b:@ {expr_bin!(a Lte b)}317 a:(@) _ binop(<">=">) _ b:@ {expr_bin!(a Gte b)}318 a:(@) _ binop(<keyword("in")>) _ b:@ {expr_bin!(a In b)}319 --320 a:(@) _ binop(<"<<">) _ b:@ {expr_bin!(a Lhs b)}321 a:(@) _ binop(<">>">) _ b:@ {expr_bin!(a Rhs b)}322 --323 a:(@) _ binop(<"+">) _ b:@ {expr_bin!(a Add b)}324 a:(@) _ binop(<"-">) _ b:@ {expr_bin!(a Sub b)}325 --326 a:(@) _ binop(<"*">) _ b:@ {expr_bin!(a Mul b)}327 a:(@) _ binop(<"/">) _ b:@ {expr_bin!(a Div b)}328 a:(@) _ binop(<"%">) _ b:@ {expr_bin!(a Mod b)}329 --330 unaryop(<"-">) _ b:@ {expr_un!(Minus b)}331 unaryop(<"!">) _ b:@ {expr_un!(Not b)}332 unaryop(<"~">) _ b:@ {expr_un!(BitNot b)}333 --334 a:(@) _ "[" _ e:slice_desc(s) _ "]" {Expr::Slice(a, e)}335 a:(@) _ "." _ a:position!() e:id_loc(s) b:position!() {Expr::Index(a, e)}336 a:(@) _ "[" _ e:expr(s) _ "]" {Expr::Index(a, e)}337 a:(@) _ "(" _ args:args(s) _ ")" ts:(_ keyword("tailstrict"))? {Expr::Apply(a, args, ts.is_some())}338 a:(@) _ "{" _ body:objinside(s) _ "}" {Expr::ObjExtend(a, body)}339 --340 e:expr_basic(s) {e}341 "(" _ e:expr(s) _ ")" {Expr::Parened(e)}342 }343344 pub rule jsonnet(s: &ParserSettings) -> LocExpr = _ e:expr(s) _ {e}345 }346}347348pub type ParseError = peg::error::ParseError<peg::str::LineCol>;349pub fn parse(str: &str, settings: &ParserSettings) -> Result<LocExpr, ParseError> {350 jsonnet_parser::jsonnet(str, settings)351}352/// Used for importstr values353pub fn string_to_expr(str: IStr, settings: &ParserSettings) -> LocExpr {354 let len = str.len();355 LocExpr(356 Rc::new(Expr::Str(str)),357 ExprLocation(settings.file_name.clone(), 0, len as u32),358 )359}360361#[cfg(test)]362pub mod tests {363 use std::borrow::Cow;364365 use BinaryOpType::*;366367 use super::{expr::*, parse};368 use crate::{source::Source, ParserSettings};369370 macro_rules! parse {371 ($s:expr) => {372 parse(373 $s,374 &ParserSettings {375 file_name: Source::new_virtual(Cow::Borrowed("<test>")),376 },377 )378 .unwrap()379 };380 }381382 macro_rules! el {383 ($expr:expr, $from:expr, $to:expr$(,)?) => {384 LocExpr(385 std::rc::Rc::new($expr),386 ExprLocation(Source::new_virtual(Cow::Borrowed("<test>")), $from, $to),387 )388 };389 }390391 #[test]392 fn multiline_string() {393 assert_eq!(394 parse!("|||\n Hello world!\n a\n|||"),395 el!(Expr::Str("Hello world!\n a\n".into()), 0, 31),396 );397 assert_eq!(398 parse!("|||\n Hello world!\n a\n|||"),399 el!(Expr::Str("Hello world!\n a\n".into()), 0, 27),400 );401 assert_eq!(402 parse!("|||\n\t\tHello world!\n\t\t\ta\n|||"),403 el!(Expr::Str("Hello world!\n\ta\n".into()), 0, 27),404 );405 assert_eq!(406 parse!("|||\n Hello world!\n a\n |||"),407 el!(Expr::Str("Hello world!\n a\n".into()), 0, 30),408 );409 }410411 #[test]412 fn slice() {413 parse!("a[1:]");414 parse!("a[1::]");415 parse!("a[:1:]");416 parse!("a[::1]");417 parse!("str[:len - 1]");418 }419420 #[test]421 fn string_escaping() {422 assert_eq!(423 parse!(r#""Hello, \"world\"!""#),424 el!(Expr::Str(r#"Hello, "world"!"#.into()), 0, 19),425 );426 assert_eq!(427 parse!(r#"'Hello \'world\'!'"#),428 el!(Expr::Str("Hello 'world'!".into()), 0, 18),429 );430 assert_eq!(parse!(r#"'\\\\'"#), el!(Expr::Str("\\\\".into()), 0, 6));431 }432433 #[test]434 fn string_unescaping() {435 assert_eq!(436 parse!(r#""Hello\nWorld""#),437 el!(Expr::Str("Hello\nWorld".into()), 0, 14),438 );439 }440441 #[test]442 fn string_verbantim() {443 assert_eq!(444 parse!(r#"@"Hello\n""World""""#),445 el!(Expr::Str("Hello\\n\"World\"".into()), 0, 19),446 );447 }448449 #[test]450 fn imports() {451 assert_eq!(452 parse!("import \"hello\""),453 el!(Expr::Import("hello".into()), 0, 14),454 );455 assert_eq!(456 parse!("importstr \"garnish.txt\""),457 el!(Expr::ImportStr("garnish.txt".into()), 0, 23)458 );459 assert_eq!(460 parse!("importbin \"garnish.bin\""),461 el!(Expr::ImportBin("garnish.bin".into()), 0, 23)462 );463 }464465 #[test]466 fn empty_object() {467 assert_eq!(468 parse!("{}"),469 el!(Expr::Obj(ObjBody::MemberList(vec![])), 0, 2)470 );471 }472473 #[test]474 fn basic_math() {475 assert_eq!(476 parse!("2+2*2"),477 el!(478 Expr::BinaryOp(479 el!(Expr::Num(2.0), 0, 1),480 Add,481 el!(482 Expr::BinaryOp(el!(Expr::Num(2.0), 2, 3), Mul, el!(Expr::Num(2.0), 4, 5)),483 2,484 5485 )486 ),487 0,488 5489 )490 );491 }492493 #[test]494 fn basic_math_with_indents() {495 assert_eq!(496 parse!("2 + 2 * 2 "),497 el!(498 Expr::BinaryOp(499 el!(Expr::Num(2.0), 0, 1),500 Add,501 el!(502 Expr::BinaryOp(el!(Expr::Num(2.0), 7, 8), Mul, el!(Expr::Num(2.0), 13, 14),),503 7,504 14505 ),506 ),507 0,508 14509 )510 );511 }512513 #[test]514 fn basic_math_parened() {515 assert_eq!(516 parse!("2+(2+2*2)"),517 el!(518 Expr::BinaryOp(519 el!(Expr::Num(2.0), 0, 1),520 Add,521 el!(522 Expr::Parened(el!(523 Expr::BinaryOp(524 el!(Expr::Num(2.0), 3, 4),525 Add,526 el!(527 Expr::BinaryOp(528 el!(Expr::Num(2.0), 5, 6),529 Mul,530 el!(Expr::Num(2.0), 7, 8),531 ),532 5,533 8534 ),535 ),536 3,537 8538 )),539 2,540 9541 ),542 ),543 0,544 9545 )546 );547 }548549 /// Comments should not affect parsing550 #[test]551 fn comments() {552 assert_eq!(553 parse!("2//comment\n+//comment\n3/*test*/*/*test*/4"),554 el!(555 Expr::BinaryOp(556 el!(Expr::Num(2.0), 0, 1),557 Add,558 el!(559 Expr::BinaryOp(560 el!(Expr::Num(3.0), 22, 23),561 Mul,562 el!(Expr::Num(4.0), 40, 41)563 ),564 22,565 41566 )567 ),568 0,569 41570 )571 );572 }573574 /// Comments should be able to be escaped575 #[test]576 fn comment_escaping() {577 assert_eq!(578 parse!("2/*\\*/+*/ - 22"),579 el!(580 Expr::BinaryOp(el!(Expr::Num(2.0), 0, 1), Sub, el!(Expr::Num(22.0), 12, 14)),581 0,582 14583 )584 );585 }586587 #[test]588 fn suffix() {589 // assert_eq!(parse!("std.test"), el!(Expr::Num(2.2)));590 // assert_eq!(parse!("std(2)"), el!(Expr::Num(2.2)));591 // assert_eq!(parse!("std.test(2)"), el!(Expr::Num(2.2)));592 // assert_eq!(parse!("a[b]"), el!(Expr::Num(2.2)))593 }594595 #[test]596 fn array_comp() {597 use Expr::*;598 /*599 `ArrComp(Apply(Index(Var("std") from "test.jsonnet":1-4, Var("deepJoin") from "test.jsonnet":5-13) from "test.jsonnet":1-13, ArgsDesc { unnamed: [Var("x") from "test.jsonnet":14-15], named: [] }, false) from "test.jsonnet":1-16, [ForSpec(ForSpecData("x", Var("arr") from "test.jsonnet":26-29))]) from "test.jsonnet":0-30`,600 `ArrComp(Apply(Index(Var("std") from "test.jsonnet":1-4, Str("deepJoin") from "test.jsonnet":5-13) from "test.jsonnet":1-13, ArgsDesc { unnamed: [Var("x") from "test.jsonnet":14-15], named: [] }, false) from "test.jsonnet":1-16, [ForSpec(ForSpecData("x", Var("arr") from "test.jsonnet":26-29))]) from "test.jsonnet":0-30`601 */602 assert_eq!(603 parse!("[std.deepJoin(x) for x in arr]"),604 el!(605 ArrComp(606 el!(607 Apply(608 el!(609 Index(610 el!(Var("std".into()), 1, 4),611 el!(Str("deepJoin".into()), 5, 13)612 ),613 1,614 13615 ),616 ArgsDesc::new(vec![el!(Var("x".into()), 14, 15)], vec![]),617 false,618 ),619 1,620 16621 ),622 vec![CompSpec::ForSpec(ForSpecData(623 "x".into(),624 el!(Var("arr".into()), 26, 29)625 ))]626 ),627 0,628 30629 ),630 )631 }632633 #[test]634 fn reserved() {635 use Expr::*;636 assert_eq!(parse!("null"), el!(Literal(LiteralType::Null), 0, 4));637 assert_eq!(parse!("nulla"), el!(Var("nulla".into()), 0, 5));638 }639640 #[test]641 fn multiple_args_buf() {642 parse!("a(b, null_fields)");643 }644645 #[test]646 fn infix_precedence() {647 use Expr::*;648 assert_eq!(649 parse!("!a && !b"),650 el!(651 BinaryOp(652 el!(UnaryOp(UnaryOpType::Not, el!(Var("a".into()), 1, 2)), 0, 2),653 And,654 el!(UnaryOp(UnaryOpType::Not, el!(Var("b".into()), 7, 8)), 6, 8)655 ),656 0,657 8658 )659 );660 }661662 #[test]663 fn infix_precedence_division() {664 use Expr::*;665 assert_eq!(666 parse!("!a / !b"),667 el!(668 BinaryOp(669 el!(UnaryOp(UnaryOpType::Not, el!(Var("a".into()), 1, 2)), 0, 2),670 Div,671 el!(UnaryOp(UnaryOpType::Not, el!(Var("b".into()), 6, 7)), 5, 7)672 ),673 0,674 7675 )676 );677 }678679 #[test]680 fn double_negation() {681 use Expr::*;682 assert_eq!(683 parse!("!!a"),684 el!(685 UnaryOp(686 UnaryOpType::Not,687 el!(UnaryOp(UnaryOpType::Not, el!(Var("a".into()), 2, 3)), 1, 3)688 ),689 0,690 3691 )692 )693 }694695 #[test]696 fn array_test_error() {697 parse!("[a for a in b if c for e in f]");698 // ^^^^ failed code699 }700701 #[test]702 fn missing_newline_between_comment_and_eof() {703 parse!(704 "{a:1}705706 //+213"707 );708 }709710 #[test]711 fn default_param_before_nondefault() {712 parse!("local x(foo = 'foo', bar) = null; null");713 }714715 #[test]716 fn can_parse_stdlib() {717 parse!(jrsonnet_stdlib::STDLIB_STR);718 }719720 #[test]721 fn add_location_info_to_all_sub_expressions() {722 use Expr::*;723724 let file_name = Source::new_virtual(Cow::Borrowed("<test>"));725 let expr = parse(726 "{} { local x = 1, x: x } + {}",727 &ParserSettings { file_name },728 )729 .unwrap();730 assert_eq!(731 expr,732 el!(733 BinaryOp(734 el!(735 ObjExtend(736 el!(Obj(ObjBody::MemberList(vec![])), 0, 2),737 ObjBody::MemberList(vec![738 Member::BindStmt(BindSpec::Field {739 into: Destruct::Full("x".into()),740 value: el!(Num(1.0), 15, 16)741 }),742 Member::Field(FieldMember {743 name: FieldName::Fixed("x".into()),744 plus: false,745 params: None,746 visibility: Visibility::Normal,747 value: el!(Var("x".into()), 21, 22),748 })749 ])750 ),751 0,752 24753 ),754 BinaryOpType::Add,755 el!(Obj(ObjBody::MemberList(vec![])), 27, 29),756 ),757 0,758 29759 ),760 );761 }762}crates/jrsonnet-stdlib/src/lib.rsdiffbeforeafterboth--- a/crates/jrsonnet-stdlib/src/lib.rs
+++ b/crates/jrsonnet-stdlib/src/lib.rs
@@ -8,7 +8,7 @@
use jrsonnet_evaluator::{
error::{Error::*, Result},
function::{builtin::Builtin, ArgLike, CallLocation, FuncVal, TlaArg},
- gc::TraceBox,
+ gc::{GcHashMap, TraceBox},
tb, throw_runtime,
typed::{Any, Either, Either2, Either4, VecVal, M1},
val::{equals, ArrValue},
@@ -201,6 +201,8 @@
pub ext_vars: HashMap<IStr, TlaArg>,
/// Used for `std.native`
pub ext_natives: HashMap<IStr, Cc<TraceBox<dyn Builtin>>>,
+ /// Helper to add globals without implementing custom ContextInitializer
+ pub globals: GcHashMap<IStr, Thunk<Val>>,
/// Used for `std.trace`
pub trace_printer: Box<dyn TracePrinter>,
}
@@ -210,6 +212,7 @@
Self {
ext_vars: Default::default(),
ext_natives: Default::default(),
+ globals: Default::default(),
trace_printer: Box::new(StdTracePrinter),
}
}
@@ -289,7 +292,17 @@
impl jrsonnet_evaluator::ContextInitializer for ContextInitializer {
#[cfg(not(feature = "legacy-this-file"))]
fn initialize(&self, _s: State, _source: Source) -> jrsonnet_evaluator::Context {
- self.context.clone()
+ let out = self.context.clone();
+ let globals = &self.settings().globals;
+ if globals.is_empty() {
+ return out;
+ }
+
+ let mut out = ContextBuilder::extend(out);
+ for (k, v) in globals.iter() {
+ out.bind(k.clone(), v.clone());
+ }
+ out.build()
}
#[cfg(feature = "legacy-this-file")]
fn initialize(&self, s: State, source: Source) -> jrsonnet_evaluator::Context {
@@ -316,6 +329,9 @@
"std".into(),
Thunk::evaluated(Val::Obj(stdlib_with_this_file)),
);
+ for (k, v) in &self.settings().globals {
+ context.bind(k.clone(), v.clone())
+ }
context.build()
}
unsafe fn as_any(&self) -> &dyn std::any::Any {
@@ -513,3 +529,25 @@
_ => throw_runtime!("both arguments should be of the same type"),
})
}
+
+pub trait StateExt {
+ /// This method was previously implemented in jrsonnet-evaluator itself
+ fn with_stdlib(&self);
+ fn add_global(&self, name: IStr, value: Thunk<Val>);
+}
+
+impl StateExt for State {
+ fn with_stdlib(&self) {
+ let initializer = ContextInitializer::new(self.clone());
+ self.settings_mut().context_initializer = Box::new(initializer)
+ }
+ fn add_global(&self, name: IStr, value: Thunk<Val>) {
+ // Safety:
+ unsafe { self.settings().context_initializer.as_any() }
+ .downcast_ref::<ContextInitializer>()
+ .expect("not standard context initializer")
+ .settings_mut()
+ .globals
+ .insert(name, value);
+ }
+}
tests/Cargo.tomldiffbeforeafterboth--- /dev/null
+++ b/tests/Cargo.toml
@@ -0,0 +1,10 @@
+[package]
+name = "tests"
+version = "0.1.0"
+edition = "2021"
+
+[dependencies]
+jrsonnet-evaluator = { path = "../crates/jrsonnet-evaluator" }
+jrsonnet-gcmodule = "0.3.4"
+jrsonnet-stdlib = { path = "../crates/jrsonnet-stdlib" }
+serde = "1.0.142"
tests/golden/array_comp.jsonnetdiffbeforeafterboth--- /dev/null
+++ b/tests/golden/array_comp.jsonnet
@@ -0,0 +1 @@
+[[a, b] for a in [1, 2, 3] for b in [4, 5, 6]]
tests/golden/array_comp.jsonnet.goldendiffbeforeafterboth--- /dev/null
+++ b/tests/golden/array_comp.jsonnet.golden
@@ -0,0 +1,38 @@
+[
+ [
+ 1,
+ 4
+ ],
+ [
+ 1,
+ 5
+ ],
+ [
+ 1,
+ 6
+ ],
+ [
+ 2,
+ 4
+ ],
+ [
+ 2,
+ 5
+ ],
+ [
+ 2,
+ 6
+ ],
+ [
+ 3,
+ 4
+ ],
+ [
+ 3,
+ 5
+ ],
+ [
+ 3,
+ 6
+ ]
+]
\ No newline at end of file
tests/golden/builtin_json.jsonnetdiffbeforeafterboth--- /dev/null
+++ b/tests/golden/builtin_json.jsonnet
@@ -0,0 +1 @@
+std.manifestJsonEx({ a: 3, b: 4, c: 6 }, '')
tests/golden/builtin_json.jsonnet.goldendiffbeforeafterboth--- /dev/null
+++ b/tests/golden/builtin_json.jsonnet.golden
@@ -0,0 +1 @@
+"{\n\"a\": 3,\n\"b\": 4,\n\"c\": 6\n}"
\ No newline at end of file
tests/golden/builtin_json_minified.jsonnetdiffbeforeafterboth--- /dev/null
+++ b/tests/golden/builtin_json_minified.jsonnet
@@ -0,0 +1 @@
+std.manifestJsonMinified({ a: 3, b: 4, c: 6 })
tests/golden/builtin_json_minified.jsonnet.goldendiffbeforeafterboth--- /dev/null
+++ b/tests/golden/builtin_json_minified.jsonnet.golden
@@ -0,0 +1 @@
+"{\"a\":3,\"b\":4,\"c\":6}"
\ No newline at end of file
tests/golden/builtin_parseJson.jsonnetdiffbeforeafterboth--- /dev/null
+++ b/tests/golden/builtin_parseJson.jsonnet
@@ -0,0 +1 @@
+std.parseJson('{"a": -1,"b": 1,"c": 3.141,"d": []}')
tests/golden/builtin_parseJson.jsonnet.goldendiffbeforeafterboth--- /dev/null
+++ b/tests/golden/builtin_parseJson.jsonnet.golden
@@ -0,0 +1,6 @@
+{
+ "a": -1,
+ "b": 1,
+ "c": 3.141,
+ "d": [ ]
+}
\ No newline at end of file
tests/golden/issue23.jsonnetdiffbeforeafterboth--- /dev/null
+++ b/tests/golden/issue23.jsonnet
@@ -0,0 +1 @@
+import 'issue23.jsonnet'
tests/golden/issue23.jsonnet.goldendiffbeforeafterboth--- /dev/null
+++ b/tests/golden/issue23.jsonnet.golden
@@ -0,0 +1,2 @@
+infinite recursion detected
+ issue23.jsonnet:1:1-26: import "issue23.jsonnet"
\ No newline at end of file
tests/golden/issue40.jsonnetdiffbeforeafterboth--- /dev/null
+++ b/tests/golden/issue40.jsonnet
@@ -0,0 +1,9 @@
+local conf = {
+ n: '',
+};
+
+local result = conf {
+ assert std.isNumber(self.n) : 'is number',
+};
+
+std.manifestJsonEx(result, '')
tests/golden/issue40.jsonnet.goldendiffbeforeafterboth--- /dev/null
+++ b/tests/golden/issue40.jsonnet.golden
@@ -0,0 +1,3 @@
+assert failed: is number
+ issue40.jsonnet:6:10-31: assertion failure
+ issue40.jsonnet:9:1-32: function <builtin_manifest_json_ex> call
\ No newline at end of file
tests/golden/missing_binding.jsonnetdiffbeforeafterboth--- /dev/null
+++ b/tests/golden/missing_binding.jsonnet
@@ -0,0 +1 @@
+sta
tests/golden/missing_binding.jsonnet.goldendiffbeforeafterboth--- /dev/null
+++ b/tests/golden/missing_binding.jsonnet.golden
@@ -0,0 +1,3 @@
+variable is not defined: sta
+There is variable with similar name present: std
+ missing_binding.jsonnet:1:1-5: variable <sta> access
\ No newline at end of file
tests/golden/object_comp.jsonnetdiffbeforeafterboth--- /dev/null
+++ b/tests/golden/object_comp.jsonnet
@@ -0,0 +1 @@
+{ 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 }
tests/golden/object_comp.jsonnet.goldendiffbeforeafterboth--- /dev/null
+++ b/tests/golden/object_comp.jsonnet.golden
@@ -0,0 +1,9 @@
+{
+ "h1_2": "0a",
+ "h1_3": "0a",
+ "h1_4": "0a",
+ "h2_3": "a1",
+ "h2_4": "a1",
+ "h3_2": "0a",
+ "h3_4": "a1"
+}
\ No newline at end of file
tests/golden/test_assertThrow.jsonnetdiffbeforeafterboth--- /dev/null
+++ b/tests/golden/test_assertThrow.jsonnet
@@ -0,0 +1,2 @@
+// Test that test.assertThrow will return error, if body is not errored
+test.assertThrow(1, '1')
tests/golden/test_assertThrow.jsonnet.goldendiffbeforeafterboth--- /dev/null
+++ b/tests/golden/test_assertThrow.jsonnet.golden
@@ -0,0 +1,2 @@
+runtime error: expected argument to throw on evaluation, but it returned instead
+ test_assertThrow.jsonnet:2:1-26: function <assert_throw> call
\ No newline at end of file
tests/src/lib.rsdiffbeforeafterboth--- /dev/null
+++ b/tests/src/lib.rs
@@ -0,0 +1,14 @@
+pub fn add(left: usize, right: usize) -> usize {
+ left + right
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ #[test]
+ fn it_works() {
+ let result = add(2, 2);
+ assert_eq!(result, 4);
+ }
+}
tests/suite/builtin_ascii.jsonnetdiffbeforeafterboth--- /dev/null
+++ b/tests/suite/builtin_ascii.jsonnet
@@ -0,0 +1,3 @@
+std.assertEqual(std.asciiUpper('aBc😀'), 'ABC😀') &&
+std.assertEqual(std.asciiLower('aBc😀'), 'abc😀') &&
+true
tests/suite/builtin_base64.jsonnetdiffbeforeafterboth--- /dev/null
+++ b/tests/suite/builtin_base64.jsonnet
@@ -0,0 +1,2 @@
+std.assertEqual(std.base64('test'), 'dGVzdA==') &&
+true
tests/suite/builtin_chars.jsonnetdiffbeforeafterboth--- /dev/null
+++ b/tests/suite/builtin_chars.jsonnet
@@ -0,0 +1,3 @@
+local c = '😎';
+std.assertEqual({ c: std.codepoint(c), l: std.length(c) }, { c: 128526, l: 1 }) &&
+true
tests/suite/builtin_constant.jsonnetdiffbeforeafterboth--- /dev/null
+++ b/tests/suite/builtin_constant.jsonnet
@@ -0,0 +1,3 @@
+local std2 = std; local std = std2 { primitiveEquals(a, b):: false };
+// In jsonnet, this expression was failing because of being desugared to std.primitiveEquals(1, 1)
+std.assertEqual(1 == 1, true)
tests/suite/builtin_count.jsonnetdiffbeforeafterboth--- /dev/null
+++ b/tests/suite/builtin_count.jsonnet
@@ -0,0 +1,4 @@
+std.assertEqual(std.count([], ''), 0) &&
+std.assertEqual(std.count(['a', 'b', 'a'], 'd'), 0) &&
+std.assertEqual(std.count(['a', 'b', 'a'], 'a'), 2) &&
+true
tests/suite/builtin_join.jsonnetdiffbeforeafterboth--- /dev/null
+++ b/tests/suite/builtin_join.jsonnet
@@ -0,0 +1,4 @@
+std.assertEqual(std.join([0, 0], [[1, 2], [3, 4], [5, 6]]), [1, 2, 0, 0, 3, 4, 0, 0, 5, 6]) &&
+std.assertEqual(std.join(',', ['1', '2', '3', '4']), '1,2,3,4') &&
+std.assertEqual(std.join(',', ['1', null, '2', null, '3']), '1,2,3') &&
+true
tests/suite/builtin_member.jsonnetdiffbeforeafterboth--- /dev/null
+++ b/tests/suite/builtin_member.jsonnet
@@ -0,0 +1,7 @@
+!std.member('', '') &&
+std.member('abc', 'a') &&
+!std.member('abc', 'd') &&
+!std.member([], '') &&
+std.member(['a', 'b', 'c'], 'a') &&
+!std.member(['a', 'b', 'c'], 'd') &&
+true
tests/suite/function_args.jsonnetdiffbeforeafterboth--- /dev/null
+++ b/tests/suite/function_args.jsonnet
@@ -0,0 +1,3 @@
+std.assertEqual(local a = function(b, c=2) b + c; a(2), 4) &&
+std.assertEqual(local a = function(b, c='Dear') b + c + d, d = 'World'; a('Hello'), 'HelloDearWorld') &&
+true
tests/suite/function_context.jsonnetdiffbeforeafterboth--- /dev/null
+++ b/tests/suite/function_context.jsonnet
@@ -0,0 +1,10 @@
+local k = {
+ t(name=self.h): [self.h, name],
+ h: 3,
+};
+local f = {
+ t: k.t(),
+ h: 4,
+};
+std.assertEqual(f.t[0], f.t[1]) &&
+true
tests/suite/function_lazy_args.jsonnetdiffbeforeafterboth--- /dev/null
+++ b/tests/suite/function_lazy_args.jsonnet
@@ -0,0 +1,5 @@
+local fun(a) = 2;
+std.assertEqual(fun(error '3'), 2) &&
+// But in tailstrict mode arguments are evaluated eagerly
+test.assertThrow(fun(error '3') tailstrict, 'runtime error: 3') &&
+true
tests/suite/local.jsonnetdiffbeforeafterboth--- /dev/null
+++ b/tests/suite/local.jsonnet
@@ -0,0 +1,4 @@
+std.assertEqual(local a = 2; local b = 3; a + b, 5) &&
+std.assertEqual(local a = 1, b = a + 1; a + b, 3) &&
+std.assertEqual(local a = 1; local a = 2; a, 2) &&
+true
tests/suite/math.jsonnetdiffbeforeafterboth--- /dev/null
+++ b/tests/suite/math.jsonnet
@@ -0,0 +1,3 @@
+std.assertEqual(2 + 2 * 2, 6) &&
+std.assertEqual(3 + (2 + 2 * 2), 9) &&
+true
tests/suite/object_assertion.jsonnetdiffbeforeafterboth--- /dev/null
+++ b/tests/suite/object_assertion.jsonnet
@@ -0,0 +1,3 @@
+std.assertEqual({ assert 'a' in self : 'missing a' } + { a: 2 }, { a: 2 }) &&
+test.assertThrow({ assert 'a' in self : 'missing a', b: 1 }.b, 'assert failed: missing a') &&
+true
tests/suite/object_comp_self.jsonnetdiffbeforeafterboth--- /dev/null
+++ b/tests/suite/object_comp_self.jsonnet
@@ -0,0 +1,8 @@
+std.assertEqual(std.objectFields({
+ a: {
+ [name]: name
+ for name in std.objectFields(self)
+ },
+ b: 2,
+ c: 3,
+}.a), ['a', 'b', 'c'])
tests/suite/object_context.jsonnetdiffbeforeafterboth--- /dev/null
+++ b/tests/suite/object_context.jsonnet
@@ -0,0 +1,13 @@
+// `self` assigned to `me` was lost when being
+// referenced from field
+std.assertEqual({
+ local me = self,
+ a: 3,
+ b: me.a,
+}.b, 3) &&
+std.assertEqual({
+ local me = self,
+ a: 3,
+ b(): me.a,
+}.b(), 3) &&
+true
tests/suite/object_fields.jsonnetdiffbeforeafterboth--- /dev/null
+++ b/tests/suite/object_fields.jsonnet
@@ -0,0 +1,4 @@
+local a = 'a', b = null;
+std.assertEqual({ [a]: 2 }, { a: 2 }) &&
+std.assertEqual({ [b]: 2 }, {}) &&
+true
tests/suite/object_inheritance.jsonnetdiffbeforeafterboth--- /dev/null
+++ b/tests/suite/object_inheritance.jsonnet
@@ -0,0 +1,17 @@
+std.assertEqual({ a: self.b } + { b: 3 }, { a: 3, b: 3 }) &&
+std.assertEqual(
+ {
+ name: 'Alice',
+ welcome: 'Hello ' + self.name + '!',
+ },
+ { name: 'Alice', welcome: 'Hello Alice!' },
+) &&
+std.assertEqual(
+ {
+ name: 'Alice',
+ welcome: 'Hello ' + self.name + '!',
+ } + {
+ name: 'Bob',
+ }, { name: 'Bob', welcome: 'Hello Bob!' }
+) &&
+true
tests/suite/object_locals.jsonnetdiffbeforeafterboth--- /dev/null
+++ b/tests/suite/object_locals.jsonnet
@@ -0,0 +1,4 @@
+std.assertEqual({ local a = 3, b: a }, { b: 3 }) &&
+std.assertEqual({ local a = 3, local c = a, b: c }, { b: 3 }) &&
+std.assertEqual({ local a = function(b) { [b]: 4 }, test: a('test') }, { test: { test: 4 } }) &&
+true
tests/suite/object_super_standalone.jsonnetdiffbeforeafterboth--- /dev/null
+++ b/tests/suite/object_super_standalone.jsonnet
@@ -0,0 +1,11 @@
+local obj = {
+ a: 1,
+ b: 2,
+ c: 3,
+};
+local test = obj + {
+ fields: std.objectFields(super),
+ d: 5,
+};
+std.assertEqual(test.fields, ['a', 'b', 'c']) &&
+true
tests/suite/sjsonnet_issue_127.jsonnetdiffbeforeafterboth--- /dev/null
+++ b/tests/suite/sjsonnet_issue_127.jsonnet
@@ -0,0 +1,6 @@
+local myFunc = function(a)
+ if (a) then "a" else "b";
+
+local b = "aaa";
+
+std.assertEqual(myFunc(b == [] || b == ['e']), "b")
tests/suite/string_concat.jsonnetdiffbeforeafterboth--- /dev/null
+++ b/tests/suite/string_concat.jsonnet
@@ -0,0 +1,4 @@
+std.assertEqual('Hello' + 'World', 'HelloWorld') &&
+std.assertEqual('Hello' * 3, 'HelloHelloHello') &&
+std.assertEqual('Hello' + 'World' * 3, 'HelloWorldWorldWorld') &&
+true
tests/tests/as_native.rsdiffbeforeafterboth--- /dev/null
+++ b/tests/tests/as_native.rs
@@ -0,0 +1,20 @@
+use jrsonnet_evaluator::{error::Result, State};
+use jrsonnet_stdlib::StateExt;
+
+mod common;
+
+#[test]
+fn as_native() -> Result<()> {
+ let s = State::default();
+ s.with_stdlib();
+
+ let val = s.evaluate_snippet("snip".to_owned(), r#"function(a, b) a + b"#)?;
+ let func = val.as_func().expect("this is function");
+
+ let native = func.into_native::<((u32, u32), u32)>();
+
+ ensure_eq!(native(s.clone(), 1, 2)?, 3);
+ ensure_eq!(native(s, 3, 4)?, 7);
+
+ Ok(())
+}
tests/tests/builtin.rsdiffbeforeafterboth--- /dev/null
+++ b/tests/tests/builtin.rs
@@ -0,0 +1,94 @@
+mod common;
+
+use jrsonnet_evaluator::{
+ error::Result,
+ function::{builtin, builtin::Builtin, CallLocation, FuncVal},
+ tb,
+ typed::Typed,
+ Context, State, Thunk, Val,
+};
+use jrsonnet_gcmodule::Cc;
+use jrsonnet_stdlib::StateExt;
+
+#[builtin]
+fn a() -> Result<u32> {
+ Ok(1)
+}
+
+#[test]
+fn basic_function() -> Result<()> {
+ let s = State::default();
+ let a: a = a {};
+ let v = u32::from_untyped(
+ a.call(s.clone(), Context::new(), CallLocation::native(), &())?,
+ s,
+ )?;
+
+ ensure_eq!(v, 1);
+ Ok(())
+}
+
+#[builtin]
+fn native_add(a: u32, b: u32) -> Result<u32> {
+ Ok(a + b)
+}
+
+#[test]
+fn call_from_code() -> Result<()> {
+ let s = State::default();
+ s.with_stdlib();
+ s.add_global(
+ "nativeAdd".into(),
+ Thunk::evaluated(Val::Func(FuncVal::StaticBuiltin(native_add::INST))),
+ );
+
+ let v = s.evaluate_snippet(
+ "snip".to_owned(),
+ "
+ assert nativeAdd(1, 2) == 3;
+ assert nativeAdd(100, 200) == 300;
+ null
+ ",
+ )?;
+ ensure_val_eq!(s, v, Val::Null);
+ Ok(())
+}
+
+#[builtin(fields(
+ a: u32
+))]
+fn curried_add(this: &curried_add, b: u32) -> Result<u32> {
+ Ok(this.a + b)
+}
+
+#[builtin]
+fn curry_add(a: u32) -> Result<FuncVal> {
+ Ok(FuncVal::Builtin(Cc::new(tb!(curried_add { a }))))
+}
+
+#[test]
+fn nonstatic_builtin() -> Result<()> {
+ let s = State::default();
+ s.with_stdlib();
+ s.add_global(
+ "curryAdd".into(),
+ Thunk::evaluated(Val::Func(FuncVal::StaticBuiltin(curry_add::INST))),
+ );
+
+ let v = s.evaluate_snippet(
+ "snip".to_owned(),
+ "
+ local a = curryAdd(1);
+ local b = curryAdd(4);
+
+ assert a(2) == 3;
+ assert a(200) == 201;
+
+ assert b(2) == 6;
+ assert b(200) == 204;
+ null
+ ",
+ )?;
+ ensure_val_eq!(s, v, Val::Null);
+ Ok(())
+}
tests/tests/common.rsdiffbeforeafterboth--- /dev/null
+++ b/tests/tests/common.rs
@@ -0,0 +1,77 @@
+use jrsonnet_evaluator::{
+ error::Result,
+ function::{builtin, FuncVal},
+ throw_runtime, ObjValueBuilder, State, Thunk, Val,
+};
+use jrsonnet_stdlib::StateExt;
+
+#[macro_export]
+macro_rules! ensure_eq {
+ ($a:expr, $b:expr $(,)?) => {{
+ let a = &$a;
+ let b = &$b;
+ if a != b {
+ ::jrsonnet_evaluator::throw_runtime!("assertion failed: a != b\na={:#?}\nb={:#?}", a, b)
+ }
+ }};
+}
+
+#[macro_export]
+macro_rules! ensure {
+ ($v:expr $(,)?) => {
+ if !$v {
+ ::jrsonnet_evaluator::throw_runtime!("assertion failed: {}", stringify!($v))
+ }
+ };
+}
+
+#[macro_export]
+macro_rules! ensure_val_eq {
+ ($s:expr, $a:expr, $b:expr) => {{
+ if !::jrsonnet_evaluator::val::equals($s.clone(), &$a.clone(), &$b.clone())? {
+ ::jrsonnet_evaluator::throw_runtime!(
+ "assertion failed: a != b\na={:#?}\nb={:#?}",
+ $a.to_json(
+ $s.clone(),
+ 2,
+ #[cfg(feature = "exp-preserve-order")]
+ false
+ )?,
+ $b.to_json(
+ $s.clone(),
+ 2,
+ #[cfg(feature = "exp-preserve-order")]
+ false
+ )?,
+ )
+ }
+ }};
+}
+
+#[builtin]
+fn assert_throw(s: State, lazy: Thunk<Val>, message: String) -> Result<bool> {
+ match lazy.evaluate(s) {
+ Ok(_) => {
+ throw_runtime!("expected argument to throw on evaluation, but it returned instead")
+ }
+ Err(e) => {
+ let error = format!("{}", e.error());
+ ensure_eq!(message, error);
+ }
+ }
+ Ok(true)
+}
+
+#[allow(dead_code)]
+pub fn with_test(s: &State) {
+ let mut bobj = ObjValueBuilder::new();
+ bobj.member("assertThrow".into())
+ .hide()
+ .value(
+ s.clone(),
+ Val::Func(FuncVal::StaticBuiltin(assert_throw::INST)),
+ )
+ .expect("no error");
+
+ s.add_global("test".into(), Thunk::evaluated(Val::Obj(bobj.build())))
+}
tests/tests/golden.rsdiffbeforeafterboth--- /dev/null
+++ b/tests/tests/golden.rs
@@ -0,0 +1,70 @@
+use std::{
+ fs, io,
+ path::{Path, PathBuf},
+};
+
+use jrsonnet_evaluator::{
+ trace::{CompactFormat, PathResolver},
+ FileImportResolver, State,
+};
+use jrsonnet_stdlib::StateExt;
+
+mod common;
+
+fn run(root: &Path, file: &Path) -> String {
+ let s = State::default();
+ s.set_trace_format(Box::new(CompactFormat {
+ resolver: PathResolver::Relative(root.to_owned()),
+ padding: 3,
+ }));
+ s.with_stdlib();
+ common::with_test(&s);
+ s.set_import_resolver(Box::new(FileImportResolver::default()));
+
+ let v = match s.import(root, &file.display().to_string()) {
+ Ok(v) => v,
+ Err(e) => return s.stringify_err(&e),
+ };
+ match v.to_json(
+ s.clone(),
+ 3,
+ #[cfg(feature = "exp-preserve-order")]
+ false,
+ ) {
+ Ok(v) => v.to_string(),
+ Err(e) => s.stringify_err(&e),
+ }
+}
+
+#[test]
+fn test() -> io::Result<()> {
+ let mut root = PathBuf::from(env!("CARGO_MANIFEST_DIR"));
+ root.push("golden");
+
+ for entry in fs::read_dir(&root)? {
+ let entry = entry?;
+ if !entry.path().extension().map_or(false, |e| e == "jsonnet") {
+ continue;
+ }
+
+ let result = run(&root, &entry.path());
+
+ let mut golden_path = entry.path();
+ golden_path.set_extension("jsonnet.golden");
+
+ if !golden_path.exists() {
+ fs::write(golden_path, &result)?;
+ } else {
+ let golden = fs::read_to_string(golden_path)?;
+
+ assert_eq!(
+ result,
+ golden,
+ "golden didn't match for {}",
+ entry.path().display()
+ )
+ }
+ }
+
+ Ok(())
+}
tests/tests/sanity.rsdiffbeforeafterboth--- /dev/null
+++ b/tests/tests/sanity.rs
@@ -0,0 +1,42 @@
+use jrsonnet_evaluator::{error::Result, throw_runtime, State, Val};
+use jrsonnet_stdlib::StateExt;
+
+mod common;
+
+#[test]
+fn assert_positive() -> Result<()> {
+ let s = State::default();
+ s.with_stdlib();
+
+ let v = s.evaluate_snippet("snip".to_owned(), "assert 1 == 1: 'fail'; null")?;
+ ensure_val_eq!(s, v, Val::Null);
+ let v = s.evaluate_snippet("snip".to_owned(), "std.assertEqual(1, 1)")?;
+ ensure_val_eq!(s, v, Val::Bool(true));
+
+ Ok(())
+}
+
+#[test]
+fn assert_negative() -> Result<()> {
+ let s = State::default();
+ s.with_stdlib();
+
+ {
+ let e = match s.evaluate_snippet("snip".to_owned(), "assert 1 == 2: 'fail'; null") {
+ Ok(_) => throw_runtime!("assertion should fail"),
+ Err(e) => e,
+ };
+ let e = s.stringify_err(&e);
+ ensure!(e.starts_with("assert failed: fail\n"));
+ }
+ {
+ let e = match s.evaluate_snippet("snip".to_owned(), "std.assertEqual(1, 2)") {
+ Ok(_) => throw_runtime!("assertion should fail"),
+ Err(e) => e,
+ };
+ let e = s.stringify_err(&e);
+ ensure!(e.starts_with("runtime error: Assertion failed. 1 != 2"))
+ }
+
+ Ok(())
+}
tests/tests/suite.rsdiffbeforeafterboth--- /dev/null
+++ b/tests/tests/suite.rs
@@ -0,0 +1,47 @@
+use std::{
+ fs, io,
+ path::{Path, PathBuf},
+};
+
+use jrsonnet_evaluator::{
+ trace::{CompactFormat, PathResolver},
+ FileImportResolver, State, Val,
+};
+use jrsonnet_stdlib::StateExt;
+
+mod common;
+
+fn run(root: &Path, file: &Path) {
+ let s = State::default();
+ s.set_trace_format(Box::new(CompactFormat {
+ resolver: PathResolver::Relative(root.to_owned()),
+ padding: 3,
+ }));
+ s.with_stdlib();
+ common::with_test(&s);
+ s.set_import_resolver(Box::new(FileImportResolver::default()));
+
+ match s.import(root, &file.display().to_string()) {
+ Ok(Val::Bool(true)) => {}
+ Ok(Val::Bool(false)) => panic!("test {} returned false", file.display()),
+ Ok(_) => panic!("test {} returned wrong type as result", file.display()),
+ Err(e) => panic!("test {} failed:\n{}", file.display(), s.stringify_err(&e)),
+ };
+}
+
+#[test]
+fn test() -> io::Result<()> {
+ let mut root = PathBuf::from(env!("CARGO_MANIFEST_DIR"));
+ root.push("suite");
+
+ for entry in fs::read_dir(&root)? {
+ let entry = entry?;
+ if !entry.path().extension().map_or(false, |e| e == "jsonnet") {
+ continue;
+ }
+
+ run(&root, &entry.path());
+ }
+
+ Ok(())
+}
tests/tests/typed_obj.rsdiffbeforeafterboth--- /dev/null
+++ b/tests/tests/typed_obj.rs
@@ -0,0 +1,189 @@
+mod common;
+
+use std::fmt::Debug;
+
+use jrsonnet_evaluator::{error::Result, typed::Typed, State};
+use jrsonnet_stdlib::StateExt;
+
+#[derive(Clone, Typed, PartialEq, Debug)]
+struct A {
+ a: u32,
+ b: u16,
+}
+
+fn test_roundtrip<T: Typed + PartialEq + Debug + Clone>(value: T, s: State) -> Result<()> {
+ let untyped = T::into_untyped(value.clone(), s.clone())?;
+ let value2 = T::from_untyped(untyped.clone(), s.clone())?;
+ ensure_eq!(value, value2);
+ let untyped2 = T::into_untyped(value2, s.clone())?;
+ ensure_val_eq!(s, untyped, untyped2);
+
+ Ok(())
+}
+
+#[test]
+fn simple_object() -> Result<()> {
+ let s = State::default();
+ s.with_stdlib();
+ let a = A::from_untyped(
+ s.evaluate_snippet("snip".to_owned(), "{a: 1, b: 2}")?,
+ s.clone(),
+ )?;
+ ensure_eq!(a, A { a: 1, b: 2 });
+ test_roundtrip(a, s)?;
+ Ok(())
+}
+
+#[derive(Clone, Typed, PartialEq, Debug)]
+struct B {
+ a: u32,
+ #[typed(rename = "c")]
+ b: u16,
+}
+
+#[test]
+fn renamed_field() -> Result<()> {
+ let s = State::default();
+ s.with_stdlib();
+ let b = B::from_untyped(
+ s.evaluate_snippet("snip".to_owned(), "{a: 1, c: 2}")?,
+ s.clone(),
+ )?;
+ ensure_eq!(b, B { a: 1, b: 2 });
+ ensure_eq!(
+ &B::into_untyped(b.clone(), s.clone())?.to_string(s.clone())? as &str,
+ r#"{"a": 1, "c": 2}"#,
+ );
+ test_roundtrip(b, s)?;
+ Ok(())
+}
+
+#[derive(Clone, Typed, PartialEq, Debug)]
+struct ObjectKind {
+ #[typed(rename = "apiVersion")]
+ api_version: String,
+ #[typed(rename = "kind")]
+ kind: String,
+}
+
+#[derive(Clone, Typed, PartialEq, Debug)]
+struct Object {
+ #[typed(flatten)]
+ kind: ObjectKind,
+ b: u16,
+}
+
+#[test]
+fn flattened_object() -> Result<()> {
+ let s = State::default();
+ s.with_stdlib();
+ let obj = Object::from_untyped(
+ s.evaluate_snippet("snip".to_owned(), "{apiVersion: 'ver', kind: 'kind', b: 2}")?,
+ s.clone(),
+ )?;
+ ensure_eq!(
+ obj,
+ Object {
+ kind: ObjectKind {
+ api_version: "ver".into(),
+ kind: "kind".into(),
+ },
+ b: 2
+ }
+ );
+ ensure_eq!(
+ &Object::into_untyped(obj.clone(), s.clone())?.to_string(s.clone())? as &str,
+ r#"{"apiVersion": "ver", "b": 2, "kind": "kind"}"#,
+ );
+ test_roundtrip(obj, s)?;
+ Ok(())
+}
+
+#[derive(Clone, Typed, PartialEq, Debug)]
+struct C {
+ a: Option<u32>,
+ b: u16,
+}
+
+#[test]
+fn optional_field_some() -> Result<()> {
+ let s = State::default();
+ s.with_stdlib();
+ let c = C::from_untyped(
+ s.evaluate_snippet("snip".to_owned(), "{a: 1, b: 2}")?,
+ s.clone(),
+ )?;
+ ensure_eq!(c, C { a: Some(1), b: 2 });
+ ensure_eq!(
+ &C::into_untyped(c.clone(), s.clone())?.to_string(s.clone())? as &str,
+ r#"{"a": 1, "b": 2}"#,
+ );
+ test_roundtrip(c, s)?;
+ Ok(())
+}
+
+#[test]
+fn optional_field_none() -> Result<()> {
+ let s = State::default();
+ s.with_stdlib();
+ let c = C::from_untyped(s.evaluate_snippet("snip".to_owned(), "{b: 2}")?, s.clone())?;
+ ensure_eq!(c, C { a: None, b: 2 });
+ ensure_eq!(
+ &C::into_untyped(c.clone(), s.clone())?.to_string(s.clone())? as &str,
+ r#"{"b": 2}"#,
+ );
+ test_roundtrip(c, s)?;
+ Ok(())
+}
+
+#[derive(Clone, Typed, PartialEq, Debug)]
+struct D {
+ #[typed(flatten(ok))]
+ e: Option<E>,
+ b: u16,
+}
+
+#[derive(Clone, Typed, PartialEq, Debug)]
+struct E {
+ v: u32,
+}
+
+#[test]
+fn flatten_optional_some() -> Result<()> {
+ let s = State::default();
+ s.with_stdlib();
+ let d = D::from_untyped(
+ s.evaluate_snippet("snip".to_owned(), "{b: 2, v:1}")?,
+ s.clone(),
+ )?;
+ ensure_eq!(
+ d,
+ D {
+ e: Some(E { v: 1 }),
+ b: 2
+ }
+ );
+ ensure_eq!(
+ &D::into_untyped(d.clone(), s.clone())?.to_string(s.clone())? as &str,
+ r#"{"b": 2, "v": 1}"#,
+ );
+ test_roundtrip(d, s)?;
+ Ok(())
+}
+
+#[test]
+fn flatten_optional_none() -> Result<()> {
+ let s = State::default();
+ s.with_stdlib();
+ let d = D::from_untyped(
+ s.evaluate_snippet("snip".to_owned(), "{b: 2, v: '1'}")?,
+ s.clone(),
+ )?;
+ ensure_eq!(d, D { e: None, b: 2 });
+ ensure_eq!(
+ &D::into_untyped(d.clone(), s.clone())?.to_string(s.clone())? as &str,
+ r#"{"b": 2}"#,
+ );
+ test_roundtrip(d, s)?;
+ Ok(())
+}