mod common;
use serde_json::json;
use tabnas::{Tabnas, Value as EngineValue};
use tabnas_expr::{ContentDef, ExprOptions, OpDef, PrevalDef};
use tabnas_support::{load_spec, Runner, SpecOptions, Value};
use common::{
canonical, js_number, parse_simplified, parser_default, parser_for, parser_with, spec_dir,
to_failure,
};
fn run_spec(name: &str, parser: Tabnas) {
let path = spec_dir().join(name);
assert!(path.is_file(), "missing shared fixture {}", path.display());
hold_to_canonical_json(&path, &parser);
Runner::new(move |input| {
parse_simplified(&parser, input)
.map(Value::from)
.map_err(to_failure)
})
.file(&path);
}
#[test]
fn spec_happy() {
run_spec("happy.tsv", parser_default());
}
#[test]
fn spec_binary() {
run_spec("binary.tsv", parser_default());
}
#[test]
fn spec_dangling_operator() {
run_spec("dangling-operator.tsv", parser_default());
}
#[test]
fn spec_arithmetic_mixed() {
run_spec("arithmetic-mixed.tsv", parser_default());
}
#[test]
fn spec_prefix_infix_mixed() {
run_spec("prefix-infix-mixed.tsv", parser_default());
}
#[test]
fn spec_paren_deep_nest() {
run_spec("paren-deep-nest.tsv", parser_default());
}
#[test]
fn spec_structure_arith() {
run_spec("structure-arith.tsv", parser_default());
}
#[test]
fn spec_structure() {
run_spec("structure.tsv", parser_default());
}
#[test]
fn spec_render() {
run_spec("render.tsv", parser_default());
}
#[test]
fn spec_unary_prefix_basic() {
run_spec("unary-prefix-basic.tsv", parser_default());
}
#[test]
fn spec_paren_basic() {
run_spec("paren-basic.tsv", parser_default());
}
#[test]
fn spec_implicit_list_top_basic() {
run_spec("implicit-list-top-basic.tsv", parser_default());
}
#[test]
fn spec_json_base() {
run_spec("json-base.tsv", parser_default());
}
#[test]
fn spec_jsonic_base() {
run_spec("jsonic-base.tsv", parser_default());
}
#[test]
fn spec_implicit_list_top_paren() {
run_spec("implicit-list-top-paren.tsv", parser_default());
}
#[test]
fn spec_paren_implicit_list() {
run_spec("paren-implicit-list.tsv", parser_default());
}
#[test]
fn spec_paren_implicit_map() {
run_spec("paren-implicit-map.tsv", parser_default());
}
#[test]
fn spec_map_implicit_list_paren() {
run_spec("map-implicit-list-paren.tsv", parser_default());
}
#[test]
fn spec_paren_list_implicit_structure_comma() {
run_spec("paren-list-implicit-structure-comma.tsv", parser_default());
}
#[test]
fn spec_paren_list_implicit_structure_space() {
run_spec("paren-list-implicit-structure-space.tsv", parser_default());
}
#[test]
fn spec_paren_map_implicit_structure_comma() {
run_spec("paren-map-implicit-structure-comma.tsv", parser_default());
}
#[test]
fn spec_paren_map_implicit_structure_space() {
run_spec("paren-map-implicit-structure-space.tsv", parser_default());
}
#[test]
fn spec_infix_in_paren_map() {
run_spec("infix-in-paren-map.tsv", parser_default());
}
fn suffix_ops() -> serde_json::Value {
json!({
"op": {
"factorial": { "suffix": true, "left": 6000000, "src": "!" },
"question": { "suffix": true, "left": 3500000, "src": "?" },
}
})
}
#[test]
fn spec_binding_power_zero() {
run_spec(
"binding-power-zero.tsv",
parser_for(json!({
"op": {
"zero": { "infix": true, "left": 0, "right": 0, "src": "~" },
"below": { "infix": true, "left": -2000000, "right": -1900000, "src": "@" },
}
})),
);
}
#[test]
fn spec_unary_prefix_edge() {
run_spec(
"unary-prefix-edge.tsv",
parser_for(json!({
"op": {
"at": { "prefix": true, "right": 5000000, "src": "@" },
"tight": { "infix": true, "left": 7000000, "right": 7100000, "src": "~" },
}
})),
);
}
#[test]
fn spec_unary_suffix_basic() {
run_spec("unary-suffix-basic.tsv", parser_for(suffix_ops()));
}
#[test]
fn spec_unary_suffix_arith() {
run_spec("unary-suffix-arith.tsv", parser_for(suffix_ops()));
}
#[test]
fn spec_unary_suffix_structure() {
run_spec("unary-suffix-structure.tsv", parser_for(suffix_ops()));
}
#[test]
fn spec_unary_suffix_prefix() {
run_spec("unary-suffix-prefix.tsv", parser_for(suffix_ops()));
}
#[test]
fn spec_unary_suffix_paren() {
run_spec("unary-suffix-paren.tsv", parser_for(suffix_ops()));
}
fn named_parser(options: serde_json::Value) -> Tabnas {
parser_with(named(ExprOptions::from_value(&EngineValue::from_json(
&options,
))))
}
fn named(options: ExprOptions) -> ExprOptions {
options.with_evaluate(|_site, op, terms| {
let mut items = Vec::with_capacity(terms.len() + 1);
items.push(EngineValue::String(op.name.clone()));
items.extend(terms.iter().cloned());
EngineValue::array(items)
})
}
fn shared_opener(group_first: bool) -> Tabnas {
let paren = OpDef::paren("(", ")").with_preval(PrevalDef {
active: false,
required: false,
allow: None,
});
let call = OpDef::paren("(", ")").with_preval(PrevalDef {
active: true,
required: false,
allow: None,
});
let options = if group_first {
ExprOptions::new()
.with_op("paren", paren)
.with_op("call", call)
} else {
ExprOptions::new()
.with_op("call", call)
.with_op("paren", paren)
};
parser_with(named(options))
}
#[test]
fn spec_paren_shared_opener() {
run_spec("paren-shared-opener.tsv", shared_opener(true));
hold_to_canonical_json(
&spec_dir().join("paren-shared-opener.tsv"),
&shared_opener(false),
);
}
#[derive(Default, Clone, Copy)]
struct COptions {
left: bool,
cast: bool,
separated: bool,
refuse_juxtaposed: bool,
required: bool,
}
fn c_like(on: COptions) -> Tabnas {
let preval = |active: bool, required: bool| PrevalDef {
active,
required,
allow: None,
};
let mut comma = OpDef::infix(",", 1_000_000, 1_100_000);
if on.separated {
comma = comma.with_separator();
}
let mut paren = OpDef::paren("(", ")").with_preval(preval(false, false));
if on.required {
paren = paren.with_content(ContentDef {
required: true,
separated: false,
});
}
let mut call = OpDef::paren("(", ")").with_preval(preval(true, false));
let mut subscript = OpDef::paren("[", "]").with_preval(preval(true, true));
if on.left {
call = call.with_left(5_000_000);
subscript = subscript.with_left(5_000_000);
}
if on.separated {
call = call.with_content(ContentDef {
required: false,
separated: true,
});
}
let mut options = ExprOptions::new()
.with_op("comma", comma)
.with_op("deref", OpDef::prefix("*", 4_000_000))
.with_op("post_inc", OpDef::suffix("++", 5_000_000))
.with_op("dot", OpDef::infix(".", 5_000_000, 5_100_000))
.with_op("paren", paren)
.with_op("call", call)
.with_op("subscript", subscript);
if on.cast {
options = options.with_op(
"cast",
OpDef::cast("(", ")", 4_000_000, |term| {
matches!(term, EngineValue::String(name) if "int" == name || "long" == name || "char" == name)
}),
);
}
if on.refuse_juxtaposed {
options = options.with_juxtapose(false);
}
parser_with(named(options))
}
#[test]
fn spec_options_off() {
run_spec("options-off.tsv", c_like(COptions::default()));
}
#[test]
fn spec_options_paren_left() {
run_spec(
"options-paren-left.tsv",
c_like(COptions {
left: true,
..COptions::default()
}),
);
}
#[test]
fn spec_options_cast() {
run_spec(
"options-cast.tsv",
c_like(COptions {
cast: true,
..COptions::default()
}),
);
}
#[test]
fn spec_options_separated() {
run_spec(
"options-separated.tsv",
c_like(COptions {
separated: true,
..COptions::default()
}),
);
}
#[test]
fn spec_options_juxtapose() {
run_spec(
"options-juxtapose.tsv",
c_like(COptions {
refuse_juxtaposed: true,
..COptions::default()
}),
);
}
#[test]
fn spec_options_content_required() {
run_spec(
"options-content-required.tsv",
c_like(COptions {
required: true,
..COptions::default()
}),
);
}
#[test]
fn spec_options_all() {
run_spec(
"options-all.tsv",
c_like(COptions {
left: true,
cast: true,
separated: true,
refuse_juxtaposed: true,
required: true,
}),
);
}
fn c_ternary(bound: bool, values: bool) -> Tabnas {
let preval = |active: bool, required: bool| PrevalDef {
active,
required,
allow: None,
};
let mut tern = OpDef::ternary("?", ":");
if bound {
tern = tern.with_left(1_700_000).with_right(1_600_000);
}
let mut options = ExprOptions::new()
.with_op("comma", OpDef::infix(",", 1_000_000, 1_100_000).with_separator())
.with_op("assign", OpDef::infix("=", 1_500_000, 1_400_000))
.with_op("tern", tern)
.with_op("deref", OpDef::prefix("*", 4_000_000))
.with_op("post_inc", OpDef::suffix("++", 5_000_000))
.with_op("dot", OpDef::infix(".", 5_000_000, 5_100_000))
.with_op(
"paren",
OpDef::paren("(", ")")
.with_preval(preval(false, false))
.with_content(ContentDef {
required: true,
separated: false,
}),
)
.with_op(
"call",
OpDef::paren("(", ")")
.with_preval(preval(true, false))
.with_left(5_000_000)
.with_content(ContentDef {
required: false,
separated: true,
}),
)
.with_op(
"subscript",
OpDef::paren("[", "]")
.with_preval(preval(true, true))
.with_left(5_000_000),
)
.with_op(
"cast",
OpDef::cast("(", ")", 4_000_000, |term| {
matches!(term, EngineValue::String(name) if "int" == name || "long" == name || "char" == name)
}),
)
.with_juxtapose(false);
if values {
options = options.with_values(["#AT"]);
}
let options = named(options);
let mut parser = tabnas_jsonic::make();
let at = parser.token_with_source("#AT", "@");
parser.define_rule("val", move |spec| {
let mut alt = tabnas::AltSpec {
s: vec![vec![at]],
g: "host-value".to_string(),
..Default::default()
};
alt.add_action(|rule: &mut tabnas::Rule, _context: &mut tabnas::Context| {
rule.node = std::rc::Rc::new(std::cell::RefCell::new(EngineValue::String("@".into())));
});
spec.open.insert(0, alt);
});
parser
.use_plugin(tabnas_expr::plugin_with(options), None)
.expect("the expression grammar installs on the jsonic base");
parser
}
#[test]
fn spec_options_ternary_off() {
run_spec("options-ternary-off.tsv", c_ternary(false, false));
}
#[test]
fn spec_options_ternary() {
run_spec("options-ternary.tsv", c_ternary(true, false));
}
#[test]
fn spec_options_values_off() {
run_spec("options-values-off.tsv", c_ternary(true, false));
}
#[test]
fn spec_options_values() {
run_spec("options-values.tsv", c_ternary(true, true));
}
#[test]
fn spec_ternary_evaluate() {
let options = ExprOptions::new()
.with_op("ternary", OpDef::ternary("?", ":"))
.with_op(
"comma",
OpDef::infix(",", 1_000_000, 1_100_000).with_separator(),
)
.with_op(
"call",
OpDef::paren("(", ")")
.with_preval(PrevalDef {
active: true,
required: false,
allow: None,
})
.with_content(ContentDef {
required: false,
separated: true,
}),
);
run_spec("ternary-evaluate.tsv", parser_with(named(options)));
}
#[test]
fn spec_ternary_paren() {
run_spec(
"ternary-paren.tsv",
parser_with(ExprOptions::new().with_op("ternary", OpDef::ternary("?", ":"))),
);
}
#[test]
fn spec_op_override() {
run_spec(
"op-override.tsv",
parser_with(
ExprOptions::new()
.with_op("minus", OpDef::infix("-", 12_000, 12_001))
.with_op("unary_n", OpDef::prefix("-", 16_000))
.with_op("pct", OpDef::infix("%", 13_000, 13_001)),
),
);
}
#[test]
fn spec_unary_suffix_evaluate() {
run_spec("unary-suffix-evaluate.tsv", named_parser(suffix_ops()));
}
#[test]
fn spec_unary_suffix_edge() {
run_spec(
"unary-suffix-edge.tsv",
parser_for(json!({
"op": {
"factorial": { "suffix": true, "left": 6000000, "src": "!" },
"question": { "suffix": true, "left": 3500000, "src": "?" },
"tight": { "infix": true, "left": 7000000, "right": 7100000, "src": "~" },
}
})),
);
}
fn ternary_ops() -> serde_json::Value {
json!({
"op": {
"factorial": { "suffix": true, "src": "!", "left": 6000000 },
"ternary": { "ternary": true, "src": ["?", ":"] },
}
})
}
#[test]
fn spec_ternary_basic() {
run_spec("ternary-basic.tsv", parser_for(ternary_ops()));
}
#[test]
fn spec_ternary_implicit_list() {
run_spec("ternary-implicit-list.tsv", parser_for(ternary_ops()));
}
#[test]
fn spec_ternary_many_2() {
run_spec(
"ternary-many-2.tsv",
parser_for(json!({
"op": {
"foo": { "ternary": true, "src": ["?", ":"] },
"bar": { "ternary": true, "src": ["QQ", "CC"] },
}
})),
);
}
#[test]
fn spec_ternary_many_3() {
run_spec(
"ternary-many-3.tsv",
parser_for(json!({
"op": {
"foo": { "ternary": true, "src": ["?", ":"] },
"bar": { "ternary": true, "src": ["QQ", "CC"] },
"zed": { "ternary": true, "src": ["%%", "@@"] },
}
})),
);
}
#[test]
fn spec_ternary_paren_preval() {
run_spec(
"ternary-paren-preval.tsv",
parser_for(json!({
"op": {
"ternary": { "ternary": true, "src": ["?", ":"] },
"plain": {
"paren": true, "osrc": "(", "csrc": ")",
"preval": { "active": true },
},
}
})),
);
}
#[test]
fn spec_paren_preval_chain() {
run_spec(
"paren-preval-chain.tsv",
parser_for(json!({
"op": {
"index": {
"paren": true, "osrc": "[", "csrc": "]",
"preval": { "required": true },
},
"call": {
"paren": true, "osrc": "(", "csrc": ")",
"preval": { "active": true },
},
"plain": null,
}
})),
);
}
#[test]
fn spec_add_infix() {
run_spec(
"add-infix.tsv",
parser_for(json!({
"op": {
"foo": { "infix": true, "left": 3500000, "right": 3600000, "src": "foo" },
}
})),
);
}
#[test]
fn spec_add_paren() {
run_spec(
"add-paren.tsv",
parser_for(json!({
"op": { "angle": { "paren": true, "osrc": "<", "csrc": ">" } }
})),
);
}
#[test]
fn spec_paren_preval_basic() {
run_spec(
"paren-preval-basic.tsv",
parser_for(json!({
"op": {
"angle": {
"osrc": "<", "csrc": ">", "paren": true,
"preval": { "active": true },
},
}
})),
);
}
#[test]
fn spec_paren_preval_overload() {
run_spec(
"paren-preval-overload.tsv",
parser_for(json!({
"op": {
"factorial": { "suffix": true, "left": 6000000, "src": "!" },
"square": {
"osrc": "[", "csrc": "]", "paren": true,
"preval": { "required": true },
},
"brace": {
"osrc": "{", "csrc": "}", "paren": true,
"preval": { "required": true },
},
}
})),
);
}
#[test]
fn spec_paren_preval_implicit() {
run_spec(
"paren-preval-implicit.tsv",
parser_for(json!({ "op": { "plain": { "preval": true } } })),
);
}
fn number_at(terms: &[EngineValue], index: usize) -> f64 {
match terms.get(index) {
Some(EngineValue::Number(number)) => *number,
_ => 0.0,
}
}
fn factorial(n: f64) -> f64 {
if n <= 1.0 {
return 1.0;
}
let mut out = 1.0;
let mut step = 2.0;
while step <= n {
out *= step;
step += 1.0;
}
out
}
#[test]
fn spec_evaluate_math() {
let options = ExprOptions::new()
.with_op("addition", OpDef::infix("+", 140, 150))
.with_op("subtraction", OpDef::infix("-", 140, 150))
.with_op("multiplication", OpDef::infix("*", 160, 170))
.with_op("division", OpDef::infix("/", 160, 170))
.with_op("negative", OpDef::prefix("-", 200))
.with_op("positive", OpDef::prefix("+", 200))
.with_op("factorial", OpDef::suffix("!", 300))
.with_op(
"func",
OpDef::paren("(", ")").with_preval(PrevalDef {
active: true,
required: false,
allow: None,
}),
)
.with_evaluate(|_site, op, terms| {
let left = number_at(terms, 0);
let right = number_at(terms, 1);
match op.name.as_str() {
"addition-infix" => EngineValue::Number(left + right),
"subtraction-infix" => EngineValue::Number(left - right),
"multiplication-infix" => EngineValue::Number(left * right),
"division-infix" => {
EngineValue::Number(if 0.0 == right { 0.0 } else { left / right })
}
"negative-prefix" => EngineValue::Number(-left),
"positive-prefix" => EngineValue::Number(left),
"factorial-suffix" => EngineValue::Number(factorial(left)),
"func-paren" => {
let EngineValue::String(name) =
terms.first().unwrap_or(&EngineValue::Undefined)
else {
return terms.first().cloned().unwrap_or(EngineValue::Undefined);
};
let rest = &terms[1..];
let args: Vec<EngineValue> = match rest {
[EngineValue::Array(members)] => members.to_vec(),
other => other.to_vec(),
};
match name.as_str() {
"min" | "max" => {
let mut best = number_at(&args, 0);
for index in 1..args.len() {
let candidate = number_at(&args, index);
if ("min" == name) == (candidate < best) && candidate != best {
best = candidate;
}
}
EngineValue::Number(best)
}
_ => EngineValue::Number(number_at(&args, 0)),
}
}
"plain-paren" => EngineValue::Number(left),
_ => EngineValue::Number(left),
}
});
run_spec("evaluate-math.tsv", parser_with(options));
}
fn hold_to_canonical_json(path: &std::path::Path, parser: &Tabnas) {
let spec = load_spec(path, &SpecOptions::default())
.unwrap_or_else(|error| panic!("{}: {}", path.display(), error.0));
let mut failures = Vec::new();
for row in &spec.rows {
if let Some(code) = row.col(1).strip_prefix("ERROR:") {
match tabnas_expr::parse_simplified(parser, &row.unesc(0)) {
Err(error) if error.code == code => {}
other => failures.push(format!(
"{}\n not refused with {code}: {}",
row.location(),
match other {
Ok(value) => canonical(&value),
Err(error) => error.code.to_string(),
}
)),
}
continue;
}
let value = tabnas_expr::parse_simplified(parser, &row.unesc(0))
.unwrap_or_else(|error| panic!("{}: {error}", row.location()));
let got = canonical(&value);
if got != row.col(1) {
failures.push(format!(
"{}\n got {got}\n expected {}",
row.location(),
row.col(1)
));
}
}
assert!(
failures.is_empty(),
"{} of {} rows differ from the canonical JSON:\n{}",
failures.len(),
spec.rows.len(),
failures.join("\n")
);
}
#[test]
fn js_number_spells_as_javascript_does() {
for (number, want) in [
(1.0, "1"),
(-0.0, "0"),
(1.5, "1.5"),
(-2.25, "-2.25"),
(100.0, "100"),
(1e20, "100000000000000000000"),
(1e21, "1e+21"),
(1.5e300, "1.5e+300"),
(0.000001, "0.000001"),
(1e-7, "1e-7"),
(-1.25e-7, "-1.25e-7"),
(0.1 + 0.2, "0.30000000000000004"),
(f64::NAN, "null"),
(f64::INFINITY, "null"),
(f64::from_bits(0x4305edd45e85c45a), "771558860699787.2"),
(f64::from_bits(0x4305edd45e85c45e), "771558860699787.8"),
(f64::from_bits(0x4310000000000001), "1125899906842624.2"),
(f64::from_bits(0x3e60000000000000), "2.9802322387695312e-8"),
(f64::from_bits(0x0060000000000000), "7.120236347223045e-307"),
(f64::from_bits(0x0000000000000001), "5e-324"),
(f64::MAX, "1.7976931348623157e+308"),
(-f64::MAX, "-1.7976931348623157e+308"),
] {
assert_eq!(js_number(number), want, "for {number:?}");
}
}
#[test]
fn every_fixture_row_is_held_to_its_canonical_json() {
let rows: usize = std::fs::read_dir(spec_dir())
.expect("the shared fixture directory is readable")
.map(|entry| entry.expect("a readable directory entry").path())
.filter(|path| path.extension().is_some_and(|ext| ext == "tsv"))
.map(|path| {
load_spec(&path, &SpecOptions::default())
.unwrap_or_else(|error| panic!("{}: {}", path.display(), error.0))
.rows
.len()
})
.sum();
assert_eq!(
rows, 1470,
"the shared fixtures hold {rows} rows, not the 1470 measured"
);
}
#[test]
fn every_shared_fixture_is_run() {
let source = std::fs::read_to_string(
common::repo_root()
.join("rs")
.join("tests")
.join("parity_test.rs"),
)
.expect("this test file is readable");
let mut fixtures: Vec<String> = std::fs::read_dir(spec_dir())
.expect("the shared fixture directory is readable")
.map(|entry| entry.expect("a readable directory entry").file_name())
.map(|name| name.to_string_lossy().into_owned())
.filter(|name| name.ends_with(".tsv"))
.collect();
fixtures.sort();
assert!(
!fixtures.is_empty(),
"no fixtures in {}; the coverage gate would pass over nothing",
spec_dir().display()
);
let missing: Vec<&String> = fixtures
.iter()
.filter(|name| !source.contains(&format!("\"{name}\"")))
.collect();
assert!(
missing.is_empty(),
"no Rust runner for {} of {} shared fixtures: {:?}. \
Add a `run_spec` test with the operator table the file assumes, \
matching the TypeScript and Go runners.",
missing.len(),
fixtures.len(),
missing
);
}