Skip to main content

tabnas_json5/
lib.rs

1// Copyright (c) 2021-2026 Richard Rodger and other contributors, MIT License
2
3// The engine's error carries a code, position, hint and a formatted
4// report, so it is large by design and `Result<_, TabnasError>` trips
5// clippy's `result_large_err`. The engine allows the lint at its own
6// crate root for the same reason; boxing here would make `parse` return
7// a different shape from `Tabnas::parse` and from the other two ports.
8#![allow(clippy::result_large_err)]
9
10//! The JSON5 grammar plugin for the `tabnas` parsing engine.
11//!
12//! JSON5 is JSON plus comments, unquoted keys, trailing commas, single
13//! quotes, hex numbers, `Infinity` and `NaN`, leading and trailing
14//! decimal points, explicit `+` signs, and string line continuations.
15//! The plugin layers on the relaxed-JSON base grammar of
16//! [`tabnas_jsonic`] and then TIGHTENS it toward the JSON5 specification:
17//! no implicit top-level `a:1` or `1,2`, no auto-close at the end of the
18//! source, no unquoted text at a value position, and only ECMAScript 5.1
19//! `IdentifierName`s as unquoted keys.
20//!
21//! ```
22//! let value = tabnas_json5::parse("{ a: 1, b: [2, 3,], }")?;
23//! assert_eq!(value.to_string(), r#"{"a":1,"b":[2,3]}"#);
24//! # Ok::<(), tabnas_json5::Json5Error>(())
25//! ```
26//!
27//! TypeScript is canonical: `ts/src/json5.ts` and the shared
28//! `json5-grammar.jsonic` define behaviour and option defaults. The
29//! shared fixtures in `test/spec/*.tsv` and the vendored
30//! `test/json5-tests` corpus are the parity contract across TypeScript,
31//! Go and Rust.
32
33use std::rc::Rc;
34use std::sync::OnceLock;
35
36use indexmap::IndexMap;
37use regex::Regex;
38use serde_json::{json, Value as JsonValue};
39use tabnas::{
40    ActionError, AltSpec, Context, LexCheckResult, Lexer, Plugin, PluginError, Rule, RuleSnapshot,
41    Tabnas, Tin, Token, Value, ValueDef, TIN_NR, TIN_ST, TIN_TX, TIN_ZZ,
42};
43
44/// This crate's version. It MUST equal `ts/package.json` "version": the
45/// release orchestrator rewrites both, and `tests/version_test.rs` fails
46/// the build if they drift. Mirrors `VERSION` in `ts/src/json5.ts` and
47/// `const VERSION` in `go/json5.go`.
48pub const VERSION: &str = "0.5.13";
49
50/// The README's Rust examples run as doctests, so a stale one fails the
51/// gate rather than misleading the reader. Its `toml` and `bash` fences
52/// are skipped; rustdoc runs only the `rust` ones.
53#[cfg(doctest)]
54#[doc = include_str!("../README.md")]
55mod readme_examples {}
56
57/// The error a failed parse produces, re-exported so callers need not
58/// depend on the engine crate directly. The Go port returns the same
59/// `*jsonic.JsonicError`.
60pub use tabnas::TabnasError as Json5Error;
61
62/// The name the plugin registers under, and so the namespace of its
63/// option bag on the engine.
64const PLUGIN_NAME: &str = "json5";
65
66/// The decoration under which the resolved options are recorded on the
67/// instance, so [`parse_with`] can apply the `requireValue` rule. The Go
68/// port's `json5$requireValue`.
69const OPTIONS_MARK: &str = "json5$options";
70
71// ---------------------------------------------------------------------------
72// The JSON5 character classes.
73// ---------------------------------------------------------------------------
74
75/// JSON5 WhiteSpace: HT, VT, FF, SP, NBSP, BOM, and the Unicode Zs
76/// category characters the specification enumerates.
77const 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}";
78
79/// The JSON5 LineTerminator set is LF, CR, LS and PS. TypeScript and Go
80/// write all four into `line.chars`; this port splits them in two,
81/// because this engine reads the halves differently.
82///
83/// Both halves end a line everywhere a line can end, because the engine
84/// asks `line.chars` PLUS `line.fixed` for that. The one place that asks
85/// `line.chars` alone is the string lexer's unprintable test, and JSON5
86/// admits an unescaped U+2028 or U+2029 inside a string literal (JSON5
87/// 5.2: a `JSON5DoubleStringCharacter` is any `SourceCharacter` but a
88/// quote, a backslash or a `LineTerminator`, plus `LineContinuation`,
89/// plus U+2028 and U+2029). TypeScript reaches the same answer by its
90/// own route: `buildStringBodySpec` in the engine's `lexer.ts` tabulates
91/// the code points below 256 and falls back for the rest, and the
92/// fallback treats a line character as ordinary body unless the string
93/// is multi-line. Go accepts them too. Putting LS and PS in
94/// `line.fixed` is what makes this engine agree with both, and the rows
95/// in `../test/spec/strings.tsv` execute the agreement in all three.
96const JSON5_LINE_CHARS: &str = "\r\n";
97/// The other half of the JSON5 LineTerminator set: see
98/// [`JSON5_LINE_CHARS`].
99const JSON5_LINE_FIXED: &str = "\u{2028}\u{2029}";
100
101/// The line terminators that bump the row counter: LF, LS, PS. CR is
102/// folded into the following LF for CRLF.
103const JSON5_ROW_CHARS: &str = "\n\u{2028}\u{2029}";
104
105fn is_line_terminator(ch: char) -> bool {
106    matches!(ch, '\n' | '\r' | '\u{2028}' | '\u{2029}')
107}
108
109// ---------------------------------------------------------------------------
110// Options
111// ---------------------------------------------------------------------------
112
113/// The plugin options: a strict JSON5 configuration by default, with the
114/// relaxations jsonic offers beyond the specification opt-in. The
115/// TypeScript `Json5Options` and the Go `Defaults()` map.
116///
117/// On the engine the options travel as a [`Value`] bag under the plugin
118/// name, spelt with the TypeScript keys (`hashComment`, `requireValue`,
119/// ...); [`Json5Options::to_value`] and [`Json5Options::from_value`]
120/// convert, and a key the bag does not carry keeps its default, as the
121/// Go `optBool` does.
122#[derive(Debug, Clone, Copy, PartialEq, Eq)]
123pub struct Json5Options {
124    /// Accept `Infinity`, `NaN` and their signed forms as numbers.
125    pub infinity: bool,
126    /// Accept `0x` hexadecimal integers.
127    pub hex: bool,
128    /// Accept `#` line comments (not JSON5).
129    pub hash_comment: bool,
130    /// Accept backtick-quoted strings (not JSON5).
131    pub backtick_string: bool,
132    /// Accept `_` digit separators in numbers (not JSON5).
133    pub number_separator: bool,
134    /// Accept `0o` octal integers (not JSON5).
135    pub octal: bool,
136    /// Accept `0b` binary integers (not JSON5).
137    pub binary: bool,
138    /// Require a top-level value: an empty, whitespace-only or
139    /// comments-only source is an error (`json5_empty`,
140    /// `json5_no_value`) rather than a `null` result.
141    pub require_value: bool,
142    /// Reject unquoted text at a value position, so `foo` is an error
143    /// rather than the string `"foo"`.
144    pub strict_value: bool,
145}
146
147impl Default for Json5Options {
148    fn default() -> Self {
149        Self {
150            infinity: true,
151            hex: true,
152            hash_comment: false,
153            backtick_string: false,
154            number_separator: false,
155            octal: false,
156            binary: false,
157            require_value: true,
158            strict_value: true,
159        }
160    }
161}
162
163impl Json5Options {
164    /// The option keys as the TypeScript plugin and the Go `Defaults()`
165    /// map spell them: the keys [`Json5Options::to_value`] writes and
166    /// [`Json5Options::from_value`] reads.
167    pub const KEYS: [&str; 9] = [
168        "infinity",
169        "hex",
170        "hashComment",
171        "backtickString",
172        "numberSeparator",
173        "octal",
174        "binary",
175        "requireValue",
176        "strictValue",
177    ];
178
179    fn get(&self, key: &str) -> bool {
180        match key {
181            "infinity" => self.infinity,
182            "hex" => self.hex,
183            "hashComment" => self.hash_comment,
184            "backtickString" => self.backtick_string,
185            "numberSeparator" => self.number_separator,
186            "octal" => self.octal,
187            "binary" => self.binary,
188            "requireValue" => self.require_value,
189            "strictValue" => self.strict_value,
190            _ => unreachable!("every option key is listed"),
191        }
192    }
193
194    fn set(&mut self, key: &str, value: bool) {
195        match key {
196            "infinity" => self.infinity = value,
197            "hex" => self.hex = value,
198            "hashComment" => self.hash_comment = value,
199            "backtickString" => self.backtick_string = value,
200            "numberSeparator" => self.number_separator = value,
201            "octal" => self.octal = value,
202            "binary" => self.binary = value,
203            "requireValue" => self.require_value = value,
204            "strictValue" => self.strict_value = value,
205            _ => unreachable!("every option key is listed"),
206        }
207    }
208
209    /// The options as the engine's plugin-option bag, keyed as the
210    /// TypeScript plugin spells them.
211    pub fn to_value(&self) -> Value {
212        let mut map = IndexMap::new();
213        for key in Self::KEYS {
214            map.insert(key.to_string(), Value::Bool(self.get(key)));
215        }
216        Value::object(map)
217    }
218
219    /// Read a plugin-option bag. A key that is absent, or not a boolean,
220    /// keeps its default, as the Go port's `optBool` does.
221    pub fn from_value(bag: &Value) -> Self {
222        let mut options = Self::default();
223        if let Value::Object(map) = bag {
224            for key in Self::KEYS {
225                if let Some(Value::Bool(value)) = map.get(key) {
226                    options.set(key, *value);
227                }
228            }
229        }
230        options
231    }
232
233    /// Read a JSON option object, the form the shared fixtures' `opts`
234    /// column and the TypeScript tests use.
235    pub fn from_json(bag: &JsonValue) -> Self {
236        Self::from_value(&Value::from_json(bag))
237    }
238}
239
240// ---------------------------------------------------------------------------
241// The embedded grammar.
242//
243// Authored ONCE in `../json5-grammar.jsonic` and embedded into every
244// runtime by `ts/embed-grammar.js`. Never hand-edit the text between the
245// markers: edit the `.jsonic` file and re-run the embed. The text is
246// jsonic, not JSON, and is parsed at plugin-install time by a standard
247// jsonic instance, exactly as the TypeScript and Go ports parse it.
248// ---------------------------------------------------------------------------
249
250// --- BEGIN EMBEDDED json5-grammar.jsonic ---
251const GRAMMAR_TEXT: &str = r#"# JSON5 Grammar Definition
252# Parsed by a standard Jsonic instance and passed to jsonic.grammar()
253# Function references (@ prefixed) are resolved against the refs map
254# Regex references (@/pattern/flags) are resolved to RegExp instances
255# Bare identifiers (UPPER_SNAKE_CASE) are placeholders overridden by the
256# plugin code before the spec is applied.
257#
258# This file captures the strict-JSON5 baseline. The plugin layers
259# option-dependent overrides (hash comments, backtick strings, octal /
260# binary / separator numbers, Infinity / NaN keywords, etc.) on top.
261
262{
263  # Drop Jsonic's implicit top-level list / map alternates so `a:1` and
264  # `1,2` are not accepted at the document root. JSON5 requires a single
265  # value expression at top level.
266  #
267  # `finish: false` turns off Jsonic's auto-close of open rules at the end
268  # of the source: JSON5 requires every `{` / `[` to be closed, so `{a:1`
269  # is an error, not `{"a":1}`.
270  options: rule: { exclude: 'imp' finish: false }
271
272  # Restrict the token sets used by Jsonic's grammar rules:
273  #   VAL drops #TX — reject bare unquoted text at value positions.
274  #   KEY drops #NR — reject numeric keys like `{10: 1}`.
275  options: tokenSet: {
276    VAL: [ '#ST' '#NR' '#VL' ]
277    KEY: [ '#TX' '#ST' '#VL' ]
278  }
279
280  # Whitespace and line-terminator sets are broadened to match the JSON5
281  # spec (Unicode Zs, BOM, LS / PS). The actual character strings are
282  # supplied by the plugin because they contain code points the grammar
283  # parser cannot round-trip losslessly.
284  options: space: { chars: JSON5_WHITESPACE }
285  options: line: {
286    chars: JSON5_LINE_TERMINATOR
287    rowChars: JSON5_ROW_CHARS
288  }
289
290  # LexCheck hooks close the last gaps the built-in lexer has against
291  # the JSON5 spec:
292  #   fixed.check  reads a string literal that holds a line continuation
293  #                (a backslash and a LineTerminatorSequence), which the
294  #                escape map cannot express, where it stands, so every
295  #                row, column and offset after it is the source's own.
296  #   text.check   rejects unquoted text that cannot start a valid
297  #                JSON5 IdentifierName AND is not a registered value
298  #                keyword or regex-matched number.
299  #   string.check rejects the escape sequences ECMAScript 5.1 forbids
300  #                inside a string literal but the permissive lexer
301  #                would otherwise accept (`\1`..`\9`, `\0` followed by
302  #                a digit, and the ES2015-only `\u{...}` form).
303  options: fixed: { check: '@fixed-check' }
304  options: text:  { check: '@text-check' }
305
306  # JSON5 numeric literals: allow hex, disallow octal / binary / digit
307  # separators. Reject JS-style leading-zero integers (`010`, `-098`).
308  options: number: {
309    lex: true
310    hex: true
311    oct: false
312    bin: false
313    sep: ''
314    exclude: '@/^[+-]?0[0-9]/'
315  }
316
317  # JSON5 comments are `//` and `/* */`. Hash comments are disabled here
318  # and only enabled by the plugin when the `hashComment` option is set.
319  options: comment: {
320    def: {
321      slash: { line: true start: '//' lex: true eatline: false }
322      multi: { line: false start: '/*' end: '*/' lex: true eatline: false }
323      hash:  { line: true start: '#' lex: false eatline: false }
324    }
325  }
326
327  # JSON5 strings: single or double quote, with ES5.1 escapes. A line
328  # continuation (backslash + LineTerminatorSequence, which produces the
329  # empty string) has no entry here: an entry is keyed by one character,
330  # which cannot spell CRLF, and the TypeScript and Go lexers take an
331  # empty replacement as no entry at all. A string holding one is read by
332  # fixed.check instead.
333  options: string: {
334    lex: true
335    check: '@string-check'
336    chars: JSON5_QUOTE_CHARS
337    multiChars: JSON5_MULTI_QUOTE_CHARS
338    escapeChar: '\\'
339    escape: {
340      b:  '\b'
341      f:  '\f'
342      n:  '\n'
343      r:  '\r'
344      t:  '\t'
345      v:  '\v'
346      '0': '\u0000'
347      '"': '"'
348      "'": "'"
349      '`': '`'
350      '\\': '\\'
351      '/': '/'
352    }
353    allowUnknown: true
354  }
355
356  # Value keywords. The Infinity / NaN family is layered on by the
357  # plugin (because the numeric literals cannot be round-tripped through
358  # this grammar parser as actual JS numbers). The regex-matched
359  # defs pick up number shapes the built-in number lexer does not
360  # recognise — trailing-decimal-with-exponent (`5.e4`) and uppercase
361  # `0X` hex — so both TS and Go exhibit the same behaviour on those.
362  options: value: {
363    lex: true
364    def: {
365      true:  { val: true }
366      false: { val: false }
367      null:  { val: null }
368
369      trailingDecExp: {
370        match:   '@/^[+-]?(?:0|[1-9][0-9]*)\\.[eE][+-]?[0-9]+/'
371        val:     '@parse-trailing-dec-exp'
372        consume: true
373      }
374
375      uppercaseHex: {
376        match:   '@/^[+-]?0X[0-9a-fA-F]+/'
377        val:     '@parse-uppercase-hex'
378        consume: true
379      }
380    }
381  }
382
383  # JSON5 objects extend on duplicate keys (last wins); no bare-colon
384  # child syntax. Lists are strict — no named properties, pairs, or
385  # bare-colon children.
386  options: map:  { extend: true  child: false }
387  options: list: { property: false pair: false child: false }
388
389  # Reject an entirely empty source. A comments-only source is handled
390  # in code by dropping the `#ZZ jsonic` alternate from the val rule.
391  options: lex: { empty: false emptyResult: null }
392
393  options: error: {
394    json5_empty:    'JSON5 input must contain a value'
395    json5_no_value: 'JSON5 input must contain a value'
396  }
397  options: hint: {
398    json5_empty: 'JSON5 requires a top-level value. An empty source is not a valid JSON5 document.'
399    json5_no_value: 'JSON5 requires a top-level value. A source that consists only of whitespace and comments is not valid.'
400  }
401}
402"#;
403// --- END EMBEDDED json5-grammar.jsonic ---
404
405// ---------------------------------------------------------------------------
406// Identifier names.
407// ---------------------------------------------------------------------------
408
409/// ECMAScript 5.1 `IdentifierStart` CHARACTER: `$`, `_`, or a Unicode
410/// letter (`L`) or letter number (`Nl`). The `\` that introduces a
411/// `UnicodeEscapeSequence` is not included; see [`is_identifier_start`].
412fn id_start(ch: char) -> bool {
413    static RE: OnceLock<Regex> = OnceLock::new();
414    ch == '$'
415        || ch == '_'
416        || RE
417            .get_or_init(|| Regex::new(r"^[\p{L}\p{Nl}]$").expect("a literal pattern"))
418            .is_match(ch.encode_utf8(&mut [0; 4]))
419}
420
421/// ECMAScript 5.1 `IdentifierPart`: an `IdentifierStart`, a combining
422/// mark (`Mn`, `Mc`), a digit (`Nd`), a connector punctuation (`Pc`),
423/// ZWNJ or ZWJ.
424fn id_part(ch: char) -> bool {
425    static RE: OnceLock<Regex> = OnceLock::new();
426    id_start(ch)
427        || ch == '\u{200C}'
428        || ch == '\u{200D}'
429        || RE
430            .get_or_init(|| Regex::new(r"^[\p{Mn}\p{Mc}\p{Nd}\p{Pc}]$").expect("a literal pattern"))
431            .is_match(ch.encode_utf8(&mut [0; 4]))
432}
433
434/// Whether `ch` may begin a JSON5 `IdentifierName` in the SOURCE text: an
435/// `IdentifierStart` character, or the `\` of a `UnicodeEscapeSequence`.
436fn is_identifier_start(ch: char) -> bool {
437    ch == '\\' || id_start(ch)
438}
439
440/// Validate AND decode a JSON5 `IdentifierName` (used for unquoted keys).
441/// `None` when the source is not a legal ECMAScript 5.1 `IdentifierName`.
442///
443/// An `IdentifierStart` / `IdentifierPart` may be written as a
444/// `UnicodeEscapeSequence` (`\uXXXX`), and the identifier's VALUE is the
445/// decoded text: `{ sigΣma: 1 }` has the key `sigΣma`. Each escape
446/// contributes exactly one UTF-16 code unit, which must itself be a legal
447/// identifier character: per ES5.1 7.6 an escape cannot smuggle an
448/// otherwise-illegal character into an identifier, so ` `, `-`, a leading
449/// `0` and escaped surrogate halves are all rejected. Mirrors the
450/// TypeScript and Go `decodeIdentifierName`.
451fn decode_identifier_name(source: &str) -> Option<String> {
452    if source.is_empty() {
453        return None;
454    }
455    let bytes = source.as_bytes();
456    let mut out = String::with_capacity(source.len());
457    let mut first = true;
458    let mut i = 0;
459    while i < bytes.len() {
460        let ch = if bytes[i] == b'\\' {
461            if i + 6 > bytes.len()
462                || bytes[i + 1] != b'u'
463                || !bytes[i + 2..i + 6].iter().all(u8::is_ascii_hexdigit)
464            {
465                return None;
466            }
467            let unit = u32::from_str_radix(&source[i + 2..i + 6], 16).ok()?;
468            // A lone UTF-16 surrogate half is not an identifier character.
469            if (0xD800..=0xDFFF).contains(&unit) {
470                return None;
471            }
472            i += 6;
473            char::from_u32(unit)?
474        } else {
475            let ch = source[i..].chars().next()?;
476            i += ch.len_utf8();
477            ch
478        };
479        if first {
480            if !id_start(ch) {
481                return None;
482            }
483            first = false;
484        } else if !id_part(ch) {
485            return None;
486        }
487        out.push(ch);
488    }
489    Some(out)
490}
491
492// ---------------------------------------------------------------------------
493// String line continuations.
494// ---------------------------------------------------------------------------
495
496/// What a string literal holds, as [`scan_string_escapes`] reports it. A
497/// string with neither is the engine's.
498#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
499struct StringEscapes {
500    /// An escape ES5.1 refuses (`\1`..`\9`, `\0` before a digit, `\u{`), so
501    /// the string is refused at its quote.
502    forbidden: bool,
503    /// A `LineContinuation`, so the fixed check reads the string.
504    continued: bool,
505}
506
507/// What the string literal opening at the start of `remaining` holds,
508/// walked the way the string check has always walked it: an escape takes
509/// the character after it along, and the walk ends at the closing quote
510/// or the end of the source. Mirrors `scanString` in `ts/src/json5.ts`.
511fn scan_string_escapes(remaining: &str, quote: char) -> StringEscapes {
512    let bytes = remaining.as_bytes();
513    let mut found = StringEscapes::default();
514    let mut i = quote.len_utf8();
515    while i < bytes.len() {
516        let c = remaining[i..].chars().next().expect("inside the source");
517        let size = c.len_utf8();
518        if c == quote {
519            break;
520        }
521        if c != '\\' {
522            i += size;
523            continue;
524        }
525        if i + size >= bytes.len() {
526            break;
527        }
528        let next = bytes[i + size];
529        let after = bytes.get(i + size + 1).copied().unwrap_or(0);
530        // Skip the escape lead and the character it escapes.
531        let escaped = remaining[i + size..].chars().next().expect("checked above");
532        if next.is_ascii_digit() && (next != b'0' || after.is_ascii_digit())
533            || (next == b'u' && after == b'{')
534        {
535            found.forbidden = true;
536        } else if is_line_terminator(escaped) {
537            found.continued = true;
538        }
539        i += size + escaped.len_utf8();
540    }
541    found
542}
543
544/// The string options the continuation reader reads, taken from the
545/// grammar document at install. A lexer check has no access to the live
546/// options, so the reader carries its own copy, as the text check carries
547/// its keyword list.
548#[derive(Debug, Clone)]
549struct StringSyntax {
550    quotes: String,
551    multi_line: String,
552    escape: Vec<(char, String)>,
553    allow_unknown: bool,
554    escape_strict: bool,
555    allow_control: bool,
556}
557
558impl StringSyntax {
559    fn from_document(document: &JsonValue) -> Self {
560        let string = &document["options"]["string"];
561        let text = |key: &str| string[key].as_str().unwrap_or_default().to_string();
562        let flag = |key: &str| string[key].as_bool().unwrap_or(false);
563        let escape = string["escape"]
564            .as_object()
565            .map(|map| {
566                map.iter()
567                    .filter_map(|(key, replacement)| {
568                        let mut chars = key.chars();
569                        match (chars.next(), chars.next(), replacement.as_str()) {
570                            (Some(ch), None, Some(text)) => Some((ch, text.to_string())),
571                            _ => None,
572                        }
573                    })
574                    .collect()
575            })
576            .unwrap_or_default();
577        StringSyntax {
578            quotes: text("chars"),
579            multi_line: text("multiChars"),
580            escape,
581            allow_unknown: flag("allowUnknown"),
582            escape_strict: flag("escapeStrict"),
583            allow_control: flag("allowControl"),
584        }
585    }
586
587    fn escape(&self, ch: char) -> Option<&str> {
588        self.escape
589            .iter()
590            .find(|(key, _)| *key == ch)
591            .map(|(_, replacement)| replacement.as_str())
592    }
593}
594
595/// What [`decode_continued_string`] read, counted from the opening quote.
596enum ContinuedString {
597    /// The string's value, and how far it runs: in characters and in
598    /// bytes, through the closing quote.
599    Read {
600        value: String,
601        chars: usize,
602        bytes: usize,
603    },
604    /// An error `at` characters in, its source `len` characters long.
605    Bad {
606        why: &'static str,
607        at: usize,
608        len: usize,
609    },
610    /// No closing quote before the end of the source.
611    Unterminated,
612}
613
614/// Read the string literal at the cursor when it holds a JSON5
615/// `LineContinuation`: a backslash and the `LineTerminatorSequence` after
616/// it (CRLF counting as one), which adds nothing to the value.
617///
618/// An escape-map entry, which this engine honours even when its
619/// replacement is empty, can spell a backslash before LF, CR, LS or PS,
620/// but not one before CRLF, which is two characters: an entry for CR
621/// takes the CR and leaves a bare LF, which is `unprintable`. Rewriting
622/// the source before lexing, as this crate's `parse_with` used to, made
623/// the value right and every later position wrong: it removed each
624/// continuation whole, so every token and every error after one was
625/// reported a row early (tabnas/json5#80), and it completed a partial
626/// escape across the line break, reading `\x4`, a continuation and `b` as
627/// `\x4b`.
628///
629/// The TypeScript and Go engines read no continuation at all, so their
630/// plugins read such a string themselves, and this reads every one too,
631/// not only one with a CRLF, so that the three agree on all of them:
632/// entries for the other four forms would read them, but the engine ends
633/// a pending surrogate pair at every escape-map hit, where the source
634/// holds the pair across the continuation.
635///
636/// So this reads the string where it stands, the way the engine's string
637/// matcher reads every other one: the same escape map, the same `\x` and
638/// `\u` forms, the same surrogate pairing, the same errors on the same
639/// characters. It moves the cursor with the engine's own advance, so every
640/// row, column and offset after the string is the one the engine counts
641/// for the source as it is. The grammar declares no `string.replace`, so
642/// there is no replace step. Mirrors `readContinuedString` in
643/// `ts/src/json5.ts`.
644fn read_continued_string(lexer: &mut Lexer<'_>, syntax: &StringSyntax) -> LexCheckResult {
645    let remaining = lexer.remaining();
646    let Some(quote) = remaining
647        .chars()
648        .next()
649        .filter(|quote| syntax.quotes.contains(*quote))
650    else {
651        return LexCheckResult::Continue;
652    };
653    let found = scan_string_escapes(remaining, quote);
654    if !found.continued {
655        return LexCheckResult::Continue;
656    }
657    // Such a string never reaches the string check, so one that also holds
658    // a forbidden escape is refused here instead, the same way and at the
659    // same place: `unexpected`, on the quote.
660    if found.forbidden {
661        return LexCheckResult::native_token(lexer.bad("unexpected"));
662    }
663    let start = lexer.point();
664    match decode_continued_string(remaining, quote, syntax) {
665        ContinuedString::Read {
666            value,
667            chars,
668            bytes,
669        } => {
670            let source = remaining[..bytes].to_string();
671            lexer.advance_chars(chars);
672            LexCheckResult::native_token(lexer.token(
673                "#ST",
674                TIN_ST,
675                Value::String(value),
676                source,
677                start,
678            ))
679        }
680        // Sited where it stands: on the offending character, or on the
681        // backslash of a malformed escape.
682        ContinuedString::Bad { why, at, len } => {
683            lexer.advance_chars(at);
684            let site = start.site.pos + at;
685            LexCheckResult::native_token(lexer.bad_span(why, site, site + len))
686        }
687        // Sited on the opening quote, as the engine sites it.
688        ContinuedString::Unterminated => {
689            let len = remaining.chars().count();
690            let site = start.site.pos;
691            LexCheckResult::native_token(lexer.bad_span("unterminated_string", site, site + len))
692        }
693    }
694}
695
696/// Decode the string literal opening at the start of `remaining`, without
697/// moving the lexer: see [`read_continued_string`].
698fn decode_continued_string(remaining: &str, quote: char, syntax: &StringSyntax) -> ContinuedString {
699    let multi_line = syntax.multi_line.contains(quote);
700    let next = |at: usize| remaining[at..].chars().next();
701    // Up to `len` characters from byte `from`, clipped at the end of the
702    // source, as the engine cuts the span of a malformed escape.
703    let span = |from: usize, len: usize| remaining[from..].chars().take(len).count();
704
705    let mut value = String::new();
706    let mut pending = None;
707    let mut i = quote.len_utf8();
708    let mut at = 1;
709
710    while let Some(c) = next(i) {
711        if c == quote {
712            flush_surrogate(&mut pending, &mut value);
713            return ContinuedString::Read {
714                value,
715                chars: at + 1,
716                bytes: i + c.len_utf8(),
717            };
718        }
719
720        if c == '\\' {
721            let Some(n) = next(i + 1) else {
722                break;
723            };
724            let body = i + 1 + n.len_utf8();
725
726            // The continuation: nothing in the value. It holds a surrogate
727            // pair open, because it is no code unit.
728            if is_line_terminator(n) {
729                if n == '\r' && remaining[body..].starts_with('\n') {
730                    i = body + 1;
731                    at += 3;
732                } else {
733                    i = body;
734                    at += 2;
735                }
736                continue;
737            }
738
739            if n != 'u' {
740                flush_surrogate(&mut pending, &mut value);
741            }
742
743            if let Some(replacement) = syntax.escape(n) {
744                value.push_str(replacement);
745                i = body;
746                at += 2;
747                continue;
748            }
749
750            if n == 'u' {
751                let Some(unit) = hex_digits(&remaining[body..], 4) else {
752                    return ContinuedString::Bad {
753                        why: "invalid_unicode",
754                        at,
755                        len: span(i, 6),
756                    };
757                };
758                emit_code_unit(unit, &mut pending, &mut value);
759                i = body + 4;
760                at += 6;
761                continue;
762            }
763
764            if n == 'x' && !syntax.escape_strict {
765                let Some(byte) = hex_digits(&remaining[body..], 2) else {
766                    return ContinuedString::Bad {
767                        why: "invalid_ascii",
768                        at,
769                        len: span(i, 4),
770                    };
771                };
772                value.push(char::from_u32(byte).expect("two hex digits are a scalar"));
773                i = body + 2;
774                at += 4;
775                continue;
776            }
777
778            if !syntax.allow_unknown {
779                return ContinuedString::Bad {
780                    why: "unexpected",
781                    at: at + 1,
782                    len: 1,
783                };
784            }
785            value.push(n);
786            i = body;
787            at += 2;
788            continue;
789        }
790
791        // CR and LF are this engine's `line.chars` (see JSON5_LINE_CHARS):
792        // string body only in a multi-line string. LS and PS are body in
793        // any string, and the engine's advance counts their rows.
794        let unprintable = if c == '\r' || c == '\n' {
795            !multi_line
796        } else {
797            (c as u32) < 32 && !syntax.allow_control
798        };
799        if unprintable {
800            return ContinuedString::Bad {
801                why: "unprintable",
802                at,
803                len: 1,
804            };
805        }
806
807        flush_surrogate(&mut pending, &mut value);
808        value.push(c);
809        i += c.len_utf8();
810        at += 1;
811    }
812
813    ContinuedString::Unterminated
814}
815
816/// Exactly `count` hex digits at the start of `text`, or `None` when fewer
817/// are there: a short or junk-terminated run is not an escape.
818fn hex_digits(text: &str, count: usize) -> Option<u32> {
819    let digits = text.get(..count)?;
820    if !digits.bytes().all(|byte| byte.is_ascii_hexdigit()) {
821        return None;
822    }
823    u32::from_str_radix(digits, 16).ok()
824}
825
826/// Append one decoded UTF-16 code unit, pairing surrogates as the engine's
827/// string matcher does: a high surrogate is held until the next code unit
828/// decides it, and one that nothing pairs with is U+FFFD.
829fn emit_code_unit(unit: u32, pending: &mut Option<u32>, out: &mut String) {
830    if (0xD800..=0xDBFF).contains(&unit) {
831        flush_surrogate(pending, out);
832        *pending = Some(unit);
833    } else if (0xDC00..=0xDFFF).contains(&unit) {
834        match pending.take() {
835            Some(high) => out.push(
836                char::from_u32(0x10000 + ((high - 0xD800) << 10) + (unit - 0xDC00))
837                    .expect("paired surrogates form a Unicode scalar"),
838            ),
839            None => out.push('\u{FFFD}'),
840        }
841    } else {
842        flush_surrogate(pending, out);
843        out.push(
844            char::from_u32(unit).expect("four hex digits outside the surrogates are a scalar"),
845        );
846    }
847}
848
849/// Resolve a held high surrogate that nothing paired with.
850fn flush_surrogate(pending: &mut Option<u32>, out: &mut String) {
851    if pending.take().is_some() {
852        out.push('\u{FFFD}');
853    }
854}
855
856// ---------------------------------------------------------------------------
857// The requireValue rule.
858// ---------------------------------------------------------------------------
859
860/// Does `src` contain anything that could begin a value, as opposed to
861/// only whitespace and comments? JSON5 requires a top-level value, and a
862/// comments-only document is exactly what `json5_no_value` names.
863///
864/// This deliberately does NOT lex or parse. It only has to find the FIRST
865/// character that is neither whitespace nor part of a comment, and stop
866/// there, which is what makes it safe. The trap in a naive "strip the
867/// comments and see what is left" is a source like `"/* x */"`: a valid
868/// JSON5 STRING whose contents look like a comment, which stripping would
869/// wrongly report as empty. Here the leading quote is simply a non-trivia
870/// character, so the scan stops on it and answers true without ever
871/// looking inside.
872///
873/// An unterminated block comment answers TRUE on purpose. `/* x` contains
874/// no value, but the engine's own `unterminated_comment` is the more
875/// useful diagnostic and this declines to shadow it.
876///
877/// `hash_comment` says whether THIS configuration also has the `#` form.
878/// It is a parameter rather than a read of the options because the two
879/// callers want different answers: the `require_value` guard passes
880/// `false`, so a hash-comment-only source keeps falling through to the
881/// rules and the engine's own `unexpected`, and the `require_value`-off
882/// short-circuit passes the option, so the same source counts as trivia
883/// and resolves to the declared empty result.
884///
885/// Mirrors `hasValue` in `ts/src/json5.ts`.
886fn has_value(src: &str, hash_comment: bool) -> bool {
887    let chars: Vec<char> = src.chars().collect();
888    let n = chars.len();
889    let mut i = 0;
890    while i < n {
891        let c = chars[i];
892        if is_json5_space(c) {
893            i += 1;
894            continue;
895        }
896        if hash_comment && c == '#' {
897            // Line comment: runs to the next line terminator, or the end.
898            i += 1;
899            while i < n && !is_line_terminator(chars[i]) {
900                i += 1;
901            }
902            continue;
903        }
904        if c == '/' && i + 1 < n {
905            let d = chars[i + 1];
906            if d == '/' {
907                // Line comment: runs to the next line terminator, or the end.
908                i += 2;
909                while i < n && !is_line_terminator(chars[i]) {
910                    i += 1;
911                }
912                continue;
913            }
914            if d == '*' {
915                let end =
916                    (i + 2..n.saturating_sub(1)).find(|&k| chars[k] == '*' && chars[k + 1] == '/');
917                let Some(end) = end else {
918                    return true; // unterminated: leave it to unterminated_comment
919                };
920                i = end + 2;
921                continue;
922            }
923        }
924        // Anything else begins something. Whether it is a VALID value is
925        // the parser's question, not this one.
926        return true;
927    }
928    false
929}
930
931/// The ECMAScript `\s` class, which is the JSON5 whitespace and line
932/// terminator set: `White_Space` minus NEL, plus the BOM. Named here
933/// rather than borrowed from `char::is_whitespace`, which includes U+0085
934/// and excludes U+FEFF, so the intent survives the difference.
935fn is_json5_space(c: char) -> bool {
936    c == '\u{FEFF}' || (c.is_whitespace() && c != '\u{0085}')
937}
938
939// ---------------------------------------------------------------------------
940// Grammar alternate helpers.
941// ---------------------------------------------------------------------------
942
943fn tag_contains(tags: &str, want: &str) -> bool {
944    tags.split(',').any(|tag| tag.trim() == want)
945}
946
947/// Remove `tin` from every slot of every alternate tagged `required_tag`.
948fn filter_tin_from_alts(alts: &mut [AltSpec], tin: Tin, required_tag: &str) {
949    for alt in alts.iter_mut() {
950        if !tag_contains(&alt.g, required_tag) {
951            continue;
952        }
953        for slot in alt.s.iter_mut() {
954            slot.retain(|t| *t != tin);
955        }
956    }
957}
958
959/// jsonic's `#ZZ` end-of-source alternate: the one that lets a source
960/// holding no value succeed.
961fn is_zz_jsonic_alt(alt: &AltSpec) -> bool {
962    tag_contains(&alt.g, "jsonic")
963        && alt.s.len() == 1
964        && alt.s[0].len() == 1
965        && alt.s[0][0] == TIN_ZZ
966}
967
968/// The pattern inside a serialized `@/pattern/flags` regular expression
969/// (the flags are not used by this grammar), or `None` for any other
970/// string.
971fn bare_regex_source(source: &str) -> Option<&str> {
972    let body = source.strip_prefix("@/")?;
973    let slash = body.rfind('/')?;
974    Some(&body[..slash])
975}
976
977/// A serialized regular expression, compiled for the `regex` crate.
978fn compile_serialized_regex(source: &str) -> Option<Regex> {
979    Regex::new(bare_regex_source(source)?).ok()
980}
981
982// ---------------------------------------------------------------------------
983// Base-prefixed integer literals.
984//
985// `0x`, `0o` and `0b` literals are read as an EXACT integer and rounded
986// to a double ONCE. The obvious fold -- `value = value * base + digit`
987// in `f64` -- rounds at every digit, and past the 53-bit exact integer
988// range those roundings accumulate: `0Xa6f2f78f4f9bf44` came out as
989// `43a4de5ef1e9f37e` where canonical TypeScript's `parseInt` answers
990// `43a4de5ef1e9f37f`, one unit in the last place low. That is silently
991// altered data, not a formatting difference.
992//
993// `parseInt` on a base-prefixed digit string is correctly rounded from
994// the exact integer, half to even, so that is what these reproduce. The
995// zon port solves the same problem over general bases in
996// `zon/rs/src/number.rs`; the bases here are all powers of two, so a
997// `u128` head plus a sticky bit replaces its limb arithmetic.
998// ---------------------------------------------------------------------------
999
1000/// `2^k` for a non-negative `k`, exactly, saturating to infinity above
1001/// the double range. A repeated multiply would round on the way up.
1002/// Mirrors `pow2` in the zon port.
1003fn pow2(k: i64) -> f64 {
1004    debug_assert!(k >= 0, "only non-negative exponents arise here");
1005    if k > 1023 {
1006        f64::INFINITY
1007    } else {
1008        f64::from_bits(((k + 1023) as u64) << 52)
1009    }
1010}
1011
1012/// The exact integer the digit values denote, as the NEAREST double,
1013/// rounding half to even. `bits` is the width of one digit, so the base
1014/// is a power of two: 1 for binary, 3 for octal, 4 for hexadecimal.
1015fn digits_to_f64(digits: &[u32], bits: u32) -> f64 {
1016    // Leading zeros carry no value, and dropping them is what makes the
1017    // head below wider than the 54 significant bits the rounding needs.
1018    let start = digits.iter().position(|digit| *digit != 0);
1019    let Some(start) = start else {
1020        return 0.0;
1021    };
1022    let digits = &digits[start..];
1023
1024    // A u128 holds exactly this many digits of the base.
1025    let head_len = (128 / bits) as usize;
1026    let pack = |run: &[u32]| {
1027        run.iter()
1028            .fold(0u128, |value, digit| (value << bits) | u128::from(*digit))
1029    };
1030    if digits.len() <= head_len {
1031        // A `u128` to `f64` cast rounds to nearest, ties to even, which
1032        // is the rule `parseInt` follows.
1033        return pack(digits) as f64;
1034    }
1035
1036    // Longer than a u128: keep the top `head_len` digits, and remember
1037    // whether anything below them was set. Those two are all the
1038    // rounding can depend on. The leading digit is non-zero, so the head
1039    // is at least 121 bits wide in every base here and `shift` is
1040    // comfortably positive.
1041    let head = pack(&digits[..head_len]);
1042    let tail = &digits[head_len..];
1043    let dropped = i64::from(bits) * tail.len() as i64;
1044    let shift = 128 - head.leading_zeros() - 53;
1045
1046    let mut mantissa = (head >> shift) as u64;
1047    let half = (head >> (shift - 1)) & 1 == 1;
1048    let sticky = head & ((1u128 << (shift - 1)) - 1) != 0 || tail.iter().any(|digit| *digit != 0);
1049    if half && (sticky || mantissa & 1 == 1) {
1050        // At most 2^53, which is still an exact double.
1051        mantissa += 1;
1052    }
1053    mantissa as f64 * pow2(dropped + i64::from(shift))
1054}
1055
1056/// The value of a base-prefixed integer literal -- `0x1F`, `-0o17`,
1057/// `+0b1010`, with an optional `separator` between digits -- or `None`
1058/// when `src` is not one.
1059///
1060/// This is deliberately tolerant about which prefixes it reads: whether
1061/// a literal is ACCEPTED is settled by the lexer and by the `hex` /
1062/// `octal` / `binary` options long before this runs, and re-deciding it
1063/// here would be a second copy of that rule.
1064fn radix_literal_value(src: &str, separator: Option<char>) -> Option<f64> {
1065    let (negative, rest) = match src.strip_prefix('-') {
1066        Some(rest) => (true, rest),
1067        None => (false, src.strip_prefix('+').unwrap_or(src)),
1068    };
1069    let rest = rest.strip_prefix('0')?;
1070    let mut characters = rest.chars();
1071    let bits = match characters.next()? {
1072        'x' | 'X' => 4,
1073        'o' | 'O' => 3,
1074        'b' | 'B' => 1,
1075        _ => return None,
1076    };
1077    let base = 1u32 << bits;
1078
1079    let mut digits = Vec::new();
1080    for character in characters {
1081        if Some(character) == separator {
1082            continue;
1083        }
1084        digits.push(character.to_digit(base)?);
1085    }
1086    if digits.is_empty() {
1087        return None;
1088    }
1089
1090    let magnitude = digits_to_f64(&digits, bits);
1091    Some(if negative { -magnitude } else { magnitude })
1092}
1093
1094// ---------------------------------------------------------------------------
1095// The plugin.
1096// ---------------------------------------------------------------------------
1097
1098/// The names the grammar document binds.
1099const FIXED_CHECK: &str = "@fixed-check";
1100const TEXT_CHECK: &str = "@text-check";
1101const STRING_CHECK: &str = "@string-check";
1102const PARSE_TRAILING_DEC_EXP: &str = "@parse-trailing-dec-exp";
1103const PARSE_UPPERCASE_HEX: &str = "@parse-uppercase-hex";
1104/// The `pair` after-open validator this plugin adds in code.
1105const PAIR_KEY_CHECK: &str = "@json5-pair-key";
1106
1107/// The `pair` after-open action: reject a `#TX` key whose source is not a
1108/// JSON5 `IdentifierName`, and rewrite one written with `\uXXXX` escapes
1109/// to its decoded text. jsonic's `@pairkey` alternate action has already
1110/// copied the raw token value into `u.key`, so both are updated.
1111fn pair_key_check(
1112    rule: &mut Rule,
1113    _context: &mut Context,
1114    _next: Option<&RuleSnapshot>,
1115    out: Option<Token>,
1116) -> Result<Option<Token>, ActionError> {
1117    let Some(token) = rule.o0().filter(|token| token.tin == TIN_TX) else {
1118        return Ok(out);
1119    };
1120    let Some(name) = decode_identifier_name(token.src.as_str()) else {
1121        let mut bad = token.clone();
1122        bad.bad("unexpected");
1123        return Ok(Some(bad));
1124    };
1125    if token.val != Value::String(name.clone()) {
1126        Rc::make_mut(&mut rule.o)[0].val = Value::String(name.clone());
1127        rule.u_mut().insert("key".to_string(), Value::String(name));
1128    }
1129    Ok(out)
1130}
1131
1132/// Parse the embedded grammar with a standard jsonic instance and patch
1133/// the placeholders and the option-dependent overrides, exactly as the
1134/// TypeScript and Go plugins do before `grammar()`.
1135fn grammar_document(options: &Json5Options) -> Result<JsonValue, PluginError> {
1136    let parsed = tabnas_jsonic::make().parse(GRAMMAR_TEXT).map_err(|error| {
1137        PluginError(format!(
1138            "json5: the embedded grammar does not parse: {error}"
1139        ))
1140    })?;
1141    let mut document = parsed.to_json();
1142    if !document.get("options").is_some_and(JsonValue::is_object) {
1143        return Err(PluginError(
1144            "json5: the embedded grammar has no `options` table".into(),
1145        ));
1146    }
1147    let opts = &mut document["options"];
1148
1149    // Substitute the placeholder bare-identifier strings with the real
1150    // character sets. (The grammar parser cannot round-trip some of these
1151    // code points safely as string literals.)
1152    opts["space"]["chars"] = json!(JSON5_WHITESPACE);
1153    // LS and PS travel in `line.fixed` rather than `line.chars`: see the
1154    // note on `JSON5_LINE_CHARS`. Together the two are the JSON5
1155    // LineTerminator set, which TypeScript and Go write into
1156    // `line.chars` whole.
1157    opts["line"]["chars"] = json!(JSON5_LINE_CHARS);
1158    opts["line"]["fixed"] = json!(JSON5_LINE_FIXED);
1159    opts["line"]["rowChars"] = json!(JSON5_ROW_CHARS);
1160    if options.backtick_string {
1161        opts["string"]["chars"] = json!("'\"`");
1162        opts["string"]["multiChars"] = json!("`");
1163    } else {
1164        opts["string"]["chars"] = json!("'\"");
1165        opts["string"]["multiChars"] = json!("");
1166    }
1167
1168    // Option-dependent overrides applied on top of the strict baseline.
1169    opts["number"]["hex"] = json!(options.hex);
1170    opts["number"]["oct"] = json!(options.octal);
1171    opts["number"]["bin"] = json!(options.binary);
1172    opts["number"]["sep"] = if options.number_separator {
1173        json!("_")
1174    } else {
1175        JsonValue::Null
1176    };
1177    opts["comment"]["def"]["hash"]["lex"] = json!(options.hash_comment);
1178    opts["lex"]["empty"] = json!(!options.require_value);
1179
1180    // `options.number.exclude` is a bare pattern on this engine, where a
1181    // `value.def.match` is the serialized `@/pattern/` form; the loader
1182    // stores the string as it is, so the wrapper is taken off here.
1183    if let Some(exclude) = opts["number"]["exclude"].as_str() {
1184        if let Some(bare) = bare_regex_source(exclude) {
1185            opts["number"]["exclude"] = json!(bare);
1186        }
1187    }
1188
1189    if !options.strict_value {
1190        if let Some(sets) = opts["tokenSet"].as_object_mut() {
1191            sets.shift_remove("VAL");
1192        }
1193    }
1194    Ok(document)
1195}
1196
1197/// The `Infinity` / `NaN` family the plugin layers on in code: the
1198/// values cannot be round-tripped through the grammar parser as numbers.
1199const INFINITY_DEFINITIONS: [(&str, f64); 6] = [
1200    ("Infinity", f64::INFINITY),
1201    ("+Infinity", f64::INFINITY),
1202    ("-Infinity", f64::NEG_INFINITY),
1203    ("NaN", f64::NAN),
1204    ("+NaN", f64::NAN),
1205    ("-NaN", f64::NAN),
1206];
1207
1208/// The value keywords and value regexes in force, so the text check can
1209/// let them through: the ones the document declares, plus the
1210/// `Infinity` family when the option is on.
1211fn value_definitions(document: &JsonValue, options: &Json5Options) -> (Vec<String>, Vec<Regex>) {
1212    let mut names = Vec::new();
1213    let mut regexes = Vec::new();
1214    if let Some(defs) = document["options"]["value"]["def"].as_object() {
1215        for (name, def) in defs {
1216            match def.get("match").and_then(JsonValue::as_str) {
1217                Some(source) => regexes.extend(compile_serialized_regex(source)),
1218                None => names.push(name.clone()),
1219            }
1220        }
1221    }
1222    if options.infinity {
1223        names.extend(
1224            INFINITY_DEFINITIONS
1225                .iter()
1226                .map(|(name, _)| name.to_string()),
1227        );
1228    }
1229    (names, regexes)
1230}
1231
1232/// The keywords the document declares with `val: null`. The JSON loader
1233/// reads a null `val` as "no value" and the keyword would come back as
1234/// its own text, so these are put back as [`Value::Null`] after install.
1235fn null_keywords(document: &JsonValue) -> Vec<String> {
1236    document["options"]["value"]["def"]
1237        .as_object()
1238        .map(|defs| {
1239            defs.iter()
1240                .filter(|(_, def)| def.get("val").is_some_and(JsonValue::is_null))
1241                .map(|(name, _)| name.clone())
1242                .collect()
1243        })
1244        .unwrap_or_default()
1245}
1246
1247/// Install JSON5 on `parser`, which must already carry the jsonic grammar
1248/// (from [`tabnas_jsonic::make`], or [`tabnas_jsonic::jsonic`] on a bare
1249/// engine). The counterpart of the TypeScript `Json5` plugin function and
1250/// the Go `Json5(j, opts)`.
1251///
1252/// Most callers want [`make`] / [`make_with`], or [`plugin`] with
1253/// [`Tabnas::use_plugin`], which record the options on the instance the
1254/// same way this does.
1255///
1256/// ```
1257/// let mut parser = tabnas_jsonic::make();
1258/// tabnas_json5::json5(&mut parser, &tabnas_json5::Json5Options::default())?;
1259/// let value = tabnas_json5::parse_with(&parser, "{ a: 0x1F, b: [+Infinity, NaN] }")?;
1260/// assert_eq!(value.to_json()["a"], 31.0);
1261/// assert_eq!(value.to_json()["b"], serde_json::json!([null, null]));
1262/// let tabnas::Value::Object(map) = &value else { panic!("not an object") };
1263/// let tabnas::Value::Array(numbers) = &map["b"] else { panic!("not an array") };
1264/// assert_eq!(numbers[0], tabnas::Value::Number(f64::INFINITY));
1265/// assert!(matches!(numbers[1], tabnas::Value::Number(n) if n.is_nan()));
1266/// # Ok::<(), Box<dyn std::error::Error>>(())
1267/// ```
1268pub fn json5(parser: &mut Tabnas, options: &Json5Options) -> Result<(), PluginError> {
1269    let options = *options;
1270
1271    let document = grammar_document(&options)?;
1272    let (value_names, value_regexes) = value_definitions(&document, &options);
1273    let null_keywords = null_keywords(&document);
1274
1275    // The refs the document names, registered before it is installed.
1276    //
1277    // `@fixed-check` runs before every lexer step, ahead of every matcher.
1278    // A string that holds a line continuation is its own: at the string's
1279    // opening quote it reads it (`read_continued_string`) and returns the
1280    // finished token, or refuses it, as the string check would, when it
1281    // also holds a forbidden escape. Anywhere else it does nothing, and
1282    // every other string is the engine's.
1283    let syntax = StringSyntax::from_document(&document);
1284    parser.imperative_lex_check_ref(FIXED_CHECK, move |lexer: &mut Lexer<'_>| {
1285        read_continued_string(lexer, &syntax)
1286    });
1287
1288    // Reject unquoted text that cannot start a valid JSON5 IdentifierName
1289    // AND is not a value keyword or a value regex match. Skipping the text
1290    // matcher leaves the character unclaimed, so the lexer raises
1291    // `unexpected` there, the same outcome as the TypeScript
1292    // `{ done: true, token: undefined }`.
1293    parser.lex_check_ref(TEXT_CHECK, move |remaining: &str| {
1294        let Some(first) = remaining.chars().next() else {
1295            return LexCheckResult::Continue;
1296        };
1297        if is_identifier_start(first)
1298            || value_names
1299                .iter()
1300                .any(|name| remaining.starts_with(name.as_str()))
1301            || value_regexes.iter().any(|regex| regex.is_match(remaining))
1302        {
1303            LexCheckResult::Continue
1304        } else {
1305            LexCheckResult::Skip
1306        }
1307    });
1308
1309    // Reject the escape sequences ECMAScript 5.1, and hence JSON5, forbids
1310    // inside a string literal but the engine's permissive escape handling
1311    // (allowUnknown, non-strict `\u{...}`) would otherwise accept:
1312    //   \1 .. \9    a DecimalDigit is an EscapeCharacter, so it is not a
1313    //               NonEscapeCharacter: legacy octal escapes are not JSON5.
1314    //   \0<digit>   `0` is an escape only when NOT followed by a DecimalDigit.
1315    //   \u{XXXX}    the ES2015 code-point form; JSON5 has only `\uXXXX`.
1316    let quotes = document["options"]["string"]["chars"]
1317        .as_str()
1318        .unwrap_or("'\"")
1319        .to_string();
1320    parser.lex_check_ref(STRING_CHECK, move |remaining: &str| {
1321        match remaining
1322            .chars()
1323            .next()
1324            .filter(|quote| quotes.contains(*quote))
1325        {
1326            Some(quote) if scan_string_escapes(remaining, quote).forbidden => LexCheckResult::Skip,
1327            _ => LexCheckResult::Continue,
1328        }
1329    });
1330
1331    // Trailing-decimal-with-exponent (`5.e4`) and uppercase `0X` hex: the
1332    // number shapes the built-in lexer misses, matched by regex value
1333    // definitions so every runtime agrees on them.
1334    parser.value_transform_ref(PARSE_TRAILING_DEC_EXP, |groups: &[String]| {
1335        let literal = groups.first().map(String::as_str).unwrap_or_default();
1336        let (mantissa, exponent) = literal.split_once(['e', 'E']).unwrap_or((literal, "0"));
1337        Value::Number(
1338            format!("{}e{exponent}", mantissa.trim_end_matches('.'))
1339                .parse()
1340                .unwrap_or(f64::NAN),
1341        )
1342    });
1343    parser.value_transform_ref(PARSE_UPPERCASE_HEX, |groups: &[String]| {
1344        // The regex admits no digit separator, so none is passed.
1345        let literal = groups.first().map(String::as_str).unwrap_or_default();
1346        Value::Number(radix_literal_value(literal, None).unwrap_or(f64::NAN))
1347    });
1348
1349    parser.state_action_with_next_ref(PAIR_KEY_CHECK, pair_key_check);
1350
1351    let spec = tabnas::GrammarSpec::from_value(document).map_err(|error| PluginError(error.0))?;
1352    parser
1353        .grammar(&spec)
1354        .map_err(|error| PluginError(error.0))?;
1355
1356    // Infinity / NaN cannot be round-tripped through the grammar parser as
1357    // actual numbers, so layer them on here; and the `null` keyword's
1358    // value cannot travel as JSON null, so it is put back the same way.
1359    parser
1360        .set_options(|o| {
1361            for name in &null_keywords {
1362                if let Some(def) = o.value.definitions.get_mut(name) {
1363                    def.val = Some(Value::Null);
1364                }
1365            }
1366            if options.infinity {
1367                for (name, value) in INFINITY_DEFINITIONS {
1368                    o.value.definitions.insert(
1369                        name.to_string(),
1370                        ValueDef {
1371                            val: Some(Value::Number(value)),
1372                            matcher: None,
1373                            transform: None,
1374                            consume: false,
1375                        },
1376                    );
1377                }
1378            }
1379        })
1380        .map_err(|error| PluginError(error.0))?;
1381
1382    // Grammar alternates resolve token sets when they are installed, so
1383    // the `tokenSet` the document declares does not reach jsonic's
1384    // pre-built `val` and `pair` alternates. Filter `#TX` from the
1385    // val-tagged alternates and `#NR` from the pair-tagged ones directly,
1386    // as the Go port does, to make the restriction effective at parse
1387    // time.
1388    for name in parser.rule_names() {
1389        parser.define_rule(name, |spec| {
1390            if options.strict_value {
1391                filter_tin_from_alts(&mut spec.open, TIN_TX, "val");
1392                filter_tin_from_alts(&mut spec.close, TIN_TX, "val");
1393            }
1394            filter_tin_from_alts(&mut spec.open, TIN_NR, "pair");
1395            filter_tin_from_alts(&mut spec.close, TIN_NR, "pair");
1396        });
1397    }
1398
1399    // Rule-level trims the grammar file cannot express declaratively:
1400    //   - pair.open loses its leading-comma `jsonic` alt so `{,}` fails.
1401    //   - pair gains an after-open validator that rejects #TX keys whose
1402    //     source text is not a valid JSON5 IdentifierName.
1403    //   - val.open loses its `#ZZ jsonic` alt (when requireValue is set)
1404    //     so a source containing only whitespace / comments errors out.
1405    parser.define_rule("pair", |spec| {
1406        spec.open
1407            .retain(|alt| !(tag_contains(&alt.g, "comma") && tag_contains(&alt.g, "jsonic")));
1408        if !spec.ao.iter().any(|action| action == PAIR_KEY_CHECK) {
1409            spec.ao.push(PAIR_KEY_CHECK.to_string());
1410        }
1411    });
1412    if options.require_value {
1413        parser.define_rule("val", |spec| {
1414            spec.open.retain(|alt| !is_zz_jsonic_alt(alt));
1415        });
1416    }
1417
1418    // Record the resolved options on the instance so `parse_with` can
1419    // apply the requireValue rule. The TypeScript plugin wraps the
1420    // parser's `start` for this; the engine here runs a `parser.start`
1421    // hook INSTEAD of the parse rather than before it, so the guard lives
1422    // in the package-level entry point, as in Go.
1423    parser.decorate(OPTIONS_MARK, options);
1424    Ok(())
1425}
1426
1427/// The plugin form of [`json5`], for [`Tabnas::use_plugin`]. Its defaults
1428/// are [`Json5Options::default`], and the bag it receives is read with
1429/// [`Json5Options::from_value`], so a caller passes only the keys to
1430/// change:
1431///
1432/// ```
1433/// let mut parser = tabnas_jsonic::make();
1434/// let overrides = tabnas_json5::Json5Options { hash_comment: true, ..Default::default() };
1435/// parser.use_plugin(tabnas_json5::plugin(), Some(overrides.to_value()))?;
1436/// assert_eq!(tabnas_json5::parse_with(&parser, "# c\n42")?.to_string(), "42");
1437/// # Ok::<(), Box<dyn std::error::Error>>(())
1438/// ```
1439pub fn plugin() -> Plugin {
1440    Plugin::new(PLUGIN_NAME, |parser, options| {
1441        json5(parser, &Json5Options::from_value(options))
1442    })
1443    .with_defaults(Json5Options::default().to_value())
1444}
1445
1446/// Build a JSON5 parser with caller options: `jsonic.Make()` followed by
1447/// `UseDefaults(Json5, Defaults(), opts)` in Go, or
1448/// `new Tabnas().use(jsonic).use(Json5, opts)` in TypeScript.
1449///
1450/// Infallible by design: the grammar is a fixed literal, so a failure
1451/// here is a bug in this crate rather than anything a caller did.
1452///
1453/// ```
1454/// let options = tabnas_json5::Json5Options { strict_value: false, ..Default::default() };
1455/// let parser = tabnas_json5::make_with(options);
1456/// assert_eq!(tabnas_json5::parse_with(&parser, "foo")?.to_string(), r#""foo""#);
1457/// # Ok::<(), tabnas_json5::Json5Error>(())
1458/// ```
1459pub fn make_with(options: Json5Options) -> Tabnas {
1460    let mut parser = tabnas_jsonic::make();
1461    parser
1462        .use_plugin(plugin(), Some(options.to_value()))
1463        .expect("the json5 grammar is fixed and valid");
1464    parser
1465}
1466
1467/// Build a JSON5 parser with the default (strict JSON5) options.
1468///
1469/// ```
1470/// let parser = tabnas_json5::make();
1471/// let value = tabnas_json5::parse_with(&parser, "[1, 2, 3,]")?;
1472/// assert_eq!(value.to_string(), "[1,2,3]");
1473/// assert!(tabnas_json5::parse_with(&parser, "[1, 2").is_err());
1474/// # Ok::<(), tabnas_json5::Json5Error>(())
1475/// ```
1476pub fn make() -> Tabnas {
1477    make_with(Json5Options::default())
1478}
1479
1480/// A `json5_empty` or `json5_no_value` error, worded from the message and
1481/// hint templates the grammar registers on the instance, so the wording
1482/// has one source.
1483fn value_error(parser: &Tabnas, code: &str, src: &str) -> Json5Error {
1484    let mut error = Json5Error::new(code, "", src, 0, 1, 1);
1485    let config = parser.config();
1486    error.detail = config
1487        .error
1488        .get(code)
1489        .cloned()
1490        .unwrap_or_else(|| "JSON5 input must contain a value".to_string());
1491    error.hint = config.hint.get(code).cloned().unwrap_or_default();
1492    error
1493}
1494
1495/// Parse a JSON5 source with a parser that carries the plugin: the
1496/// counterpart of the Go `Parse(j, src)` and of the `parse` the
1497/// TypeScript plugin wraps.
1498///
1499/// This is the entry point the plugin's behaviour is specified against.
1500/// It applies the one thing the engine's own [`Tabnas::parse`] cannot do
1501/// from inside a plugin, the `requireValue` rule: with the option on (the
1502/// default) an empty source is `json5_empty` and a whitespace-only or
1503/// comments-only one is `json5_no_value`; with it off, every such source
1504/// is the grammar's declared empty result, `null`. Everything else,
1505/// string line continuations included, is the instance's own, so
1506/// [`Tabnas::parse`] reads it the same way and reports the same
1507/// positions.
1508///
1509/// A parser that does not carry the plugin is parsed as it is.
1510///
1511/// ```
1512/// let parser = tabnas_json5::make();
1513/// let error = tabnas_json5::parse_with(&parser, "// only a comment").unwrap_err();
1514/// assert_eq!(error.code, "json5_no_value");
1515/// # Ok::<(), tabnas_json5::Json5Error>(())
1516/// ```
1517pub fn parse_with(parser: &Tabnas, src: &str) -> Result<Value, Json5Error> {
1518    let Some(options) = parser.decoration::<Json5Options>(OPTIONS_MARK).copied() else {
1519        return parser.parse(src);
1520    };
1521    if options.require_value {
1522        if src.is_empty() {
1523            return Err(value_error(parser, "json5_empty", src));
1524        }
1525        // Slash forms ONLY, deliberately, and the `false` says so at the
1526        // call rather than in a comment on the scan. A hash-comment-only
1527        // source is not `json5_no_value` here: it reaches the rules and
1528        // fails on the comment with the engine's own `unexpected`, which
1529        // is what all three runtimes do and what the `# comment` row of
1530        // `test/spec/options.tsv` pins.
1531        if !has_value(src, false) {
1532            return Err(value_error(parser, "json5_no_value", src));
1533        }
1534    } else if !src.is_empty() && !has_value(src, options.hash_comment) {
1535        // Without requireValue, a source holding no value resolves to the
1536        // SAME declared empty result that `""` already resolves to.
1537        // Delegating to the engine's own empty-source path keeps the
1538        // grammar's `emptyResult` the one place that value is written.
1539        //
1540        // With `hash_comment` on, `#` is trivia exactly as `//` is, so a
1541        // hash-comment-only source takes this path too. The result is the
1542        // same `null` the rules already fell out with here, measured both
1543        // ways; what changes is that it now arrives by the SAME route as
1544        // in the canonical, which took the rules path and answered
1545        // `undefined` until 2026-09-21.
1546        return parser.parse("");
1547    }
1548    parser.parse(src)
1549}
1550
1551/// Parse a JSON5 source string with the shared default parser.
1552///
1553/// The parser is built once, on first use, and reused after that. Reuse
1554/// is safe: [`Tabnas::parse`] takes `&self` and builds a fresh parse
1555/// context per call, and `Tabnas` is `Send + Sync`, so concurrent callers
1556/// share one installed grammar instead of each rebuilding it, which is
1557/// what dominates a small parse.
1558///
1559/// Use [`make_with`] and [`parse_with`] instead when the parser needs
1560/// configuring: that returns a fresh instance and leaves this one alone.
1561///
1562/// ```
1563/// let value = tabnas_json5::parse("{ a: 1, b: [2, 3,], }")?;
1564/// assert_eq!(value.to_string(), r#"{"a":1,"b":[2,3]}"#);
1565/// assert_eq!(tabnas_json5::parse("").unwrap_err().code, "json5_empty");
1566/// # Ok::<(), tabnas_json5::Json5Error>(())
1567/// ```
1568pub fn parse(src: &str) -> Result<Value, Json5Error> {
1569    static DEFAULT: OnceLock<Tabnas> = OnceLock::new();
1570    parse_with(DEFAULT.get_or_init(make), src)
1571}
1572
1573/// One optional alchemy source and the entry point a host calls.
1574#[derive(Clone, Copy, Debug, Eq, PartialEq)]
1575pub struct TranslationPart {
1576    /// The entry point a host calls.
1577    pub entry: &'static str,
1578    /// The source text, or `None` for an entry supplied by alchemy.
1579    pub source: Option<&'static str>,
1580}
1581
1582/// The package-local structural translation interface.
1583#[derive(Clone, Copy, Debug, Eq, PartialEq)]
1584pub struct TranslationParts {
1585    /// The complete `tabnas.plugin.json` text.
1586    pub manifest: &'static str,
1587    /// An optional lift from the grammar's events to its first read shape.
1588    pub lift: Option<TranslationPart>,
1589    /// An optional render from the write shape to text.
1590    pub render: Option<TranslationPart>,
1591}
1592
1593const TRANSLATION: TranslationParts = TranslationParts {
1594    manifest: include_str!("../translate/manifest.json"),
1595    lift: None,
1596    render: Some(TranslationPart {
1597        entry: "json",
1598        source: None,
1599    }),
1600};
1601
1602/// Return JSON5's immutable translation parts.
1603#[must_use]
1604pub const fn translate() -> Option<TranslationParts> {
1605    Some(TRANSLATION)
1606}
1607
1608/// The plugin's manifest, `tabnas.plugin.json`, as the repository carries
1609/// it. Its `translate` object is what a host that translates reads: the
1610/// shape JSON5 is read as and written from (`tree`), the render that
1611/// writes it, which is the `json` render alchemy carries rather than a
1612/// file of this repository's, and the sentences that say what that render
1613/// does not keep. The crate embeds its own copy, `translate/manifest.json`,
1614/// since a packaged crate holds nothing outside `rs/`;
1615/// `tests/translate_test.rs` holds the copy to the file.
1616///
1617/// ```
1618/// assert!(tabnas_json5::manifest_text().contains("\"translate\""));
1619/// ```
1620pub fn manifest_text() -> &'static str {
1621    TRANSLATION.manifest
1622}