use datex_core::{
compiler::{CompileOptions, compile_script},
core_compiler::core_compilation_context::DXBWithSharedValues,
decompiler::{
DecompileOptions, FormattingMode, FormattingOptions,
dxb_to_source_code::dxb_to_source_code,
},
runtime::{
Runtime,
execution::{
ExecutionInput, ExecutionOptions, execute_dxb_sync,
execution_input::ExecutionCallerMetadata,
},
},
traits::structural_eq::assert_structural_eq,
values::{
core_value::CoreValue,
core_values::{
decimal::Decimal, integer::Integer, list::List, map::Map,
},
value::Value,
value_container::ValueContainer,
},
};
use indexmap::IndexMap;
use itertools::Itertools;
use json_syntax::Parse;
use std::path::PathBuf;
fn json_value_to_datex_value(json: &json_syntax::Value) -> Value {
match json {
json_syntax::Value::Null => Value::null(),
json_syntax::Value::String(s) => {
Value::from(CoreValue::Text(s.to_string().into()))
}
json_syntax::Value::Number(n) => {
let num_str = n.as_str();
let is_integer = num_str
.chars()
.all(|c| c.is_ascii_digit() || c == '+' || c == '-');
if is_integer {
Value::from(
Integer::try_from_string(num_str).unwrap(), )
} else {
Value::from(Decimal::try_from_string(num_str).unwrap())
}
}
json_syntax::Value::Boolean(b) => Value::from(*b),
json_syntax::Value::Array(arr) => {
let mut vec = List::default();
for value in arr {
vec.push(json_value_to_datex_value(value));
}
Value::from(vec)
}
json_syntax::Value::Object(obj) => {
let mut map = IndexMap::default();
for entry in obj {
map.insert(
entry.key.to_string(),
ValueContainer::from(json_value_to_datex_value(
&entry.value.clone(),
)),
);
}
Value::from(Map::from(map))
}
}
}
fn compare_datex_result_with_json(json_string: &str) {
let runtime = Runtime::stub();
let json_value = json_syntax::Value::parse_str(json_string).unwrap().0;
let (dxb, _) =
compile_script(json_string, CompileOptions::default(), runtime.clone())
.unwrap();
let exec_input = ExecutionInput::new(
DXBWithSharedValues::new(dxb, vec![]),
ExecutionCallerMetadata::local_default(),
ExecutionOptions {
verbose: false,
..ExecutionOptions::default()
},
runtime,
);
let datex_value = execute_dxb_sync(exec_input).unwrap().unwrap();
let json_value_converted = json_value_to_datex_value(&json_value);
println!(" JSON Value: {json_value}");
println!(" DATEX Value: {datex_value}",);
println!(" Converted JSON Value: {json_value_converted}",);
let collapsed = datex_value.collapsed_value();
assert_structural_eq!(json_value_converted, *collapsed.borrow());
}
fn get_datex_decompiled_from_json(json_string: &str) -> String {
let runtime = Runtime::stub();
let (dxb, _) =
compile_script(json_string, CompileOptions::default(), runtime)
.unwrap();
let decompiled = dxb_to_source_code(
&dxb,
DecompileOptions {
formatting_options: FormattingOptions {
json_compat: true,
mode: FormattingMode::pretty(),
..FormattingOptions::default()
},
..DecompileOptions::default()
},
)
.unwrap();
let parsed_json = json_syntax::Value::parse_str(&decompiled);
if parsed_json.is_err() {
panic!(
"Decompiled JSON is not valid: {decompiled}, error: {:?}",
parsed_json.unwrap_err()
);
}
decompiled
}
fn compare_datex_result_with_expected(
json_string: &str,
expected: &str,
path: PathBuf,
) {
let datex_decompiled = get_datex_decompiled_from_json(json_string);
assert_eq!(
normalize_newlines(&datex_decompiled),
normalize_newlines(expected),
"Decompiled output does not match expected output for file: {}",
path.display()
);
}
gen fn iterate_test_cases() -> (PathBuf, PathBuf) {
let test_dir = std::path::Path::new("tests/json/test_cases");
for entry in std::fs::read_dir(test_dir)
.unwrap()
.map(|e| e.unwrap())
.sorted_by_key(|e| e.path())
{
if entry.file_type().unwrap().is_file()
&& entry.path().extension().unwrap() == "json"
{
let input_path = entry.path();
let output_path =
std::path::PathBuf::from("tests/json/expected_results")
.join(entry.file_name());
yield (input_path, output_path);
}
}
}
#[test]
fn basic_json() {
compare_datex_result_with_json("1");
compare_datex_result_with_json("-42");
compare_datex_result_with_json("true");
compare_datex_result_with_json("false");
compare_datex_result_with_json("null");
compare_datex_result_with_json(r#""Hello World""#);
compare_datex_result_with_json(r#""ölz1中文""#);
compare_datex_result_with_json("1.23456789");
compare_datex_result_with_json("5e3");
compare_datex_result_with_json("-5e-3");
compare_datex_result_with_json("1234567890");
compare_datex_result_with_json("[]");
compare_datex_result_with_json("{}");
compare_datex_result_with_json(
r#"{"key": "value", "number": 123, "boolean": true, "null_value": null}"#,
);
compare_datex_result_with_json(
r#"{"array": [1, 2, 3], "object": {"key": "value"}}"#,
);
}
#[test]
fn json_test_cases() {
for (path, _) in iterate_test_cases() {
println!("Testing JSON file: {}", path.display());
let file_content = std::fs::read_to_string(path).unwrap();
compare_datex_result_with_json(&file_content);
}
}
fn normalize_newlines(s: &str) -> String {
s.replace("\r\n", "\n")
}
#[test]
fn compare_with_expected() {
for (input_path, output_path) in iterate_test_cases() {
println!("Testing JSON file: {}", input_path.display());
let file_content = std::fs::read_to_string(input_path.clone()).unwrap();
let expected_content = std::fs::read_to_string(output_path).unwrap();
compare_datex_result_with_expected(
&file_content,
&expected_content,
input_path,
);
}
}
#[test]
#[ignore = "Only run this test to update expected results"]
fn update_expected() {
for (input_path, output_path) in iterate_test_cases() {
if output_path.exists() {
println!(
"Expected results already exist for: {}. Skipping update.",
input_path.display()
);
continue;
}
println!("Updating expected results for: {}", input_path.display());
let file_content = std::fs::read_to_string(input_path).unwrap();
let decompiled = get_datex_decompiled_from_json(&file_content);
std::fs::write(output_path.clone(), decompiled).unwrap();
println!("Updated expected results for: {}", output_path.display());
}
}