#![allow(clippy::result_large_err)]
use std::cell::RefCell;
use std::rc::Rc;
use std::sync::{Arc, OnceLock};
use indexmap::IndexMap;
use regex::Regex;
use serde_json::json;
use tabnas::{
ActionError, Context, GrammarError, GrammarSpec, LexCheckResult, ListRef, Options, Plugin,
PluginError, Rule, Tabnas, Text, Tin, Token, Value, TIN_OB, TIN_OS, TIN_ST, TIN_TX, TIN_ZZ,
};
pub const VERSION: &str = "0.7.2";
#[cfg(doctest)]
#[doc = include_str!("../README.md")]
mod readme_examples {}
pub use tabnas::TabnasError as JsonicError;
const FINISH: &str = "@finish";
const PAIRKEY: &str = "@jsonic-pairkey";
const VAL_BC: &str = "@val-bc/replace";
const VAL_AC: &str = "@val-ac/append";
const MAP_BO: &str = "@map-bo/append";
const MAP_BC: &str = "@map-bc/append";
const LIST_BO: &str = "@list-bo/append";
const LIST_BC: &str = "@list-bc/append";
const PAIR_BC: &str = "@pair-bc/append";
const ELEM_BC: &str = "@elem-bc/replace";
const VAL_CLOSE_ERROR: &str = "@val-close-error";
const ELEM_DOUBLE_COMMA: &str = "@elem-double-comma";
const ELEM_SINGLE_COMMA: &str = "@elem-single-comma";
const ELEM_PAIR_ERR: &str = "@elem-pair-err";
const ELEM_CLOSE_ERR: &str = "@elem-close-err";
const STRICT_NUMBER_CHECK: &str = "jsonic-strict-number";
const PLUGIN_NAME: &str = "jsonic";
fn jsonic_options_document() -> serde_json::Value {
json!({
"options": {
"errmsg": {
"name": "jsonic",
"link": "https://github.com/tabnas/jsonic",
},
"hint": {
"unknown": "\nSince the error is unknown, this is probably a bug inside jsonic\nitself, or a plugin. Please consider posting a github issue - thanks!\n\nCode: {code}, Details: \n{details}",
"unexpected": "\nThe character(s) {src} were not expected at this point as they do not\nmatch the expected syntax, even under the relaxed jsonic rules. If it\nis not obviously wrong, the actual syntax error may be elsewhere. Try\ncommenting out larger areas around this point until you get no errors,\nthen remove the comments in small sections until you find the\noffending syntax. NOTE: Also check if any plugins you are using\nexpect different syntax in this case.",
"invalid_unicode": "\nThe escape sequence {src} does not encode a valid unicode code point\nnumber. You may need to validate your string data manually using test\ncode to see how JavaScript will interpret it. Also consider that your\ndata may have become corrupted, or the escape sequence has not been\ngenerated correctly.",
"invalid_ascii": "\nThe escape sequence {src} does not encode a valid ASCII character. You\nmay need to validate your string data manually using test code to see\nhow JavaScript will interpret it. Also consider that your data may\nhave become corrupted, or the escape sequence has not been generated\ncorrectly.",
"unprintable": "\nString values cannot contain unprintable characters (character codes\nbelow 32). The character {src} is unprintable. You may need to remove\nthese characters from your source data. Also check that it has not\nbecome corrupted.",
"unterminated_string": "\nThis string has no end quote.",
"unterminated_comment": "\nThis comment is never closed.",
"unknown_rule": "\nNo rule named $rulename is defined. This is probably an error in the\ngrammar of a plugin.",
"end_of_source": "\nUnexpected end of source.",
},
},
})
}
fn apply_options(parser: &mut Tabnas) -> Result<(), GrammarError> {
let spec = GrammarSpec::from_value(jsonic_options_document())?;
parser.grammar(&spec)?;
Ok(())
}
fn restore_relaxed(options: &mut Options, relaxed: &Options) {
options.text.lex = relaxed.text.lex;
options.number.hex = relaxed.number.hex;
options.number.oct = relaxed.number.oct;
options.number.bin = relaxed.number.bin;
options.number.sep.clone_from(&relaxed.number.sep);
options.number.check.clone_from(&relaxed.number.check);
options.string.chars.clone_from(&relaxed.string.chars);
options
.string
.multi_chars
.clone_from(&relaxed.string.multi_chars);
options.string.allow_unknown = relaxed.string.allow_unknown;
options.string.escape_strict = relaxed.string.escape_strict;
options.string.escape.clone_from(&relaxed.string.escape);
options.comment.lex = relaxed.comment.lex;
options.map.extend = relaxed.map.extend;
options.lex.empty = relaxed.lex.empty;
options.rule.finish = relaxed.rule.finish;
options.rule.include.clone_from(&relaxed.rule.include);
match relaxed.token_set.get("KEY") {
Some(key) => {
options.token_set.insert("KEY".to_string(), key.clone());
}
None => {
options.token_set.remove("KEY");
}
}
options.parse.budget = relaxed.parse.budget.clone();
}
fn jsonic_document(options: &Options) -> serde_json::Value {
let list_pairs_allowed = options.list.property || options.list.pair;
let mut pair_open = vec![
json!({ "s": "#KEY #CL", "p": "val", "u": { "pair": true }, "a": PAIRKEY,
"g": "map,pair,key,json" }),
json!({ "s": "#CA", "g": "map,pair,comma,jsonic" }),
];
if options.map.child {
pair_open.push(
json!({ "s": "#CL", "p": "val", "u": { "done": true, "child": true },
"g": "map,pair,child,jsonic" }),
);
}
let mut elem_pair = json!({
"s": "#KEY #CL", "p": "val",
"n": { "pk": 1, "dmap": 1 },
"u": { "done": true, "pair": true, "list": true },
"a": PAIRKEY,
"g": "elem,pair,jsonic",
});
if !list_pairs_allowed {
elem_pair["e"] = json!(ELEM_PAIR_ERR);
}
let mut elem_open = vec![
json!({ "s": "#CA #CA", "b": 2, "u": { "done": true }, "a": ELEM_DOUBLE_COMMA,
"g": "list,elem,imp,null,jsonic" }),
json!({ "s": "#CA", "u": { "done": true }, "a": ELEM_SINGLE_COMMA,
"g": "list,elem,imp,null,jsonic" }),
elem_pair,
];
if options.list.child {
elem_open.push(json!({ "s": "#CL", "p": "val",
"u": { "done": true, "child": true, "list": true },
"g": "elem,child,jsonic" }));
}
json!({
"v": 2,
"rule": {
"val": {
"open": {
"alts": [
{ "s": "#KEY #CL", "c": { "d": 0 }, "p": "map", "b": 2, "a": "@reset$",
"g": "pair,jsonic,top" },
{ "s": "#KEY #CL", "p": "map", "b": 2, "n": { "pk": 1 }, "a": "@reset$",
"g": "pair,jsonic" },
{ "s": "#VAL", "a": "@reset$", "g": "val,json" },
{ "s": ["#CB #CS"], "b": 1, "c": { "d": { "$gt": 0 } }, "a": "@reset$",
"g": "val,imp,null,jsonic" },
{ "s": "#CA", "c": { "d": 0 }, "p": "list", "b": 1, "a": "@array$",
"k": { "array$": { "implicit": true } }, "g": "list,imp,jsonic" },
{ "s": "#CA", "b": 1, "a": "@reset$", "g": "list,val,imp,null,jsonic" },
{ "s": "#ZZ", "g": "jsonic" },
],
"inject": { "append": true, "delete": [2] },
},
"close": {
"alts": [
{ "s": ["#CB #CS"], "b": 1, "g": "val,json,close", "e": VAL_CLOSE_ERROR },
{ "s": "#CA", "c": { "n.dlist": { "$lte": 0 }, "n.dmap": { "$lte": 0 } },
"r": "list", "u": { "implist": true },
"g": "list,val,imp,comma,jsonic" },
{ "c": { "n.dlist": { "$lte": 0 }, "n.dmap": { "$lte": 0 } },
"r": "list", "u": { "implist": true },
"g": "list,val,imp,space,jsonic", "b": 1 },
{ "s": "#ZZ", "g": "end,jsonic" },
],
"inject": { "append": true },
},
},
"map": {
"open": [
{ "s": "#OB #ZZ", "b": 1, "a": "@object$", "e": FINISH, "g": "end,jsonic" },
],
"close": {
"alts": [
{ "s": "#CB", "c": { "n.pk": { "$lte": 0 } }, "g": "end,json" },
{ "s": "#CB", "b": 1, "g": "path,close,jsonic" },
{ "s": ["#CA #CS #VAL"], "b": 1, "g": "end,path,jsonic" },
{ "s": "#ZZ", "e": FINISH, "g": "end,jsonic" },
],
"inject": { "append": true, "delete": [0] },
},
},
"list": {
"open": [
{ "c": { "prev.u.implist": { "$eq": true } }, "p": "elem" },
],
"close": {
"alts": [
{ "s": "#ZZ", "e": FINISH, "g": "end,jsonic" },
],
"inject": { "append": true },
},
},
"pair": {
"open": {
"alts": pair_open,
"inject": { "append": true, "clear": true },
},
"close": {
"alts": [
{ "s": "#CB", "c": { "n.pk": { "$lte": 0 } }, "b": 1,
"g": "map,pair,close,json" },
{ "s": "#CA #CB", "c": { "n.pk": { "$lte": 0 } }, "b": 1,
"g": "map,pair,comma,jsonic" },
{ "s": "#CA #ZZ", "g": "end,jsonic" },
{ "s": "#CA", "c": { "n.pk": { "$lte": 0 } }, "r": "pair",
"g": "map,pair,sync,json" },
{ "s": "#CA", "c": { "n.dmap": { "$lte": 1 } }, "r": "pair",
"g": "map,pair,sync,jsonic" },
{ "s": "#KEY", "c": { "n.dmap": { "$lte": 1 } }, "r": "pair", "b": 1,
"g": "map,pair,imp,sync,jsonic" },
{ "s": ["#CB #CA #CS #KEY"], "c": { "n.pk": { "$gt": 0 } }, "b": 1,
"g": "map,pair,imp,path,close,jsonic" },
{ "s": "#CS", "e": ELEM_CLOSE_ERR, "g": "end,jsonic" },
{ "s": "#ZZ", "e": FINISH, "g": "map,pair,end,json" },
{ "r": "pair", "b": 1, "g": "map,pair,imp,jsonic" },
],
"inject": { "append": true, "delete": [0, 1] },
},
},
"elem": {
"open": elem_open,
"close": {
"alts": [
{ "s": ["#CA", "#CS #ZZ"], "b": 1, "g": "list,elem,comma,jsonic" },
{ "s": "#CA", "r": "elem", "g": "list,elem,sync,json" },
{ "s": "#CS", "b": 1, "g": "list,elem,close,json" },
{ "s": "#ZZ", "e": FINISH, "g": "list,elem,end,json" },
{ "s": "#CB", "e": ELEM_CLOSE_ERR, "g": "end,jsonic" },
{ "r": "elem", "b": 1, "g": "list,elem,imp,jsonic" },
],
"inject": { "delete": [-1, -2] },
},
},
},
})
}
fn jsonic_document_append() -> serde_json::Value {
json!({
"v": 2,
"rule": {
"val": {
"close": { "alts": [], "inject": { "move": [1, -1] } },
},
"map": {
"open": {
"alts": [
{ "s": "#KEY #CL", "p": "pair", "b": 2, "a": "@object$",
"k": { "object$": { "implicit": true } },
"g": "pair,list,val,imp,jsonic" },
],
"inject": { "append": true },
},
},
"list": {
"open": {
"alts": [
{ "s": "#CA", "p": "elem", "b": 1, "g": "list,elem,val,imp,jsonic" },
{ "p": "elem", "g": "list,elem,jsonic" },
],
"inject": { "append": true },
},
},
},
})
}
fn set_node(rule: &mut Rule, value: Value) {
rule.node = Rc::new(RefCell::new(value));
}
fn unwrap_arc<T: Clone>(shared: Arc<T>) -> T {
Arc::try_unwrap(shared).unwrap_or_else(|shared| (*shared).clone())
}
fn map_get(node: &Value, key: &str) -> Option<Value> {
match node {
Value::Object(map) => map.get(key).cloned(),
Value::MapRef(map) => map.value.get(key).cloned(),
_ => None,
}
}
fn map_insert(node: &mut Value, key: String, value: Value) {
match node {
Value::Object(map) => {
Arc::make_mut(map).insert(key, value);
}
Value::MapRef(map) => {
Arc::make_mut(map).value.insert(key, value);
}
_ => {}
}
}
fn list_push(node: &mut Value, value: Value) {
match node {
Value::Array(items) => Arc::make_mut(items).push(value),
Value::ListRef(list) => Arc::make_mut(list).value.push(value),
_ => {}
}
}
fn is_primitive(value: &Value) -> bool {
matches!(value, Value::Bool(_) | Value::Number(_) | Value::String(_))
}
fn flag(rule: &Rule, name: &str) -> bool {
matches!(rule.u.get(name), Some(Value::Bool(true)))
}
fn child_or_null(rule: &Rule) -> Value {
if rule.child_node.is_undefined() {
Value::Null
} else {
rule.child_node.clone()
}
}
fn is_fixed(tin: Tin, options: &Options) -> bool {
options.fixed.tokens.values().any(|token| token.tin == tin)
}
fn carries_no_value(token: &Token, options: &Options) -> bool {
token.tin == TIN_ZZ
|| (is_fixed(token.tin, options)
&& matches!(&token.val, Value::String(text) if text == token.src.as_str()))
}
pub fn deep_merge(base: Value, overlay: Value) -> Value {
const DANGEROUS: [&str; 3] = ["__proto__", "constructor", "prototype"];
fn merge_entries(base: &mut IndexMap<String, Value>, overlay: IndexMap<String, Value>) {
for (key, value) in overlay {
if DANGEROUS.contains(&key.as_str()) {
continue;
}
let previous = base.get(&key).cloned().unwrap_or(Value::Undefined);
base.insert(key, deep_merge(previous, value));
}
}
fn merge_items(base: &mut Vec<Value>, overlay: Vec<Value>) {
for (index, value) in overlay.into_iter().enumerate() {
if index < base.len() {
let previous = std::mem::replace(&mut base[index], Value::Undefined);
base[index] = deep_merge(previous, value);
} else {
base.push(value);
}
}
}
match (base, overlay) {
(base, Value::Undefined) => base,
(Value::Object(base), Value::Object(overlay)) => {
let mut base = unwrap_arc(base);
merge_entries(&mut base, unwrap_arc(overlay));
Value::object(base)
}
(Value::Object(base), Value::MapRef(overlay)) => {
let mut base = unwrap_arc(base);
merge_entries(&mut base, unwrap_arc(overlay).value);
Value::object(base)
}
(Value::MapRef(base), Value::Object(overlay)) => {
let mut base = unwrap_arc(base);
merge_entries(&mut base.value, unwrap_arc(overlay));
Value::MapRef(Arc::new(base))
}
(Value::MapRef(base), Value::MapRef(overlay)) => {
let mut base = unwrap_arc(base);
merge_entries(&mut base.value, unwrap_arc(overlay).value);
Value::MapRef(Arc::new(base))
}
(Value::Array(base), Value::Array(overlay)) => {
let mut base = unwrap_arc(base);
merge_items(&mut base, unwrap_arc(overlay));
Value::array(base)
}
(Value::Array(base), Value::ListRef(overlay)) => {
let mut base = unwrap_arc(base);
merge_items(&mut base, unwrap_arc(overlay).value);
Value::array(base)
}
(Value::ListRef(base), Value::Array(overlay)) => {
let mut base = unwrap_arc(base);
merge_items(&mut base.value, unwrap_arc(overlay));
Value::ListRef(Arc::new(base))
}
(Value::ListRef(base), Value::ListRef(overlay)) => {
let mut base = unwrap_arc(base);
merge_items(&mut base.value, unwrap_arc(overlay).value);
Value::ListRef(Arc::new(base))
}
(_, overlay) => overlay,
}
}
fn combine(previous: Value, value: Value, rule: &mut Rule, context: &mut Context) -> Value {
if let Some(merge) = context.options.map.merge.clone() {
merge(previous, value, rule, context)
} else if context.options.map.extend {
deep_merge(previous, value)
} else {
value
}
}
const DEPTH_LIMIT: usize = 127;
fn depth(context: &Context) -> usize {
let is_container = |name: &str| name == "map" || name == "list";
let ancestors = context
.rule_stack
.iter()
.filter(|rule| is_container(&rule.name))
.count();
let current = usize::from(
context
.rule
.as_ref()
.is_some_and(|rule| is_container(&rule.name)),
);
ancestors + current
}
fn within_depth_limit(context: &Context) -> bool {
depth(context) <= DEPTH_LIMIT
}
fn resolve_token(rule: &mut Rule, context: &mut Context) -> Value {
let Some(token) = rule.o0().cloned() else {
return Value::Undefined;
};
if carries_no_value(&token, &context.options) {
return Value::Undefined;
}
let value = token.resolve_val(rule, context);
if context.options.info.text && matches!(token.tin, TIN_ST | TIN_TX) {
if let Value::String(string) = value {
let quote = if token.tin == TIN_ST {
token
.src
.as_str()
.chars()
.next()
.map(String::from)
.unwrap_or_default()
} else {
String::new()
};
return Value::Text(Text { quote, string });
}
}
value
}
fn val_before_close(rule: &mut Rule, context: &mut Context) -> Result<(), ActionError> {
let openval = rule.node.borrow().clone();
rule.u_mut().insert("openval".to_string(), openval.clone());
let node = if rule.has_child_value() {
rule.child_value()
} else if is_primitive(&openval) {
return Ok(());
} else if rule.os() != 0 {
resolve_token(rule, context)
} else if !openval.is_undefined() {
return Ok(());
} else {
Value::Undefined
};
set_node(rule, node);
Ok(())
}
fn val_after_close(rule: &mut Rule, context: &mut Context) -> Result<(), ActionError> {
if rule.has_child_value() {
return Ok(());
}
let openval = rule.u.get("openval").cloned().unwrap_or(Value::Undefined);
if is_primitive(&openval) {
set_node(rule, openval);
} else if rule
.o0()
.is_some_and(|token| carries_no_value(token, &context.options))
{
set_node(rule, Value::Undefined);
}
Ok(())
}
fn bump(rule: &mut Rule, counter: &str) {
let depth = rule.n.get(counter).copied().unwrap_or(0);
rule.n_mut().insert(counter.to_string(), depth + 1);
}
fn map_before_open(rule: &mut Rule, _context: &mut Context) -> Result<(), ActionError> {
bump(rule, "dmap");
Ok(())
}
fn list_before_open(rule: &mut Rule, context: &mut Context) -> Result<(), ActionError> {
bump(rule, "dlist");
let promoted = rule.prev_rule.as_ref().and_then(|prev| {
matches!(prev.u.get("implist"), Some(Value::Bool(true))).then(|| prev.node.borrow().clone())
});
if let Some(first) = promoted {
let first = if first.is_undefined() {
Value::Null
} else {
first
};
let list = if context.options.info.list {
Value::ListRef(Arc::new(ListRef {
value: vec![first],
implicit: true,
child: None,
meta: IndexMap::new(),
}))
} else {
Value::array(vec![first])
};
*rule.node.borrow_mut() = list;
}
Ok(())
}
fn map_before_close(rule: &mut Rule, context: &mut Context) -> Result<(), ActionError> {
if context.options.info.map {
let implicit = rule.o0().is_none_or(|token| token.tin != TIN_OB);
if let Value::MapRef(map) = &mut *rule.node.borrow_mut() {
Arc::make_mut(map).implicit = implicit;
}
}
Ok(())
}
fn list_before_close(rule: &mut Rule, _context: &mut Context) -> Result<(), ActionError> {
let implicit = rule.o0().is_none_or(|token| token.tin != TIN_OS);
if let Value::ListRef(list) = &mut *rule.node.borrow_mut() {
Arc::make_mut(list).implicit = implicit;
}
Ok(())
}
fn pairval(rule: &mut Rule, context: &mut Context) {
let Some(Value::String(key)) = rule.u.get("key").cloned() else {
return;
};
let value = child_or_null(rule);
if flag(rule, "list")
&& context.options.safe.key
&& (key == "__proto__" || key == "constructor")
{
return;
}
if context.options.info.map && key == context.options.info.marker {
return;
}
let previous = {
let node = rule.node.borrow();
map_get(&node, &key)
};
let value = match previous {
None | Some(Value::Null) | Some(Value::Undefined) => value,
Some(previous) => combine(previous, value, rule, context),
};
map_insert(&mut rule.node.borrow_mut(), key, value);
}
fn map_child(rule: &mut Rule, context: &mut Context) {
let value = child_or_null(rule);
let previous = {
let node = rule.node.borrow();
map_get(&node, "child$")
};
let value = match previous {
None | Some(Value::Undefined) => value,
Some(previous) => combine(previous, value, rule, context),
};
map_insert(&mut rule.node.borrow_mut(), "child$".to_string(), value);
}
fn list_child(rule: &mut Rule, context: &mut Context) {
let value = child_or_null(rule);
let previous = {
let node = rule.node.borrow();
match &*node {
Value::ListRef(list) => list.child.as_deref().cloned(),
_ => None,
}
};
let value = match previous {
None => value,
Some(previous) => combine(previous, value, rule, context),
};
let mut node = rule.node.borrow_mut();
let mut list = match std::mem::replace(&mut *node, Value::Undefined) {
Value::Array(items) => ListRef {
value: unwrap_arc(items),
implicit: false,
child: None,
meta: IndexMap::new(),
},
Value::ListRef(list) => unwrap_arc(list),
other => {
*node = other;
return;
}
};
list.child = Some(Box::new(value));
*node = Value::ListRef(Arc::new(list));
}
fn pair_before_close(rule: &mut Rule, context: &mut Context) -> Result<(), ActionError> {
if flag(rule, "pair") {
pairval(rule, context);
}
if flag(rule, "child") {
map_child(rule, context);
}
Ok(())
}
fn elem_before_close(rule: &mut Rule, context: &mut Context) -> Result<(), ActionError> {
if !flag(rule, "done") && !rule.child_node.is_undefined() {
let child = rule.child_node.clone();
list_push(&mut rule.node.borrow_mut(), child);
}
if flag(rule, "pair") {
if context.options.list.pair {
if let Some(Value::String(key)) = rule.u.get("key").cloned() {
let mut pair = IndexMap::new();
pair.insert(key, child_or_null(rule));
list_push(&mut rule.node.borrow_mut(), Value::object(pair));
}
} else {
pairval(rule, context);
}
}
if flag(rule, "child") {
list_child(rule, context);
}
Ok(())
}
fn pairkey(rule: &mut Rule, _context: &mut Context) -> Result<(), ActionError> {
let Some(token) = rule.o0().cloned() else {
return Ok(());
};
let key = if matches!(token.tin, TIN_ST | TIN_TX) {
match token.val {
Value::String(text) => text,
Value::Text(text) => text.string,
Value::Number(number) if number.fract() == 0.0 && number.is_finite() => {
format!("{number:.0}")
}
other => other.to_string(),
}
} else {
token.src.as_str().to_string()
};
rule.u_mut().insert("key".to_string(), Value::String(key));
Ok(())
}
fn push_null(rule: &mut Rule, _context: &mut Context) -> Result<(), ActionError> {
list_push(&mut rule.node.borrow_mut(), Value::Null);
Ok(())
}
fn register_refs(parser: &mut Tabnas) {
parser.alt_error(FINISH, |_rule, context| {
if context.options.rule.finish {
return None;
}
let mut token = context.t0()?.clone();
token.bad("end_of_source");
Some(token)
});
parser.alt_error(VAL_CLOSE_ERROR, |rule, context| {
if rule.d == 0 {
context.t0().cloned()
} else {
None
}
});
parser.alt_error(ELEM_PAIR_ERR, |_rule, context| context.t0().cloned());
parser.alt_error(ELEM_CLOSE_ERR, |rule, _context| rule.c0().cloned());
parser.action_with_context(PAIRKEY, pairkey);
parser.action_with_context(ELEM_DOUBLE_COMMA, push_null);
parser.action_with_context(ELEM_SINGLE_COMMA, push_null);
parser.state_action_ref(VAL_BC, val_before_close);
parser.state_action_ref(VAL_AC, val_after_close);
parser.state_action_ref(MAP_BO, map_before_open);
parser.state_action_ref(MAP_BC, map_before_close);
parser.state_action_ref(LIST_BO, list_before_open);
parser.state_action_ref(LIST_BC, list_before_close);
parser.state_action_ref(PAIR_BC, pair_before_close);
parser.state_action_ref(ELEM_BC, elem_before_close);
}
fn grammar_installed(parser: &Tabnas) -> bool {
parser
.rules
.get("val")
.is_some_and(|spec| spec.bc.iter().any(|action| action == VAL_BC))
}
pub fn register_jsonic_grammar(parser: &mut Tabnas) -> Result<(), GrammarError> {
if grammar_installed(parser) {
return Ok(());
}
register_refs(parser);
let relaxed = parser.config();
tabnas_json::json(parser)?;
parser
.set_options(|options| restore_relaxed(options, &relaxed))
.map_err(|error| GrammarError(error.0))?;
let options = parser.config();
let phase_one = GrammarSpec::from_value(jsonic_document(&options))?;
parser.grammar(&phase_one)?;
let phase_two = GrammarSpec::from_value(jsonic_document_append())?;
parser.grammar(&phase_two)?;
if parser.config().parse.budget.on_check.is_none() {
parser.parse_budget(1, within_depth_limit);
}
Ok(())
}
pub fn jsonic(parser: &mut Tabnas) -> Result<(), GrammarError> {
apply_options(parser)?;
register_jsonic_grammar(parser)
}
pub fn plugin() -> Plugin {
Plugin::new(PLUGIN_NAME, |parser, _options| {
jsonic(parser).map_err(|error| PluginError(error.0))
})
}
fn grammar_plugin() -> Plugin {
Plugin::new(PLUGIN_NAME, |parser, _options| {
register_jsonic_grammar(parser).map_err(|error| PluginError(error.0))
})
}
pub fn make_with(configure: impl FnOnce(&mut Options)) -> Tabnas {
let mut parser = Tabnas::new();
apply_options(&mut parser).expect("the jsonic option document is fixed and valid");
parser
.set_options(configure)
.expect("the caller's options apply to a fresh engine");
parser
.use_plugin(grammar_plugin(), None)
.expect("the jsonic grammar documents are fixed and valid");
parser
}
pub fn make() -> Tabnas {
make_with(|_| {})
}
fn strict_number() -> &'static Regex {
static RE: OnceLock<Regex> = OnceLock::new();
RE.get_or_init(|| {
Regex::new(r"^-?(0|[1-9][0-9]*)(\.[0-9]+)?([eE][+-]?[0-9]+)?$")
.expect("the strict-number pattern is a literal and compiles")
})
}
fn leading_literal(src: &str) -> &str {
let end = src
.find(|c: char| c.is_whitespace() || matches!(c, ',' | '}' | ']' | ':' | '"' | '/'))
.unwrap_or(src.len());
&src[..end]
}
fn strict_number_check(src: &str) -> LexCheckResult {
let literal = leading_literal(src);
let starts_number = literal
.chars()
.next()
.is_some_and(|c| c == '-' || c == '+' || c == '.' || c.is_ascii_digit());
if !starts_number || strict_number().is_match(literal) {
LexCheckResult::Continue
} else {
LexCheckResult::Skip
}
}
fn strict_json_document() -> serde_json::Value {
json!({
"options": {
"text": { "lex": false },
"number": {
"hex": false, "oct": false, "bin": false, "sep": null,
"check": STRICT_NUMBER_CHECK,
},
"string": {
"chars": "\"",
"multiChars": "",
"allowUnknown": false,
"escape": { "v": null },
"escapeStrict": true,
},
"comment": { "lex": false },
"map": { "extend": false },
"lex": { "empty": false },
"rule": { "finish": false, "include": "json" },
"tokenSet": { "KEY": ["#ST", null, null, null] },
},
})
}
pub fn make_json() -> Tabnas {
let mut parser = Tabnas::new();
apply_options(&mut parser).expect("the jsonic option document is fixed and valid");
parser.lex_check_ref(STRICT_NUMBER_CHECK, strict_number_check);
let strict = GrammarSpec::from_value(strict_json_document())
.expect("the strict-JSON option document is fixed and valid");
parser
.grammar(&strict)
.expect("the strict-JSON options apply to a fresh engine");
parser
.use_plugin(grammar_plugin(), None)
.expect("the jsonic grammar documents are fixed and valid");
parser
}
pub fn empty() -> Tabnas {
let mut parser = make();
for name in parser.rule_names() {
parser.define_rule(name, |spec| {
spec.clear();
});
}
parser
}
pub fn parse(src: &str) -> Result<Value, JsonicError> {
static DEFAULT: OnceLock<Tabnas> = OnceLock::new();
DEFAULT.get_or_init(make).parse(src)
}