mod common;
use std::sync::Arc;
use std::thread;
use tabnas::Tabnas;
use tabnas_json5::{json5, make, make_with, parse, parse_with, plugin, Json5Options};
use common::{json, to_value};
fn parser(configure: impl FnOnce(&mut Json5Options)) -> Tabnas {
let mut options = Json5Options::default();
configure(&mut options);
make_with(options)
}
fn parsed(parser: &Tabnas, src: &str) -> String {
json(&parse_with(parser, src).unwrap_or_else(|error| panic!("{src:?}: {error}")))
}
fn code(parser: &Tabnas, src: &str) -> String {
match parse_with(parser, src) {
Ok(value) => panic!("{src:?} parsed to {}", json(&value)),
Err(error) => error.code,
}
}
#[test]
fn primitives() {
let j = make();
for (src, want) in [
("true", "true"),
("false", "false"),
("null", "null"),
(r#""hello""#, r#""hello""#),
("'hello'", r#""hello""#),
("42", "42"),
("3.14", "3.14"),
("-7", "-7"),
("+5", "5"),
(".5", "0.5"),
("5.", "5"),
("1e10", "10000000000"),
("1.5e-2", "0.015"),
("0x1F", "31"),
("0xDEADBEEF", "3735928559"),
("-0x10", "-16"),
] {
assert_eq!(parsed(&j, src), want, "{src:?}");
}
}
#[test]
fn infinity_and_nan() {
let j = make();
for src in ["Infinity", "+Infinity"] {
assert_eq!(parsed(&j, src), "Infinity", "{src:?}");
}
assert_eq!(parsed(&j, "-Infinity"), "-Infinity");
for src in ["NaN", "+NaN", "-NaN"] {
assert_eq!(parsed(&j, src), "NaN", "{src:?}");
}
let jn = parser(|o| o.infinity = false);
assert_eq!(code(&jn, "Infinity"), "unexpected");
assert_eq!(code(&jn, "NaN"), "unexpected");
}
#[test]
fn objects() {
let j = make();
for (src, want) in [
("{}", "{}"),
(r#"{"a":1}"#, r#"{"a":1}"#),
("{a:1}", r#"{"a":1}"#),
("{a:1,b:2}", r#"{"a":1,"b":2}"#),
("{a:1, 'b':2}", r#"{"a":1,"b":2}"#),
("{ nested: { x: 1 } }", r#"{"nested":{"x":1}}"#),
("{$id:1, _n:2, a1:3}", r#"{"$id":1,"_n":2,"a1":3}"#),
] {
assert_eq!(parsed(&j, src), want, "{src:?}");
}
}
#[test]
fn arrays() {
let j = make();
for (src, want) in [
("[]", "[]"),
("[1]", "[1]"),
("[1,2,3]", "[1,2,3]"),
(r#"["a","b"]"#, r#"["a","b"]"#),
("[[1,2],[3,4]]", "[[1,2],[3,4]]"),
] {
assert_eq!(parsed(&j, src), want, "{src:?}");
}
}
#[test]
fn trailing_commas() {
let j = make();
for (src, want) in [
("[1,2,3,]", "[1,2,3]"),
("{a:1,b:2,}", r#"{"a":1,"b":2}"#),
("[1,]", "[1]"),
("{a:1,}", r#"{"a":1}"#),
("[ 1 , 2 , ]", "[1,2]"),
] {
assert_eq!(parsed(&j, src), want, "{src:?}");
}
}
#[test]
fn comments() {
let j = make();
for (src, want) in [
("// hello\n42", "42"),
("/* block */ 42", "42"),
("{ a: 1, /* mid */ b: 2 }", r#"{"a":1,"b":2}"#),
("[/* a */ 1, /* b */ 2]", "[1,2]"),
("/* multi\nline\ncomment */ [1,2]", "[1,2]"),
] {
assert_eq!(parsed(&j, src), want, "{src:?}");
}
assert_eq!(code(&j, "# nope\n42"), "unexpected");
let jh = parser(|o| o.hash_comment = true);
assert_eq!(parsed(&jh, "# hello\n42"), "42");
}
#[test]
fn strings() {
let j = make();
for (src, want) in [
(r#""hello""#, "hello"),
("'hello'", "hello"),
(r#""he said \"hi\"""#, r#"he said "hi""#),
(r#"'he said \'hi\''"#, "he said 'hi'"),
(r#""a\tb""#, "a\tb"),
(r#""a\nb""#, "a\nb"),
(r#""aAb""#, "aAb"),
(r#""a\x41b""#, "aAb"),
(r#""\0""#, "\0"),
("\"line1\\\nline2\"", "line1line2"),
("\"line1\\\r\nline2\"", "line1line2"),
] {
match parse_with(&j, src) {
Ok(tabnas::Value::String(got)) => assert_eq!(got, want, "{src:?}"),
other => panic!("{src:?}: {other:?}"),
}
}
assert_eq!(code(&j, "`backtick`"), "unexpected");
let jb = parser(|o| o.backtick_string = true);
assert_eq!(parsed(&jb, "`backtick`"), r#""backtick""#);
}
#[test]
fn rejects_non_json5() {
let j = make();
for src in [
"", "foo", "0o17", "0b101", "1_000", "1,2,3", "a:1", "{,}", "{10:1}",
] {
assert!(parse_with(&j, src).is_err(), "{src:?} expected an error");
}
}
#[test]
fn require_value() {
let j = make();
let error = parse_with(&j, "").expect_err("empty input is an error");
assert_eq!(error.code, "json5_empty");
assert!(error.to_string().contains("JSON5"), "{error}");
assert_eq!(error.detail, "JSON5 input must contain a value");
assert!(error.hint.contains("top-level value"), "{}", error.hint);
let error = parse_with(&j, " // nothing").expect_err("no value is an error");
assert_eq!(error.code, "json5_no_value");
assert!(j.parse("").is_err());
let jopt = parser(|o| o.require_value = false);
assert_eq!(parsed(&jopt, ""), "null");
assert_eq!(parsed(&jopt, " // nothing\n/* here */"), "null");
}
#[test]
fn the_no_value_errors_carry_a_position() {
let j = make();
for (src, want) in [("//", "json5_no_value"), ("", "json5_empty")] {
let error = parse_with(&j, src).expect_err("refused");
assert_eq!(
(error.code.as_str(), error.row, error.col),
(want, 1, 1),
"{src:?}"
);
}
}
#[test]
fn non_strict_options() {
let js = parser(|o| {
o.octal = true;
o.binary = true;
o.number_separator = true;
});
assert_eq!(parsed(&js, "0o17"), "15");
assert_eq!(parsed(&js, "0b101"), "5");
assert_eq!(parsed(&js, "1_000"), "1000");
let jnh = parser(|o| o.hex = false);
assert_eq!(code(&jnh, "0x1F"), "unexpected");
}
#[test]
fn strict_value_toggle() {
let j = parser(|o| o.strict_value = false);
assert_eq!(parsed(&j, "foo"), r#""foo""#);
}
#[test]
fn json5_spec_example() {
let j = make();
let src = "{
// comments
unquoted: 'and you can quote me on that',
singleQuotes: 'I can use \"double quotes\" here',
lineBreaks: \"Look, Mom! \\
No \\\\n's!\",
hexadecimal: 0xdecaf,
leadingDecimalPoint: .8675309, andTrailing: 8675309.,
positiveSign: +1,
trailingComma: 'in objects', andIn: ['arrays',],
\"backwardsCompatible\": \"with JSON\",
}";
assert_eq!(
parsed(&j, src),
concat!(
r#"{"unquoted":"and you can quote me on that","#,
r#""singleQuotes":"I can use \"double quotes\" here","#,
r#""lineBreaks":"Look, Mom! No \\n's!","hexadecimal":912559,"#,
r#""leadingDecimalPoint":0.8675309,"andTrailing":8675309,"positiveSign":1,"#,
r#""trailingComma":"in objects","andIn":["arrays"],"backwardsCompatible":"with JSON"}"#
)
);
}
#[test]
fn json_is_json5() {
let j = make();
for src in [
"{}",
"[]",
r#"{"a":1,"b":"two","c":null,"d":true,"e":false}"#,
r#"[1,2.5,-3,1e10,"s",null,true,false]"#,
r#"{"nested":{"list":[1,{"x":null}]}}"#,
] {
let want = tabnas_support::parse_expect(src).expect("valid JSON");
let got = to_value(&parse_with(&j, src).unwrap_or_else(|error| panic!("{src:?}: {error}")));
assert!(
tabnas_support::equal_value(&got, &want),
"{src:?}: {}",
tabnas_support::format_value(&got)
);
}
}
#[test]
fn unquoted_keys_are_decoded() {
let j = make();
let value = parse_with(&j, r"{sigΣma:1, A:2}").expect("it parses");
let tabnas::Value::Object(map) = value else {
panic!("not an object: {value:?}");
};
let keys: Vec<&str> = map.keys().map(String::as_str).collect();
assert_eq!(keys, ["sigΣma", "A"]);
}
#[test]
fn options_round_trip_through_the_plugin_bag() {
let options = Json5Options {
hash_comment: true,
require_value: false,
..Default::default()
};
assert_eq!(Json5Options::from_value(&options.to_value()), options);
let partial = Json5Options::from_json(&serde_json::json!({ "octal": true }));
assert_eq!(
partial,
Json5Options {
octal: true,
..Default::default()
}
);
let odd = Json5Options::from_json(&serde_json::json!({ "hex": "no" }));
assert_eq!(odd, Json5Options::default());
}
#[test]
fn the_plugin_installs_through_use_plugin_and_records_its_options() {
let mut parser = tabnas_jsonic::make();
let overrides = Json5Options {
backtick_string: true,
..Default::default()
};
parser
.use_plugin(plugin(), Some(overrides.to_value()))
.expect("the plugin installs");
assert_eq!(parsed(&parser, "`x`"), r#""x""#);
assert_eq!(code(&parser, ""), "json5_empty");
let bag = parser.plugin_options("json5").expect("the bag is recorded");
assert_eq!(Json5Options::from_value(bag), overrides);
}
#[test]
fn the_plain_install_function_matches_the_plugin() {
let mut direct = tabnas_jsonic::make();
json5(&mut direct, &Json5Options::default()).expect("the plugin installs");
let through_make = make();
for src in ["{a:1,}", "[1,2,]", "0x10", "Infinity", "'s'"] {
assert_eq!(parsed(&direct, src), parsed(&through_make, src), "{src:?}");
}
assert_eq!(code(&direct, "foo"), code(&through_make, "foo"));
}
#[test]
fn parse_with_on_a_parser_without_the_plugin_is_a_plain_parse() {
let jsonic = tabnas_jsonic::make();
assert_eq!(parsed(&jsonic, "a:1"), r#"{"a":1}"#);
assert_eq!(
json(&parse_with(&jsonic, "").expect("jsonic accepts empty")),
"undefined"
);
}
#[test]
fn errors_carry_the_position() {
let j = make();
let error = parse_with(&j, "[1,\n foo]").expect_err("bare text is rejected");
assert_eq!(error.code, "unexpected");
assert_eq!((error.row, error.col), (2, 3));
}
#[test]
fn a_string_line_continuation_is_stripped_inside_strings_only() {
let j = make();
assert_eq!(parsed(&j, "['a\\\nb', \"p\\\r\nq\"]"), r#"["ab","pq"]"#);
assert!(parse_with(&j, "[1,\\\n2]").is_err());
assert_eq!(parsed(&j, "// c\\\n1"), "1");
}
fn error_at(parser: &Tabnas, src: &str) -> (String, usize, usize, usize) {
let at = |result: Result<tabnas::Value, tabnas::TabnasError>| match result {
Ok(value) => panic!("{src:?} parsed to {}", json(&value)),
Err(error) => (error.code, error.row, error.col, error.pos),
};
let wrapped = at(parse_with(parser, src));
assert_eq!(
at(parser.parse(src)),
wrapped,
"{src:?}: parse_with and Tabnas::parse disagree"
);
wrapped
}
#[test]
fn a_line_continuation_keeps_every_later_position() {
let j = make();
let unexpected = |row, col, pos| ("unexpected".to_string(), row, col, pos);
assert_eq!(error_at(&j, "['a\\\nb',\n @]"), unexpected(3, 3, 11));
assert_eq!(error_at(&j, "['a\\\r\nb',\r\n @]"), unexpected(3, 3, 13));
assert_eq!(error_at(&j, "['ab',\n @]"), unexpected(2, 3, 9));
}
#[test]
fn a_crlf_continuation_reads_as_an_lf_one() {
let j = make();
for eol in ["\n", "\r\n"] {
let src = format!("'a\\{eol}b'");
assert_eq!(parsed(&j, &src), r#""ab""#, "{src:?}");
let value = j
.parse(&src)
.unwrap_or_else(|error| panic!("Tabnas::parse({src:?}): {error}"));
assert_eq!(json(&value), r#""ab""#, "{src:?}");
let (code, row, col, _) = error_at(&j, &format!("['a\\{eol}b', @]"));
assert_eq!((code.as_str(), row, col), ("unexpected", 2, 5), "{eol:?}");
}
}
#[test]
fn only_an_odd_run_of_backslashes_continues_a_line() {
let j = make();
let (code, row, col, _) = error_at(&j, "['a\\\\\r\nb']");
assert_eq!((code.as_str(), row, col), ("unprintable", 1, 6));
assert_eq!(parsed(&j, "['a\\\\\\\r\nb']"), r#"["a\\b"]"#);
let (code, row, col, _) = error_at(&j, "['a\\\\\\\r\nb', @]");
assert_eq!((code.as_str(), row, col), ("unexpected", 2, 5));
}
#[test]
fn parse_uses_a_shared_default_and_is_safe_across_threads() {
assert_eq!(
json(&parse("{a:[1,2,],b:0x10}").unwrap()),
r#"{"a":[1,2],"b":16}"#
);
assert_eq!(parse("").unwrap_err().code, "json5_empty");
let sources: Arc<Vec<&'static str>> = Arc::new(vec![
"{a:1}",
"[1,2,3,]",
"'x'",
"Infinity",
"// c\n42",
"{sig\\u03A3ma:1}",
]);
let handles: Vec<_> = (0..8)
.map(|_| {
let sources = Arc::clone(&sources);
thread::spawn(move || {
for _ in 0..50 {
for src in sources.iter() {
parse(src).unwrap_or_else(|error| panic!("{src:?}: {error}"));
}
}
})
})
.collect();
for handle in handles {
handle.join().expect("a parsing thread panicked");
}
}
#[test]
fn a_line_separator_is_legal_inside_a_string_but_still_ends_a_line() {
let j = make();
for (src, want) in [
("\"a\u{2028}b\"", "a\u{2028}b"),
("\"a\u{2029}b\"", "a\u{2029}b"),
("'a\u{2028}b'", "a\u{2028}b"),
("\"\u{2028}\"", "\u{2028}"),
] {
match parse_with(&j, src) {
Ok(tabnas::Value::String(got)) => assert_eq!(got, want, "{src:?}"),
other => panic!("{src:?}: {other:?}"),
}
}
for src in ["\"a\nb\"", "\"a\rb\""] {
assert_eq!(code(&j, src), "unprintable", "{src:?}");
}
assert_eq!(parsed(&j, "//c\u{2028}1"), "1");
assert_eq!(parsed(&j, "//c\u{2029}1"), "1");
match parse_with(&j, "1\u{2028}2") {
Err(error) => assert_eq!(
(error.code.as_str(), error.row, error.col),
("unexpected", 2, 1)
),
other => panic!("{other:?}"),
}
}
#[test]
fn a_lone_surrogate_folds_to_the_replacement_character() {
let j = make();
for (src, want) in [
(r#""\uD800""#, "\u{FFFD}"),
(r#""\uDFFF""#, "\u{FFFD}"),
(r#""a\uD800b""#, "a\u{FFFD}b"),
(r#""\uDE00\uD83D""#, "\u{FFFD}\u{FFFD}"),
] {
match parse_with(&j, src) {
Ok(tabnas::Value::String(got)) => assert_eq!(got, want, "{src:?}"),
other => panic!("{src:?}: {other:?}"),
}
}
match parse_with(&j, "\"\u{1F600}\"") {
Ok(tabnas::Value::String(got)) => {
assert_eq!(got.chars().count(), 1);
assert_eq!(got, "\u{1F600}");
}
other => panic!("{other:?}"),
}
}
#[test]
fn nesting_is_capped_at_the_budget_jsonic_installs() {
const LIMIT: usize = 127;
let j = make();
for (open, close, mid) in [("[", "]", ""), ("{a:", "}", "1")] {
let at = |n: usize| format!("{}{mid}{}", open.repeat(n), close.repeat(n));
let accepted =
parse_with(&j, &at(LIMIT)).unwrap_or_else(|error| panic!("{LIMIT} levels: {error}"));
let mut level = 0;
let mut node = accepted;
loop {
let next = match &node {
tabnas::Value::Array(items) if !items.is_empty() => items[0].clone(),
tabnas::Value::Object(map) => match map.get("a") {
Some(next) => next.clone(),
None => break,
},
_ => break,
};
level += 1;
node = next;
}
let want = if mid.is_empty() { LIMIT - 1 } else { LIMIT };
assert_eq!(level, want, "{LIMIT} levels of {open}");
if !mid.is_empty() {
assert_eq!(node, tabnas::Value::Number(1.0), "{LIMIT} levels of {open}");
}
match parse_with(&j, &at(LIMIT + 1)) {
Err(error) => assert_eq!(error.code, "cancel", "{} levels", LIMIT + 1),
Ok(value) => panic!("{} levels parsed: {}", LIMIT + 1, json(&value)),
}
}
match parse_with(&j, &"[".repeat(10_000)) {
Err(error) => assert_eq!(error.code, "cancel"),
Ok(value) => panic!("10000 levels parsed: {}", json(&value)),
}
}
#[test]
fn wide_base_prefixed_literals_round_once_from_the_exact_integer() {
let j = make();
let bits = |src: &str| match parse_with(&j, src) {
Ok(tabnas::Value::Number(got)) => got.to_bits(),
other => panic!("{src:?}: {other:?}"),
};
assert_eq!(bits("0Xa6f2f78f4f9bf44"), 0x43a4_de5e_f1e9_f37f);
assert_eq!(bits("0xa6f2f78f4f9bf44"), 0x43a4_de5e_f1e9_f37f);
assert_eq!(bits("-0Xa6f2f78f4f9bf44"), 0xc3a4_de5e_f1e9_f37f);
assert_eq!(bits("+0xa6f2f78f4f9bf44"), 0x43a4_de5e_f1e9_f37f);
assert_eq!(bits("0x1fffffffffffff"), 9_007_199_254_740_991f64.to_bits());
assert_eq!(bits("0X20000000000001"), 9_007_199_254_740_992f64.to_bits());
assert_eq!(bits("0X20000000000003"), 9_007_199_254_740_996f64.to_bits());
assert_eq!(bits("0Xffffffffffffffffffffffffffffffffff"), {
let two: f64 = 2.0;
two.powi(136).to_bits()
});
assert_eq!(bits("0X10000000000000000000000000000000001"), {
let two: f64 = 2.0;
two.powi(136).to_bits()
});
let wide = format!("0x{}", "f".repeat(300));
assert_eq!(bits(&wide), f64::INFINITY.to_bits());
assert_eq!(
bits("0X0000000000000000000000000000000000001"),
1f64.to_bits()
);
assert_eq!(bits("0x0"), 0f64.to_bits());
let jo = parser(|o| {
o.octal = true;
o.binary = true;
});
let bits_o = |src: &str| match parse_with(&jo, src) {
Ok(tabnas::Value::Number(got)) => got.to_bits(),
other => panic!("{src:?}: {other:?}"),
};
assert_eq!(bits_o("0o46754573436475757744"), 0x43a3_7b2f_71e9_efc0);
assert_eq!(
bits_o("0b1010011011110010111101111000111101001111100110111111010001000101"),
0x43e4_de5e_f1e9_f37f
);
let jn = parser(|o| o.hex = false);
match parse_with(&jn, "0Xa6f2f78f4f9bf44") {
Ok(tabnas::Value::Number(got)) => assert_eq!(got.to_bits(), 0x43a4_de5e_f1e9_f37f),
other => panic!("{other:?}"),
}
}
#[test]
fn unquoted_keys_follow_this_crates_unicode_tables() {
let j = make();
let letter = regex::Regex::new(r"^[\p{L}\p{Nl}]$").expect("a literal pattern");
for ch in ['\u{00E9}', '\u{1C89}', '\u{088F}', '\u{1F600}'] {
let want = letter.is_match(ch.encode_utf8(&mut [0; 4]));
let start = format!("{{{ch}:1}}");
let part = format!("{{a{ch}:1}}");
assert_eq!(
parse_with(&j, &start).is_ok(),
want,
"U+{:04X} as a key start",
ch as u32
);
assert_eq!(
parse_with(&j, &part).is_ok(),
want,
"U+{:04X} as a key part",
ch as u32
);
}
assert_eq!(parsed(&j, "{\u{00E9}:1}"), "{\"\u{00E9}\":1}");
assert!(parse_with(&j, "{\u{1F600}:1}").is_err());
assert_eq!(parsed(&j, "{\u{1C89}:1}"), "{\"\u{1C89}\":1}");
assert_eq!(parsed(&j, "{a\u{1C89}:1}"), "{\"a\u{1C89}\":1}");
assert!(parse_with(&j, "{\u{088F}:1}").is_err());
assert!(parse_with(&j, "{a\u{088F}:1}").is_err());
}