#![allow(clippy::result_large_err)]
use std::rc::Rc;
use std::sync::OnceLock;
use indexmap::IndexMap;
use regex::Regex;
use serde_json::{json, Value as JsonValue};
use tabnas::{
ActionError, AltSpec, Context, LexCheckResult, Plugin, PluginError, Rule, RuleSnapshot, Tabnas,
Tin, Token, Value, ValueDef, TIN_NR, TIN_TX, TIN_ZZ,
};
pub const VERSION: &str = "0.5.9";
#[cfg(doctest)]
#[doc = include_str!("../README.md")]
mod readme_examples {}
pub use tabnas::TabnasError as Json5Error;
const PLUGIN_NAME: &str = "json5";
const OPTIONS_MARK: &str = "json5$options";
const JSON5_WHITESPACE: &str = "\t\u{000B}\u{000C} \u{00A0}\u{FEFF}\u{1680}\u{2000}\u{2001}\u{2002}\u{2003}\u{2004}\u{2005}\u{2006}\u{2007}\u{2008}\u{2009}\u{200A}\u{202F}\u{205F}\u{3000}";
const JSON5_LINE_CHARS: &str = "\r\n";
const JSON5_LINE_FIXED: &str = "\u{2028}\u{2029}";
const JSON5_ROW_CHARS: &str = "\n\u{2028}\u{2029}";
fn is_line_terminator(ch: char) -> bool {
matches!(ch, '\n' | '\r' | '\u{2028}' | '\u{2029}')
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct Json5Options {
pub infinity: bool,
pub hex: bool,
pub hash_comment: bool,
pub backtick_string: bool,
pub number_separator: bool,
pub octal: bool,
pub binary: bool,
pub require_value: bool,
pub strict_value: bool,
}
impl Default for Json5Options {
fn default() -> Self {
Self {
infinity: true,
hex: true,
hash_comment: false,
backtick_string: false,
number_separator: false,
octal: false,
binary: false,
require_value: true,
strict_value: true,
}
}
}
impl Json5Options {
pub const KEYS: [&str; 9] = [
"infinity",
"hex",
"hashComment",
"backtickString",
"numberSeparator",
"octal",
"binary",
"requireValue",
"strictValue",
];
fn get(&self, key: &str) -> bool {
match key {
"infinity" => self.infinity,
"hex" => self.hex,
"hashComment" => self.hash_comment,
"backtickString" => self.backtick_string,
"numberSeparator" => self.number_separator,
"octal" => self.octal,
"binary" => self.binary,
"requireValue" => self.require_value,
"strictValue" => self.strict_value,
_ => unreachable!("every option key is listed"),
}
}
fn set(&mut self, key: &str, value: bool) {
match key {
"infinity" => self.infinity = value,
"hex" => self.hex = value,
"hashComment" => self.hash_comment = value,
"backtickString" => self.backtick_string = value,
"numberSeparator" => self.number_separator = value,
"octal" => self.octal = value,
"binary" => self.binary = value,
"requireValue" => self.require_value = value,
"strictValue" => self.strict_value = value,
_ => unreachable!("every option key is listed"),
}
}
pub fn to_value(&self) -> Value {
let mut map = IndexMap::new();
for key in Self::KEYS {
map.insert(key.to_string(), Value::Bool(self.get(key)));
}
Value::object(map)
}
pub fn from_value(bag: &Value) -> Self {
let mut options = Self::default();
if let Value::Object(map) = bag {
for key in Self::KEYS {
if let Some(Value::Bool(value)) = map.get(key) {
options.set(key, *value);
}
}
}
options
}
pub fn from_json(bag: &JsonValue) -> Self {
Self::from_value(&Value::from_json(bag))
}
}
const GRAMMAR_TEXT: &str = r#"# JSON5 Grammar Definition
# Parsed by a standard Jsonic instance and passed to jsonic.grammar()
# Function references (@ prefixed) are resolved against the refs map
# Regex references (@/pattern/flags) are resolved to RegExp instances
# Bare identifiers (UPPER_SNAKE_CASE) are placeholders overridden by the
# plugin code before the spec is applied.
#
# This file captures the strict-JSON5 baseline. The plugin layers
# option-dependent overrides (hash comments, backtick strings, octal /
# binary / separator numbers, Infinity / NaN keywords, etc.) on top.
{
# Drop Jsonic's implicit top-level list / map alternates so `a:1` and
# `1,2` are not accepted at the document root. JSON5 requires a single
# value expression at top level.
#
# `finish: false` turns off Jsonic's auto-close of open rules at the end
# of the source: JSON5 requires every `{` / `[` to be closed, so `{a:1`
# is an error, not `{"a":1}`.
options: rule: { exclude: 'imp' finish: false }
# Restrict the token sets used by Jsonic's grammar rules:
# VAL drops #TX — reject bare unquoted text at value positions.
# KEY drops #NR — reject numeric keys like `{10: 1}`.
options: tokenSet: {
VAL: [ '#ST' '#NR' '#VL' ]
KEY: [ '#TX' '#ST' '#VL' ]
}
# Whitespace and line-terminator sets are broadened to match the JSON5
# spec (Unicode Zs, BOM, LS / PS). The actual character strings are
# supplied by the plugin because they contain code points the grammar
# parser cannot round-trip losslessly.
options: space: { chars: JSON5_WHITESPACE }
options: line: {
chars: JSON5_LINE_TERMINATOR
rowChars: JSON5_ROW_CHARS
}
# LexCheck hooks close the last gaps the built-in lexer has against
# the JSON5 spec:
# fixed.check preprocesses backslash+CRLF inside strings.
# text.check rejects unquoted text that cannot start a valid
# JSON5 IdentifierName AND is not a registered value
# keyword or regex-matched number.
# string.check rejects the escape sequences ECMAScript 5.1 forbids
# inside a string literal but the permissive lexer
# would otherwise accept (`\1`..`\9`, `\0` followed by
# a digit, and the ES2015-only `\u{...}` form).
options: fixed: { check: '@fixed-check' }
options: text: { check: '@text-check' }
# JSON5 numeric literals: allow hex, disallow octal / binary / digit
# separators. Reject JS-style leading-zero integers (`010`, `-098`).
options: number: {
lex: true
hex: true
oct: false
bin: false
sep: ''
exclude: '@/^[+-]?0[0-9]/'
}
# JSON5 comments are `//` and `/* */`. Hash comments are disabled here
# and only enabled by the plugin when the `hashComment` option is set.
options: comment: {
def: {
slash: { line: true start: '//' lex: true eatline: false }
multi: { line: false start: '/*' end: '*/' lex: true eatline: false }
hash: { line: true start: '#' lex: false eatline: false }
}
}
# JSON5 strings: single or double quote, with ES5.1 escapes plus line
# continuations (backslash + line terminator produces an empty string).
options: string: {
lex: true
check: '@string-check'
chars: JSON5_QUOTE_CHARS
multiChars: JSON5_MULTI_QUOTE_CHARS
escapeChar: '\\'
escape: {
b: '\b'
f: '\f'
n: '\n'
r: '\r'
t: '\t'
v: '\v'
'0': '\u0000'
'"': '"'
"'": "'"
'`': '`'
'\\': '\\'
'/': '/'
# JSON5 line continuation: backslash + LineTerminatorSequence.
'\n': ''
'\r': ''
'\u2028': ''
'\u2029': ''
}
allowUnknown: true
}
# Value keywords. The Infinity / NaN family is layered on by the
# plugin (because the numeric literals cannot be round-tripped through
# this grammar parser as actual JS numbers). The regex-matched
# defs pick up number shapes the built-in number lexer does not
# recognise — trailing-decimal-with-exponent (`5.e4`) and uppercase
# `0X` hex — so both TS and Go exhibit the same behaviour on those.
options: value: {
lex: true
def: {
true: { val: true }
false: { val: false }
null: { val: null }
trailingDecExp: {
match: '@/^[+-]?(?:0|[1-9][0-9]*)\\.[eE][+-]?[0-9]+/'
val: '@parse-trailing-dec-exp'
consume: true
}
uppercaseHex: {
match: '@/^[+-]?0X[0-9a-fA-F]+/'
val: '@parse-uppercase-hex'
consume: true
}
}
}
# JSON5 objects extend on duplicate keys (last wins); no bare-colon
# child syntax. Lists are strict — no named properties, pairs, or
# bare-colon children.
options: map: { extend: true child: false }
options: list: { property: false pair: false child: false }
# Reject an entirely empty source. A comments-only source is handled
# in code by dropping the `#ZZ jsonic` alternate from the val rule.
options: lex: { empty: false emptyResult: null }
options: error: {
json5_empty: 'JSON5 input must contain a value'
json5_no_value: 'JSON5 input must contain a value'
}
options: hint: {
json5_empty: 'JSON5 requires a top-level value. An empty source is not a valid JSON5 document.'
json5_no_value: 'JSON5 requires a top-level value. A source that consists only of whitespace and comments is not valid.'
}
}
"#;
fn id_start(ch: char) -> bool {
static RE: OnceLock<Regex> = OnceLock::new();
ch == '$'
|| ch == '_'
|| RE
.get_or_init(|| Regex::new(r"^[\p{L}\p{Nl}]$").expect("a literal pattern"))
.is_match(ch.encode_utf8(&mut [0; 4]))
}
fn id_part(ch: char) -> bool {
static RE: OnceLock<Regex> = OnceLock::new();
id_start(ch)
|| ch == '\u{200C}'
|| ch == '\u{200D}'
|| RE
.get_or_init(|| Regex::new(r"^[\p{Mn}\p{Mc}\p{Nd}\p{Pc}]$").expect("a literal pattern"))
.is_match(ch.encode_utf8(&mut [0; 4]))
}
fn is_identifier_start(ch: char) -> bool {
ch == '\\' || id_start(ch)
}
fn decode_identifier_name(source: &str) -> Option<String> {
if source.is_empty() {
return None;
}
let bytes = source.as_bytes();
let mut out = String::with_capacity(source.len());
let mut first = true;
let mut i = 0;
while i < bytes.len() {
let ch = if bytes[i] == b'\\' {
if i + 6 > bytes.len()
|| bytes[i + 1] != b'u'
|| !bytes[i + 2..i + 6].iter().all(u8::is_ascii_hexdigit)
{
return None;
}
let unit = u32::from_str_radix(&source[i + 2..i + 6], 16).ok()?;
if (0xD800..=0xDFFF).contains(&unit) {
return None;
}
i += 6;
char::from_u32(unit)?
} else {
let ch = source[i..].chars().next()?;
i += ch.len_utf8();
ch
};
if first {
if !id_start(ch) {
return None;
}
first = false;
} else if !id_part(ch) {
return None;
}
out.push(ch);
}
Some(out)
}
fn strip_line_continuations(src: &str, quotes: &str, esc: char, hash_comment: bool) -> String {
if !src.contains(esc) {
return src.to_string();
}
let bytes = src.as_bytes();
let mut out = String::with_capacity(src.len());
let mut i = 0;
while i < bytes.len() {
let c = src[i..].chars().next().expect("inside the source");
let size = c.len_utf8();
if c == '/' && src[i + size..].starts_with('/') {
let mut j = i + size + 1;
while j < bytes.len() {
let r = src[j..].chars().next().expect("inside the source");
if is_line_terminator(r) {
break;
}
j += r.len_utf8();
}
out.push_str(&src[i..j]);
i = j;
continue;
}
if hash_comment && c == '#' {
let mut j = i + size;
while j < bytes.len() {
let r = src[j..].chars().next().expect("inside the source");
if is_line_terminator(r) {
break;
}
j += r.len_utf8();
}
out.push_str(&src[i..j]);
i = j;
continue;
}
if c == '/' && src[i + size..].starts_with('*') {
let j = src[i + size + 1..]
.find("*/")
.map_or(bytes.len(), |end| i + size + 1 + end + 2);
out.push_str(&src[i..j]);
i = j;
continue;
}
if quotes.contains(c) {
let quote = c;
out.push(c);
i += size;
while i < bytes.len() {
let d = src[i..].chars().next().expect("inside the source");
let dsize = d.len_utf8();
if d == esc {
if i + dsize >= bytes.len() {
out.push(d);
i += dsize;
break;
}
let n = src[i + dsize..].chars().next().expect("inside the source");
let nsize = n.len_utf8();
if n == '\r' && src[i + dsize + nsize..].starts_with('\n') {
i += dsize + nsize + 1;
continue;
}
if is_line_terminator(n) {
i += dsize + nsize;
continue;
}
out.push_str(&src[i..i + dsize + nsize]);
i += dsize + nsize;
continue;
}
out.push(d);
i += dsize;
if d == quote {
break;
}
}
continue;
}
out.push(c);
i += size;
}
out
}
fn has_value(src: &str, hash_comment: bool) -> bool {
let chars: Vec<char> = src.chars().collect();
let n = chars.len();
let mut i = 0;
while i < n {
let c = chars[i];
if is_json5_space(c) {
i += 1;
continue;
}
if hash_comment && c == '#' {
i += 1;
while i < n && !is_line_terminator(chars[i]) {
i += 1;
}
continue;
}
if c == '/' && i + 1 < n {
let d = chars[i + 1];
if d == '/' {
i += 2;
while i < n && !is_line_terminator(chars[i]) {
i += 1;
}
continue;
}
if d == '*' {
let end =
(i + 2..n.saturating_sub(1)).find(|&k| chars[k] == '*' && chars[k + 1] == '/');
let Some(end) = end else {
return true; };
i = end + 2;
continue;
}
}
return true;
}
false
}
fn is_json5_space(c: char) -> bool {
c == '\u{FEFF}' || (c.is_whitespace() && c != '\u{0085}')
}
fn tag_contains(tags: &str, want: &str) -> bool {
tags.split(',').any(|tag| tag.trim() == want)
}
fn filter_tin_from_alts(alts: &mut [AltSpec], tin: Tin, required_tag: &str) {
for alt in alts.iter_mut() {
if !tag_contains(&alt.g, required_tag) {
continue;
}
for slot in alt.s.iter_mut() {
slot.retain(|t| *t != tin);
}
}
}
fn is_zz_jsonic_alt(alt: &AltSpec) -> bool {
tag_contains(&alt.g, "jsonic")
&& alt.s.len() == 1
&& alt.s[0].len() == 1
&& alt.s[0][0] == TIN_ZZ
}
fn bare_regex_source(source: &str) -> Option<&str> {
let body = source.strip_prefix("@/")?;
let slash = body.rfind('/')?;
Some(&body[..slash])
}
fn compile_serialized_regex(source: &str) -> Option<Regex> {
Regex::new(bare_regex_source(source)?).ok()
}
fn pow2(k: i64) -> f64 {
debug_assert!(k >= 0, "only non-negative exponents arise here");
if k > 1023 {
f64::INFINITY
} else {
f64::from_bits(((k + 1023) as u64) << 52)
}
}
fn digits_to_f64(digits: &[u32], bits: u32) -> f64 {
let start = digits.iter().position(|digit| *digit != 0);
let Some(start) = start else {
return 0.0;
};
let digits = &digits[start..];
let head_len = (128 / bits) as usize;
let pack = |run: &[u32]| {
run.iter()
.fold(0u128, |value, digit| (value << bits) | u128::from(*digit))
};
if digits.len() <= head_len {
return pack(digits) as f64;
}
let head = pack(&digits[..head_len]);
let tail = &digits[head_len..];
let dropped = i64::from(bits) * tail.len() as i64;
let shift = 128 - head.leading_zeros() - 53;
let mut mantissa = (head >> shift) as u64;
let half = (head >> (shift - 1)) & 1 == 1;
let sticky = head & ((1u128 << (shift - 1)) - 1) != 0 || tail.iter().any(|digit| *digit != 0);
if half && (sticky || mantissa & 1 == 1) {
mantissa += 1;
}
mantissa as f64 * pow2(dropped + i64::from(shift))
}
fn radix_literal_value(src: &str, separator: Option<char>) -> Option<f64> {
let (negative, rest) = match src.strip_prefix('-') {
Some(rest) => (true, rest),
None => (false, src.strip_prefix('+').unwrap_or(src)),
};
let rest = rest.strip_prefix('0')?;
let mut characters = rest.chars();
let bits = match characters.next()? {
'x' | 'X' => 4,
'o' | 'O' => 3,
'b' | 'B' => 1,
_ => return None,
};
let base = 1u32 << bits;
let mut digits = Vec::new();
for character in characters {
if Some(character) == separator {
continue;
}
digits.push(character.to_digit(base)?);
}
if digits.is_empty() {
return None;
}
let magnitude = digits_to_f64(&digits, bits);
Some(if negative { -magnitude } else { magnitude })
}
const FIXED_CHECK: &str = "@fixed-check";
const TEXT_CHECK: &str = "@text-check";
const STRING_CHECK: &str = "@string-check";
const PARSE_TRAILING_DEC_EXP: &str = "@parse-trailing-dec-exp";
const PARSE_UPPERCASE_HEX: &str = "@parse-uppercase-hex";
const PAIR_KEY_CHECK: &str = "@json5-pair-key";
fn pair_key_check(
rule: &mut Rule,
_context: &mut Context,
_next: Option<&RuleSnapshot>,
out: Option<Token>,
) -> Result<Option<Token>, ActionError> {
let Some(token) = rule.o0().filter(|token| token.tin == TIN_TX) else {
return Ok(out);
};
let Some(name) = decode_identifier_name(token.src.as_str()) else {
let mut bad = token.clone();
bad.bad("unexpected");
return Ok(Some(bad));
};
if token.val != Value::String(name.clone()) {
Rc::make_mut(&mut rule.o)[0].val = Value::String(name.clone());
rule.u_mut().insert("key".to_string(), Value::String(name));
}
Ok(out)
}
fn grammar_document(options: &Json5Options) -> Result<JsonValue, PluginError> {
let parsed = tabnas_jsonic::make().parse(GRAMMAR_TEXT).map_err(|error| {
PluginError(format!(
"json5: the embedded grammar does not parse: {error}"
))
})?;
let mut document = parsed.to_json();
if !document.get("options").is_some_and(JsonValue::is_object) {
return Err(PluginError(
"json5: the embedded grammar has no `options` table".into(),
));
}
let opts = &mut document["options"];
opts["space"]["chars"] = json!(JSON5_WHITESPACE);
opts["line"]["chars"] = json!(JSON5_LINE_CHARS);
opts["line"]["fixed"] = json!(JSON5_LINE_FIXED);
opts["line"]["rowChars"] = json!(JSON5_ROW_CHARS);
if options.backtick_string {
opts["string"]["chars"] = json!("'\"`");
opts["string"]["multiChars"] = json!("`");
} else {
opts["string"]["chars"] = json!("'\"");
opts["string"]["multiChars"] = json!("");
}
opts["number"]["hex"] = json!(options.hex);
opts["number"]["oct"] = json!(options.octal);
opts["number"]["bin"] = json!(options.binary);
opts["number"]["sep"] = if options.number_separator {
json!("_")
} else {
JsonValue::Null
};
opts["comment"]["def"]["hash"]["lex"] = json!(options.hash_comment);
opts["lex"]["empty"] = json!(!options.require_value);
if let Some(exclude) = opts["number"]["exclude"].as_str() {
if let Some(bare) = bare_regex_source(exclude) {
opts["number"]["exclude"] = json!(bare);
}
}
if !options.strict_value {
if let Some(sets) = opts["tokenSet"].as_object_mut() {
sets.shift_remove("VAL");
}
}
Ok(document)
}
const INFINITY_DEFINITIONS: [(&str, f64); 6] = [
("Infinity", f64::INFINITY),
("+Infinity", f64::INFINITY),
("-Infinity", f64::NEG_INFINITY),
("NaN", f64::NAN),
("+NaN", f64::NAN),
("-NaN", f64::NAN),
];
fn value_definitions(document: &JsonValue, options: &Json5Options) -> (Vec<String>, Vec<Regex>) {
let mut names = Vec::new();
let mut regexes = Vec::new();
if let Some(defs) = document["options"]["value"]["def"].as_object() {
for (name, def) in defs {
match def.get("match").and_then(JsonValue::as_str) {
Some(source) => regexes.extend(compile_serialized_regex(source)),
None => names.push(name.clone()),
}
}
}
if options.infinity {
names.extend(
INFINITY_DEFINITIONS
.iter()
.map(|(name, _)| name.to_string()),
);
}
(names, regexes)
}
fn null_keywords(document: &JsonValue) -> Vec<String> {
document["options"]["value"]["def"]
.as_object()
.map(|defs| {
defs.iter()
.filter(|(_, def)| def.get("val").is_some_and(JsonValue::is_null))
.map(|(name, _)| name.clone())
.collect()
})
.unwrap_or_default()
}
pub fn json5(parser: &mut Tabnas, options: &Json5Options) -> Result<(), PluginError> {
let options = *options;
let document = grammar_document(&options)?;
let (value_names, value_regexes) = value_definitions(&document, &options);
let null_keywords = null_keywords(&document);
parser.lex_check_ref(FIXED_CHECK, |_| LexCheckResult::Continue);
parser.lex_check_ref(TEXT_CHECK, move |remaining: &str| {
let Some(first) = remaining.chars().next() else {
return LexCheckResult::Continue;
};
if is_identifier_start(first)
|| value_names
.iter()
.any(|name| remaining.starts_with(name.as_str()))
|| value_regexes.iter().any(|regex| regex.is_match(remaining))
{
LexCheckResult::Continue
} else {
LexCheckResult::Skip
}
});
let quotes = document["options"]["string"]["chars"]
.as_str()
.unwrap_or("'\"")
.to_string();
parser.lex_check_ref(STRING_CHECK, move |remaining: &str| {
let bytes = remaining.as_bytes();
let Some(quote) = remaining
.chars()
.next()
.filter(|quote| quotes.contains(*quote))
else {
return LexCheckResult::Continue;
};
let mut i = quote.len_utf8();
while i < bytes.len() {
let c = remaining[i..].chars().next().expect("inside the source");
let size = c.len_utf8();
if c == quote {
break;
}
if c != '\\' {
i += size;
continue;
}
if i + size >= bytes.len() {
break;
}
let next = bytes[i + size];
let after = bytes.get(i + size + 1).copied().unwrap_or(0);
if next.is_ascii_digit() && (next != b'0' || after.is_ascii_digit())
|| (next == b'u' && after == b'{')
{
return LexCheckResult::Skip;
}
let escaped = remaining[i + size..].chars().next().expect("checked above");
i += size + escaped.len_utf8();
}
LexCheckResult::Continue
});
parser.value_transform_ref(PARSE_TRAILING_DEC_EXP, |groups: &[String]| {
let literal = groups.first().map(String::as_str).unwrap_or_default();
let (mantissa, exponent) = literal.split_once(['e', 'E']).unwrap_or((literal, "0"));
Value::Number(
format!("{}e{exponent}", mantissa.trim_end_matches('.'))
.parse()
.unwrap_or(f64::NAN),
)
});
parser.value_transform_ref(PARSE_UPPERCASE_HEX, |groups: &[String]| {
let literal = groups.first().map(String::as_str).unwrap_or_default();
Value::Number(radix_literal_value(literal, None).unwrap_or(f64::NAN))
});
parser.state_action_with_next_ref(PAIR_KEY_CHECK, pair_key_check);
let spec = tabnas::GrammarSpec::from_value(document).map_err(|error| PluginError(error.0))?;
parser
.grammar(&spec)
.map_err(|error| PluginError(error.0))?;
parser
.set_options(|o| {
for name in &null_keywords {
if let Some(def) = o.value.definitions.get_mut(name) {
def.val = Some(Value::Null);
}
}
if options.infinity {
for (name, value) in INFINITY_DEFINITIONS {
o.value.definitions.insert(
name.to_string(),
ValueDef {
val: Some(Value::Number(value)),
matcher: None,
transform: None,
consume: false,
},
);
}
}
})
.map_err(|error| PluginError(error.0))?;
for name in parser.rule_names() {
parser.define_rule(name, |spec| {
if options.strict_value {
filter_tin_from_alts(&mut spec.open, TIN_TX, "val");
filter_tin_from_alts(&mut spec.close, TIN_TX, "val");
}
filter_tin_from_alts(&mut spec.open, TIN_NR, "pair");
filter_tin_from_alts(&mut spec.close, TIN_NR, "pair");
});
}
parser.define_rule("pair", |spec| {
spec.open
.retain(|alt| !(tag_contains(&alt.g, "comma") && tag_contains(&alt.g, "jsonic")));
if !spec.ao.iter().any(|action| action == PAIR_KEY_CHECK) {
spec.ao.push(PAIR_KEY_CHECK.to_string());
}
});
if options.require_value {
parser.define_rule("val", |spec| {
spec.open.retain(|alt| !is_zz_jsonic_alt(alt));
});
}
parser.decorate(OPTIONS_MARK, options);
Ok(())
}
pub fn plugin() -> Plugin {
Plugin::new(PLUGIN_NAME, |parser, options| {
json5(parser, &Json5Options::from_value(options))
})
.with_defaults(Json5Options::default().to_value())
}
pub fn make_with(options: Json5Options) -> Tabnas {
let mut parser = tabnas_jsonic::make();
parser
.use_plugin(plugin(), Some(options.to_value()))
.expect("the json5 grammar is fixed and valid");
parser
}
pub fn make() -> Tabnas {
make_with(Json5Options::default())
}
fn value_error(parser: &Tabnas, code: &str, src: &str) -> Json5Error {
let mut error = Json5Error::new(code, "", src, 0, 1, 1);
let config = parser.config();
error.detail = config
.error
.get(code)
.cloned()
.unwrap_or_else(|| "JSON5 input must contain a value".to_string());
error.hint = config.hint.get(code).cloned().unwrap_or_default();
error
}
pub fn parse_with(parser: &Tabnas, src: &str) -> Result<Value, Json5Error> {
let Some(options) = parser.decoration::<Json5Options>(OPTIONS_MARK).copied() else {
return parser.parse(src);
};
if options.require_value {
if src.is_empty() {
return Err(value_error(parser, "json5_empty", src));
}
if !has_value(src, false) {
return Err(value_error(parser, "json5_no_value", src));
}
} else if !src.is_empty() && !has_value(src, options.hash_comment) {
return parser.parse("");
}
let quotes = if options.backtick_string {
"'\"`"
} else {
"'\""
};
let rewritten = strip_line_continuations(src, quotes, '\\', options.hash_comment);
parser.parse(&rewritten)
}
pub fn parse(src: &str) -> Result<Value, Json5Error> {
static DEFAULT: OnceLock<Tabnas> = OnceLock::new();
parse_with(DEFAULT.get_or_init(make), src)
}