#![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, Lexer, Plugin, PluginError, Rule, RuleSnapshot,
Tabnas, Tin, Token, Value, ValueDef, TIN_NR, TIN_ST, TIN_TX, TIN_ZZ,
};
pub const VERSION: &str = "0.5.18";
#[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 reads a string literal that holds a line continuation
# (a backslash and a LineTerminatorSequence), which the
# escape map cannot express, where it stands, so every
# row, column and offset after it is the source's own.
# 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. A line
# continuation (backslash + LineTerminatorSequence, which produces the
# empty string) has no entry here: an entry is keyed by one character,
# which cannot spell CRLF, and the TypeScript and Go lexers take an
# empty replacement as no entry at all. A string holding one is read by
# fixed.check instead.
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'
'"': '"'
"'": "'"
'`': '`'
'\\': '\\'
'/': '/'
}
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)
}
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
struct StringEscapes {
forbidden: bool,
continued: bool,
}
fn scan_string_escapes(remaining: &str, quote: char) -> (StringEscapes, Option<usize>) {
let bytes = remaining.as_bytes();
let mut found = StringEscapes::default();
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 {
return (found, Some(i + size));
}
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);
let escaped = remaining[i + size..].chars().next().expect("checked above");
if next.is_ascii_digit() && (next != b'0' || after.is_ascii_digit())
|| (next == b'u' && after == b'{')
{
found.forbidden = true;
} else if is_line_terminator(escaped) {
found.continued = true;
}
i += size + escaped.len_utf8();
}
(found, None)
}
fn read_on(lexer: &mut Lexer<'_>, held: usize) -> bool {
let before = lexer.window().len();
lexer.fill(held.saturating_mul(2).max(held + 1));
lexer.window().len() > before
}
fn scan_string_at(lexer: &mut Lexer<'_>, quote: char) -> (StringEscapes, usize) {
loop {
let window = lexer.window();
let (found, closed) = scan_string_escapes(window, quote);
if let Some(end) = closed {
return (found, window[..end].chars().count());
}
let held = window.chars().count();
if !read_on(lexer, held) {
return (found, held);
}
}
}
fn is_number_char(byte: u8) -> bool {
byte.is_ascii_alphanumeric() || matches!(byte, b'+' | b'-' | b'.')
}
fn hold_text(lexer: &mut Lexer<'_>) {
loop {
let window = lexer.window();
let run = window
.bytes()
.take_while(|byte| is_number_char(*byte))
.count();
if run < window.len() || !read_on(lexer, run) {
return;
}
}
}
#[derive(Debug, Clone)]
struct StringSyntax {
quotes: String,
multi_line: String,
escape: Vec<(char, String)>,
allow_unknown: bool,
escape_strict: bool,
allow_control: bool,
}
impl StringSyntax {
fn from_document(document: &JsonValue) -> Self {
let string = &document["options"]["string"];
let text = |key: &str| string[key].as_str().unwrap_or_default().to_string();
let flag = |key: &str| string[key].as_bool().unwrap_or(false);
let escape = string["escape"]
.as_object()
.map(|map| {
map.iter()
.filter_map(|(key, replacement)| {
let mut chars = key.chars();
match (chars.next(), chars.next(), replacement.as_str()) {
(Some(ch), None, Some(text)) => Some((ch, text.to_string())),
_ => None,
}
})
.collect()
})
.unwrap_or_default();
StringSyntax {
quotes: text("chars"),
multi_line: text("multiChars"),
escape,
allow_unknown: flag("allowUnknown"),
escape_strict: flag("escapeStrict"),
allow_control: flag("allowControl"),
}
}
fn escape(&self, ch: char) -> Option<&str> {
self.escape
.iter()
.find(|(key, _)| *key == ch)
.map(|(_, replacement)| replacement.as_str())
}
}
enum ContinuedString {
Read {
value: String,
chars: usize,
bytes: usize,
},
Bad {
why: &'static str,
at: usize,
len: usize,
},
Unterminated,
}
fn read_continued_string(lexer: &mut Lexer<'_>, syntax: &StringSyntax) -> LexCheckResult {
let Some(quote) = lexer
.window()
.chars()
.next()
.filter(|quote| syntax.quotes.contains(*quote))
else {
return LexCheckResult::Continue;
};
let (found, through) = scan_string_at(lexer, quote);
if !found.continued {
return LexCheckResult::Continue;
}
if found.forbidden {
return LexCheckResult::native_token(lexer.bad("unexpected"));
}
lexer.fill(through + MAX_ESCAPE_CHARS);
let start = lexer.point();
let remaining = lexer.window();
match decode_continued_string(remaining, quote, syntax) {
ContinuedString::Read {
value,
chars,
bytes,
} => {
let source = remaining[..bytes].to_string();
lexer.advance_chars(chars);
LexCheckResult::native_token(lexer.token(
"#ST",
TIN_ST,
Value::String(value),
source,
start,
))
}
ContinuedString::Bad { why, at, len } => {
lexer.advance_chars(at);
let site = start.site.pos + at;
LexCheckResult::native_token(lexer.bad_span(why, site, site + len))
}
ContinuedString::Unterminated => {
let len = remaining.chars().count();
let site = start.site.pos;
LexCheckResult::native_token(lexer.bad_span("unterminated_string", site, site + len))
}
}
}
const MAX_ESCAPE_CHARS: usize = 6;
fn decode_continued_string(remaining: &str, quote: char, syntax: &StringSyntax) -> ContinuedString {
let multi_line = syntax.multi_line.contains(quote);
let next = |at: usize| remaining[at..].chars().next();
let span = |from: usize, len: usize| remaining[from..].chars().take(len).count();
let mut value = String::new();
let mut pending = None;
let mut i = quote.len_utf8();
let mut at = 1;
while let Some(c) = next(i) {
if c == quote {
flush_surrogate(&mut pending, &mut value);
return ContinuedString::Read {
value,
chars: at + 1,
bytes: i + c.len_utf8(),
};
}
if c == '\\' {
let Some(n) = next(i + 1) else {
break;
};
let body = i + 1 + n.len_utf8();
if is_line_terminator(n) {
if n == '\r' && remaining[body..].starts_with('\n') {
i = body + 1;
at += 3;
} else {
i = body;
at += 2;
}
continue;
}
if n != 'u' {
flush_surrogate(&mut pending, &mut value);
}
if let Some(replacement) = syntax.escape(n) {
value.push_str(replacement);
i = body;
at += 2;
continue;
}
if n == 'u' {
let Some(unit) = hex_digits(&remaining[body..], 4) else {
return ContinuedString::Bad {
why: "invalid_unicode",
at,
len: span(i, 6),
};
};
emit_code_unit(unit, &mut pending, &mut value);
i = body + 4;
at += 6;
continue;
}
if n == 'x' && !syntax.escape_strict {
let Some(byte) = hex_digits(&remaining[body..], 2) else {
return ContinuedString::Bad {
why: "invalid_ascii",
at,
len: span(i, 4),
};
};
value.push(char::from_u32(byte).expect("two hex digits are a scalar"));
i = body + 2;
at += 4;
continue;
}
if !syntax.allow_unknown {
return ContinuedString::Bad {
why: "unexpected",
at: at + 1,
len: 1,
};
}
value.push(n);
i = body;
at += 2;
continue;
}
let unprintable = if c == '\r' || c == '\n' {
!multi_line
} else {
(c as u32) < 32 && !syntax.allow_control
};
if unprintable {
return ContinuedString::Bad {
why: "unprintable",
at,
len: 1,
};
}
flush_surrogate(&mut pending, &mut value);
value.push(c);
i += c.len_utf8();
at += 1;
}
ContinuedString::Unterminated
}
fn hex_digits(text: &str, count: usize) -> Option<u32> {
let digits = text.get(..count)?;
if !digits.bytes().all(|byte| byte.is_ascii_hexdigit()) {
return None;
}
u32::from_str_radix(digits, 16).ok()
}
fn emit_code_unit(unit: u32, pending: &mut Option<u32>, out: &mut String) {
if (0xD800..=0xDBFF).contains(&unit) {
flush_surrogate(pending, out);
*pending = Some(unit);
} else if (0xDC00..=0xDFFF).contains(&unit) {
match pending.take() {
Some(high) => out.push(
char::from_u32(0x10000 + ((high - 0xD800) << 10) + (unit - 0xDC00))
.expect("paired surrogates form a Unicode scalar"),
),
None => out.push('\u{FFFD}'),
}
} else {
flush_surrogate(pending, out);
out.push(
char::from_u32(unit).expect("four hex digits outside the surrogates are a scalar"),
);
}
}
fn flush_surrogate(pending: &mut Option<u32>, out: &mut String) {
if pending.take().is_some() {
out.push('\u{FFFD}');
}
}
fn has_value(src: &str, hash_comment: bool) -> bool {
ValueScan::default().scan(src.as_bytes(), true, hash_comment) != Verdict::NoValue
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum Verdict {
More,
Value,
NoValue,
}
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
enum Within {
#[default]
Space,
Line,
Block,
}
#[derive(Debug, Clone, Copy, Default)]
struct ValueScan {
at: usize,
within: Within,
}
fn first_char(bytes: &[u8], end: bool) -> Option<(char, usize)> {
let head = &bytes[..bytes.len().min(4)];
let valid = match std::str::from_utf8(head) {
Ok(text) => text,
Err(error) if error.valid_up_to() > 0 => {
std::str::from_utf8(&head[..error.valid_up_to()]).expect("the prefix is UTF-8")
}
Err(error) if error.error_len().is_none() && !end => return None,
Err(_) => return Some(('\u{FFFD}', 1)),
};
let c = valid.chars().next().expect("a character");
Some((c, c.len_utf8()))
}
impl ValueScan {
fn scan(&mut self, src: &[u8], end: bool, hash_comment: bool) -> Verdict {
let n = src.len();
let more = if end { Verdict::NoValue } else { Verdict::More };
loop {
match self.within {
Within::Line => {
while self.at < n {
let Some((c, size)) = first_char(&src[self.at..], end) else {
return Verdict::More;
};
if is_line_terminator(c) {
break;
}
self.at += size;
}
if self.at >= n {
return more;
}
self.within = Within::Space;
}
Within::Block => {
match src[self.at..].windows(2).position(|pair| pair == b"*/") {
Some(k) => {
self.at += k + 2;
self.within = Within::Space;
}
None if end => return Verdict::Value, None => {
self.at = self.at.max(n.saturating_sub(1));
return Verdict::More;
}
}
}
Within::Space => {
if self.at >= n {
return more;
}
let Some((c, size)) = first_char(&src[self.at..], end) else {
return Verdict::More;
};
if is_json5_space(c) {
self.at += size;
continue;
}
if hash_comment && c == '#' {
self.at += 1;
self.within = Within::Line;
continue;
}
if c == '/' {
match src.get(self.at + 1) {
None if !end => return Verdict::More,
Some(b'/') => {
self.at += 2;
self.within = Within::Line;
continue;
}
Some(b'*') => {
self.at += 2;
self.within = Within::Block;
continue;
}
_ => {}
}
}
return Verdict::Value;
}
}
}
}
}
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);
let syntax = StringSyntax::from_document(&document);
parser.imperative_lex_check_ref(FIXED_CHECK, move |lexer: &mut Lexer<'_>| {
match lexer.window().chars().next() {
Some(first) if !syntax.quotes.contains(first) && !is_identifier_start(first) => {
hold_text(lexer);
LexCheckResult::Continue
}
_ => read_continued_string(lexer, &syntax),
}
});
parser.imperative_lex_check_ref(TEXT_CHECK, move |lexer: &mut Lexer<'_>| {
let Some(first) = lexer.window().chars().next() else {
return LexCheckResult::Continue;
};
if is_identifier_start(first) {
return LexCheckResult::Continue;
}
hold_text(lexer);
let remaining = lexer.window();
if 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.imperative_lex_check_ref(STRING_CHECK, move |lexer: &mut Lexer<'_>| {
match lexer
.window()
.chars()
.next()
.filter(|quote| quotes.contains(*quote))
{
Some(quote) if scan_string_at(lexer, quote).0.forbidden => LexCheckResult::Skip,
_ => 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
.set_options(|options| options.lex.window = true)
.expect("lex.window sets");
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("");
}
parser.parse(src)
}
pub struct Checked<R> {
read: std::io::Cursor<Vec<u8>>,
failure: Option<std::io::Error>,
rest: Option<R>,
}
impl<R: std::io::Read> std::io::Read for Checked<R> {
fn read(&mut self, buf: &mut [u8]) -> std::io::Result<usize> {
let n = self.read.read(buf)?;
if n > 0 || buf.is_empty() {
return Ok(n);
}
if let Some(failure) = self.failure.take() {
return Err(failure);
}
match &mut self.rest {
Some(rest) => rest.read(buf),
None => Ok(0),
}
}
}
pub fn check_reader<R: std::io::Read>(
parser: &Tabnas,
mut reader: R,
) -> Result<Checked<R>, Json5Error> {
let checked = |read: Vec<u8>, failure, rest| Checked {
read: std::io::Cursor::new(read),
failure,
rest,
};
let require_value = parser
.decoration::<Json5Options>(OPTIONS_MARK)
.is_some_and(|options| options.require_value);
if !require_value {
return Ok(checked(Vec::new(), None, Some(reader)));
}
let mut read = Vec::new();
let mut scan = ValueScan::default();
let mut buf = [0u8; 512];
loop {
let n = match reader.read(&mut buf) {
Ok(n) => n,
Err(error) if error.kind() == std::io::ErrorKind::Interrupted => continue,
Err(error) => return Ok(checked(read, Some(error), None)),
};
read.extend_from_slice(&buf[..n]);
let end = n == 0;
match scan.scan(&read, end, false) {
Verdict::More => {}
Verdict::Value => return Ok(checked(read, None, (!end).then_some(reader))),
Verdict::NoValue => {
let Ok(text) = std::str::from_utf8(&read) else {
return Ok(checked(read, None, None));
};
let code = if text.is_empty() {
"json5_empty"
} else {
"json5_no_value"
};
return Err(value_error(parser, code, text));
}
}
}
}
pub fn parse_reader_with(parser: &Tabnas, reader: impl std::io::Read) -> Result<Value, Json5Error> {
let checked = check_reader(parser, reader)?;
parser.parse_reader(checked)
}
pub fn parse(src: &str) -> Result<Value, Json5Error> {
static DEFAULT: OnceLock<Tabnas> = OnceLock::new();
parse_with(DEFAULT.get_or_init(make), src)
}
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub struct TranslationPart {
pub entry: &'static str,
pub source: Option<&'static str>,
}
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub struct TranslationParts {
pub manifest: &'static str,
pub lift: Option<TranslationPart>,
pub embed: Option<TranslationPart>,
pub render: Option<TranslationPart>,
pub transduce: Option<TranslationPart>,
}
const TRANSLATION: TranslationParts = TranslationParts {
manifest: include_str!("../translate/manifest.json"),
lift: None,
embed: None,
render: Some(TranslationPart {
entry: "json5-render",
source: Some(include_str!("../translate/render.alc")),
}),
transduce: Some(TranslationPart {
entry: "json5-transduce",
source: Some(include_str!("../translate/transduce.alc")),
}),
};
#[must_use]
pub const fn translate() -> Option<TranslationParts> {
Some(TRANSLATION)
}
pub fn manifest_text() -> &'static str {
TRANSLATION.manifest
}
pub fn render_text() -> &'static str {
match TRANSLATION.render {
Some(part) => part.source.unwrap_or_default(),
None => "",
}
}