Skip to main content

tabnas_jsonic/
lib.rs

1// Copyright (c) 2013-2026 Richard Rodger, 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 jsonic relaxed-JSON grammar plugin for the `tabnas` parsing engine.
11//!
12//! jsonic accepts standard JSON and then relaxes it for humans: unquoted
13//! keys, implicit objects and arrays, comments, trailing commas, single
14//! and backtick quoted strings, and path diving (`a:b:1` is
15//! `{"a":{"b":1}}`).
16//!
17//! The standard-JSON core (`val` / `map` / `list` / `pair` / `elem`) comes
18//! from the [`tabnas_json`] plugin; this crate installs that core and
19//! weaves the relaxed alternates and lifecycle actions around it, exactly
20//! as the canonical TypeScript grammar in `ts/src/grammar.ts` does.
21//!
22//! ```
23//! let value = tabnas_jsonic::parse("a:1, b:[x,y,z]")?;
24//! assert_eq!(value.to_string(), r#"{"a":1,"b":["x","y","z"]}"#);
25//! # Ok::<(), tabnas_jsonic::JsonicError>(())
26//! ```
27//!
28//! TypeScript is canonical: `ts/src/grammar.ts` and `ts/src/defaults.ts`
29//! define behaviour, option defaults and the order of alternates. The
30//! shared fixtures in `test/spec/*.tsv` are the parity contract across
31//! TypeScript, Go and Rust.
32
33use std::cell::RefCell;
34use std::rc::Rc;
35use std::sync::{Arc, OnceLock};
36
37use indexmap::IndexMap;
38use regex::Regex;
39use serde_json::json;
40use tabnas::lexer::Lexer;
41use tabnas::{
42    ActionError, Context, GrammarError, GrammarSpec, LexCheckResult, ListRef, Options, Plugin,
43    PluginError, Rule, Tabnas, Text, Tin, Token, Value, TIN_OB, TIN_OS, TIN_ST, TIN_TX, TIN_ZZ,
44};
45
46/// This crate's version. It MUST equal `ts/package.json` "version": the
47/// release orchestrator rewrites both, and `tests/version_test.rs` fails
48/// the build if they drift. Mirrors `VERSION` in `ts/src/jsonic.ts` and
49/// `const VERSION` in `go/jsonic.go`.
50pub const VERSION: &str = "0.7.12";
51
52/// The README's Rust examples run as doctests, so a stale one fails the
53/// gate rather than misleading the reader. Its `toml` and `bash` fences
54/// are skipped; rustdoc runs only the `rust` ones.
55#[cfg(doctest)]
56#[doc = include_str!("../README.md")]
57mod readme_examples {}
58
59/// The error a failed parse produces, re-exported so callers need not
60/// depend on the engine crate directly. Mirrors the TypeScript
61/// `export { TabnasError as JsonicError }`.
62pub use tabnas::TabnasError as JsonicError;
63
64// ---------------------------------------------------------------------------
65// Named function references.
66//
67// The serialized grammar names every closure, and the closures are
68// registered on the instance BEFORE the document is installed. Each
69// lifecycle reference carries its phase suffix (`/append`, `/replace`) on
70// purpose: the engine resolves a bare `@map-bo`, `@list-bo`, `@pair-bc`,
71// `@elem-bc`, `@val-bc` or `@pairkey` to its own builtin first, so a
72// registration under one of those names would be shadowed silently.
73// ---------------------------------------------------------------------------
74
75/// Alternate error: with `rule.finish` off, an unterminated structure is
76/// `end_of_source` rather than an implicit close.
77const FINISH: &str = "@finish";
78/// Alternate action: capture the pair key from the first open token.
79const PAIRKEY: &str = "@jsonic-pairkey";
80/// Takes over the `val` before-close phase from `tabnas_json`.
81const VAL_BC: &str = "@val-bc/replace";
82/// After-close: restore a primitive value a plugin set in `val` open.
83const VAL_AC: &str = "@val-ac/append";
84const MAP_BO: &str = "@map-bo/append";
85const MAP_BC: &str = "@map-bc/append";
86const LIST_BO: &str = "@list-bo/append";
87const LIST_BC: &str = "@list-bc/append";
88const PAIR_BC: &str = "@pair-bc/append";
89/// Takes over the `elem` before-close phase from `tabnas_json`.
90const ELEM_BC: &str = "@elem-bc/replace";
91const VAL_CLOSE_ERROR: &str = "@val-close-error";
92const ELEM_DOUBLE_COMMA: &str = "@elem-double-comma";
93const ELEM_SINGLE_COMMA: &str = "@elem-single-comma";
94const ELEM_PAIR_ERR: &str = "@elem-pair-err";
95const ELEM_CLOSE_ERR: &str = "@elem-close-err";
96/// The strict-JSON number preflight hook [`make_json`] binds by name.
97const STRICT_NUMBER_CHECK: &str = "jsonic-strict-number";
98
99/// The name every jsonic plugin registers under, and so the namespace of
100/// its plugin options.
101const PLUGIN_NAME: &str = "jsonic";
102
103// ---------------------------------------------------------------------------
104// Options
105// ---------------------------------------------------------------------------
106
107/// The option branding jsonic layers on the engine's relaxed defaults.
108///
109/// `ts/src/defaults.ts` was compared field by field against the engine's
110/// `Options::default()`: the lexer, value, map, list, info, rule and
111/// result defaults are identical, so only the error identity and the
112/// jsonic hint catalogue travel here. The `error` templates are the
113/// engine's own, re-stated by jsonic rather than declared, and so are
114/// left alone.
115fn jsonic_options_document() -> serde_json::Value {
116    json!({
117        "options": {
118            "errmsg": {
119                "name": "jsonic",
120                "link": "https://github.com/tabnas/jsonic",
121            },
122            "hint": {
123                "unknown": "\nSince the error is unknown, this is probably a bug inside jsonic\nitself, or a plugin. Please consider posting a github issue - thanks!\n\nCode: {code}, Details: \n{details}",
124                "unexpected": "\nThe character(s) {src} were not expected at this point as they do not\nmatch the expected syntax, even under the relaxed jsonic rules. If it\nis not obviously wrong, the actual syntax error may be elsewhere. Try\ncommenting out larger areas around this point until you get no errors,\nthen remove the comments in small sections until you find the\noffending syntax. NOTE: Also check if any plugins you are using\nexpect different syntax in this case.",
125                "invalid_unicode": "\nThe escape sequence {src} does not encode a valid unicode code point\nnumber. You may need to validate your string data manually using test\ncode to see how JavaScript will interpret it. Also consider that your\ndata may have become corrupted, or the escape sequence has not been\ngenerated correctly.",
126                "invalid_ascii": "\nThe escape sequence {src} does not encode a valid ASCII character. You\nmay need to validate your string data manually using test code to see\nhow JavaScript will interpret it. Also consider that your data may\nhave become corrupted, or the escape sequence has not been generated\ncorrectly.",
127                "unprintable": "\nString values cannot contain unprintable characters (character codes\nbelow 32). The character {src} is unprintable. You may need to remove\nthese characters from your source data. Also check that it has not\nbecome corrupted.",
128                "unterminated_string": "\nThis string has no end quote.",
129                "unterminated_comment": "\nThis comment is never closed.",
130                "unknown_rule": "\nNo rule named $rulename is defined. This is probably an error in the\ngrammar of a plugin.",
131                "end_of_source": "\nUnexpected end of source.",
132            },
133        },
134    })
135}
136
137/// Apply jsonic's option branding to `parser`.
138fn apply_options(parser: &mut Tabnas) -> Result<(), GrammarError> {
139    let spec = GrammarSpec::from_value(jsonic_options_document())?;
140    parser.grammar(&spec)?;
141    Ok(())
142}
143
144/// Put back the relaxed lexer profile after [`tabnas_json::json`] has
145/// applied its strict one.
146///
147/// `tabnas_json` has one entry point that installs its OPTIONS as well as
148/// its RULES, where the TypeScript `registerJsonGrammar` installs rules
149/// alone. jsonic wants the rules only: every field the strict profile
150/// changes is restored to what it was before the call, so a caller's own
151/// setting (the strict `KEY` token set of [`make_json`], say) survives
152/// the layering rather than being reset to the engine default.
153fn restore_relaxed(options: &mut Options, relaxed: &Options) {
154    options.text.lex = relaxed.text.lex;
155    options.number.hex = relaxed.number.hex;
156    options.number.oct = relaxed.number.oct;
157    options.number.bin = relaxed.number.bin;
158    options.number.sep.clone_from(&relaxed.number.sep);
159    options.number.check.clone_from(&relaxed.number.check);
160    options.string.chars.clone_from(&relaxed.string.chars);
161    options
162        .string
163        .multi_chars
164        .clone_from(&relaxed.string.multi_chars);
165    options.string.allow_unknown = relaxed.string.allow_unknown;
166    options.string.escape_strict = relaxed.string.escape_strict;
167    options.string.escape.clone_from(&relaxed.string.escape);
168    options.comment.lex = relaxed.comment.lex;
169    options.map.extend = relaxed.map.extend;
170    options.lex.empty = relaxed.lex.empty;
171    options.rule.finish = relaxed.rule.finish;
172    options.rule.include.clone_from(&relaxed.rule.include);
173    match relaxed.token_set.get("KEY") {
174        Some(key) => {
175            options.token_set.insert("KEY".to_string(), key.clone());
176        }
177        None => {
178            options.token_set.remove("KEY");
179        }
180    }
181    options.parse.budget = relaxed.parse.budget.clone();
182}
183
184// ---------------------------------------------------------------------------
185// The grammar document
186// ---------------------------------------------------------------------------
187
188/// The relaxed alternates, phase one: the `rs.open(...)` / `rs.close(...)`
189/// calls of `ts/src/grammar.ts` in order, one entry per rule and state.
190///
191/// The engine applies an `inject` object's `delete` and `move` to the
192/// EXISTING alternates before the new ones go in, where TypeScript inserts
193/// first and modifies after. Three of jsonic's calls depend on that order:
194/// the `move` that sends json's "there is more JSON" alternate to the end
195/// of `val.close`, and the second `.open(..., {append: true})` on `map`
196/// and `list`. Those are the second phase, [`jsonic_document_append`],
197/// which runs once this one is installed, so the final lists are the
198/// TypeScript ones alternate for alternate.
199///
200/// The option-conditional alternates (`map.child`, `list.child`, and the
201/// `list.property || list.pair` guard on a pair inside a list) are decided
202/// against `options` when the document is built, as `p.cfg.*` decides
203/// them in TypeScript and `cfg.*` in Go.
204fn jsonic_document(options: &Options) -> serde_json::Value {
205    let list_pairs_allowed = options.list.property || options.list.pair;
206
207    let mut pair_open = vec![
208        // Re-declare the key alt so it binds jsonic's pairkey (which uses
209        // the key token's SOURCE for number and value-keyword keys, e.g.
210        // `1:x` -> "1", `true:1` -> "true"), replacing the strict
211        // tabnas_json version that uses the decoded token value. The
212        // `clear` below drops tabnas_json's pair open alts first.
213        json!({ "s": "#KEY #CL", "p": "val", "u": { "pair": true }, "a": PAIRKEY,
214                "g": "map,pair,key,json" }),
215        // Ignore initial comma: {,a:1.
216        json!({ "s": "#CA", "g": "map,pair,comma,jsonic" }),
217    ];
218    if options.map.child {
219        // map.child: bare colon `:value` stores value on child$ property.
220        pair_open.push(
221            json!({ "s": "#CL", "p": "val", "u": { "done": true, "child": true },
222                               "g": "map,pair,child,jsonic" }),
223        );
224    }
225
226    let mut elem_pair = json!({
227        "s": "#KEY #CL", "p": "val",
228        "n": { "pk": 1, "dmap": 1 },
229        "u": { "done": true, "pair": true, "list": true },
230        "a": PAIRKEY,
231        "g": "elem,pair,jsonic",
232    });
233    if !list_pairs_allowed {
234        elem_pair["e"] = json!(ELEM_PAIR_ERR);
235    }
236    let mut elem_open = vec![
237        // Empty commas insert null elements. Note that close consumes a
238        // comma, so b:2 works.
239        json!({ "s": "#CA #CA", "b": 2, "u": { "done": true }, "a": ELEM_DOUBLE_COMMA,
240                "g": "list,elem,imp,null,jsonic" }),
241        json!({ "s": "#CA", "u": { "done": true }, "a": ELEM_SINGLE_COMMA,
242                "g": "list,elem,imp,null,jsonic" }),
243        elem_pair,
244    ];
245    if options.list.child {
246        // list.child: bare colon `:value` stores value on child$ property.
247        elem_open.push(json!({ "s": "#CL", "p": "val",
248                               "u": { "done": true, "child": true, "list": true },
249                               "g": "elem,child,jsonic" }));
250    }
251
252    json!({
253        // The schema version of the native-value builtins this grammar
254        // binds to (object/array/reset, and json's key/setval/push/value).
255        "v": 2,
256
257        "rule": {
258            "val": {
259                "open": {
260                    "alts": [
261                        // A pair key: `a: ...`. Implicit map at top level.
262                        // @reset$ clears the parent-seeded node (mirrors
263                        // json's #OB/#OS open alts) so val-close coalesces
264                        // to the pushed map, not the inherited parent
265                        // container.
266                        { "s": "#KEY #CL", "c": { "d": 0 }, "p": "map", "b": 2, "a": "@reset$",
267                          "g": "pair,jsonic,top" },
268
269                        // A pair dive: `a:b: ...`. Increment counter n.pk
270                        // to indicate pair-key depth (for extensions).
271                        // a:9 -> pk=undef, a:b:9 -> pk=1, a:b:c:9 -> pk=2.
272                        { "s": "#KEY #CL", "p": "map", "b": 2, "n": { "pk": 1 }, "a": "@reset$",
273                          "g": "pair,jsonic" },
274
275                        // A plain value: `x` `"x"` `1` `true` ....
276                        { "s": "#VAL", "a": "@reset$", "g": "val,json" },
277
278                        // Implicit ends `{a:}` -> {"a":null},
279                        // `[a:]` -> [{"a":null}].
280                        { "s": ["#CB #CS"], "b": 1, "c": { "d": { "$gt": 0 } }, "a": "@reset$",
281                          "g": "val,imp,null,jsonic" },
282
283                        // Implicit list at top level starting with a
284                        // comma: `,` -> [null]. Allocate the (implicit)
285                        // array here: this path does not go through
286                        // list-bo's implist promotion, and json's @array$
287                        // only runs for `[`.
288                        { "s": "#CA", "c": { "d": 0 }, "p": "list", "b": 1, "a": "@array$",
289                          "k": { "array$": { "implicit": true } }, "g": "list,imp,jsonic" },
290
291                        // Value is implicitly null when empty before commas.
292                        { "s": "#CA", "b": 1, "a": "@reset$", "g": "list,val,imp,null,jsonic" },
293
294                        { "s": "#ZZ", "g": "jsonic" },
295                    ],
296                    "inject": { "append": true, "delete": [2] },
297                },
298                "close": {
299                    "alts": [
300                        // Explicitly close map or list: `}`, `]`
301                        { "s": ["#CB #CS"], "b": 1, "g": "val,json,close", "e": VAL_CLOSE_ERROR },
302
303                        // Implicit list (comma sep) only allowed at top
304                        // level: `1,2`.
305                        { "s": "#CA", "c": { "n.dlist": { "$lte": 0 }, "n.dmap": { "$lte": 0 } },
306                          "r": "list", "u": { "implist": true },
307                          "g": "list,val,imp,comma,jsonic" },
308
309                        // Implicit list (space sep) only allowed at top
310                        // level: `1 2`.
311                        { "c": { "n.dlist": { "$lte": 0 }, "n.dmap": { "$lte": 0 } },
312                          "r": "list", "u": { "implist": true },
313                          "g": "list,val,imp,space,jsonic", "b": 1 },
314
315                        { "s": "#ZZ", "g": "end,jsonic" },
316                    ],
317                    "inject": { "append": true },
318                },
319            },
320
321            "map": {
322                "open": [
323                    // Auto-close; fail if rule.finish option is false.
324                    // Allocate the (empty) object so `{` -> `{}` when
325                    // finish is allowed.
326                    { "s": "#OB #ZZ", "b": 1, "a": "@object$", "e": FINISH, "g": "end,jsonic" },
327                ],
328                "close": {
329                    "alts": [
330                        // Normal end of map, no path dive.
331                        { "s": "#CB", "c": { "n.pk": { "$lte": 0 } }, "g": "end,json" },
332
333                        // Not yet at end of path dive, keep ascending.
334                        { "s": "#CB", "b": 1, "g": "path,close,jsonic" },
335
336                        // End of implicit path.
337                        { "s": ["#CA #CS #VAL"], "b": 1, "g": "end,path,jsonic" },
338
339                        // Auto-close; fail if rule.finish option is false.
340                        { "s": "#ZZ", "e": FINISH, "g": "end,jsonic" },
341                    ],
342                    "inject": { "append": true, "delete": [0] },
343                },
344            },
345
346            "list": {
347                "open": [
348                    // An implicit (bracket-less) list continues with an
349                    // element: the first value was promoted in list-bo.
350                    { "c": { "prev.u.implist": { "$eq": true } }, "p": "elem" },
351                ],
352                "close": {
353                    "alts": [
354                        // Fail if rule.finish option is false.
355                        { "s": "#ZZ", "e": FINISH, "g": "end,jsonic" },
356                    ],
357                    "inject": { "append": true },
358                },
359            },
360
361            "pair": {
362                "open": {
363                    "alts": pair_open,
364                    "inject": { "append": true, "clear": true },
365                },
366                "close": {
367                    "alts": [
368                        // End of map, reset implicit depth counter so that
369                        // a:b:c:1,d:2 -> {a:{b:{c:1}},d:2}
370                        { "s": "#CB", "c": { "n.pk": { "$lte": 0 } }, "b": 1,
371                          "g": "map,pair,close,json" },
372
373                        // Ignore trailing comma at end of map.
374                        { "s": "#CA #CB", "c": { "n.pk": { "$lte": 0 } }, "b": 1,
375                          "g": "map,pair,comma,jsonic" },
376
377                        { "s": "#CA #ZZ", "g": "end,jsonic" },
378
379                        // Comma means a new pair at same pair-key level.
380                        { "s": "#CA", "c": { "n.pk": { "$lte": 0 } }, "r": "pair",
381                          "g": "map,pair,sync,json" },
382
383                        // Comma means a new pair if implicit top level map.
384                        { "s": "#CA", "c": { "n.dmap": { "$lte": 1 } }, "r": "pair",
385                          "g": "map,pair,sync,jsonic" },
386
387                        // Value means a new pair if implicit top level map.
388                        { "s": "#KEY", "c": { "n.dmap": { "$lte": 1 } }, "r": "pair", "b": 1,
389                          "g": "map,pair,imp,sync,jsonic" },
390
391                        // End of implicit path (eg. a:b:1), keep closing
392                        // until pk=0.
393                        { "s": ["#CB #CA #CS #KEY"], "c": { "n.pk": { "$gt": 0 } }, "b": 1,
394                          "g": "map,pair,imp,path,close,jsonic" },
395
396                        // Can't close a map with `]`
397                        { "s": "#CS", "e": ELEM_CLOSE_ERR, "g": "end,jsonic" },
398
399                        // Fail if auto-close option is false.
400                        { "s": "#ZZ", "e": FINISH, "g": "map,pair,end,json" },
401
402                        // Who needs commas anyway?
403                        { "r": "pair", "b": 1, "g": "map,pair,imp,jsonic" },
404                    ],
405                    "inject": { "append": true, "delete": [0, 1] },
406                },
407            },
408
409            "elem": {
410                "open": elem_open,
411                "close": {
412                    "alts": [
413                        // Ignore trailing comma.
414                        { "s": ["#CA", "#CS #ZZ"], "b": 1, "g": "list,elem,comma,jsonic" },
415
416                        // Next element.
417                        { "s": "#CA", "r": "elem", "g": "list,elem,sync,json" },
418
419                        // End of list.
420                        { "s": "#CS", "b": 1, "g": "list,elem,close,json" },
421
422                        // Fail if auto-close option is false.
423                        { "s": "#ZZ", "e": FINISH, "g": "list,elem,end,json" },
424
425                        // Can't close a list with `}`
426                        { "s": "#CB", "e": ELEM_CLOSE_ERR, "g": "end,jsonic" },
427
428                        // Who needs commas anyway?
429                        { "r": "elem", "b": 1, "g": "list,elem,imp,jsonic" },
430                    ],
431                    "inject": { "delete": [-1, -2] },
432                },
433            },
434        },
435    })
436}
437
438/// The relaxed alternates, phase two. See [`jsonic_document`].
439fn jsonic_document_append() -> serde_json::Value {
440    json!({
441        "v": 2,
442        "rule": {
443            "val": {
444                // Move "There's more JSON" to end.
445                "close": { "alts": [], "inject": { "move": [1, -1] } },
446            },
447            "map": {
448                "open": {
449                    "alts": [
450                        // Pair from implicit map (no braces). json's
451                        // map-open alts only match `#OB`, so the brace-less
452                        // entry must allocate the container itself:
453                        // @object$ with the static implicit:true flag.
454                        { "s": "#KEY #CL", "p": "pair", "b": 2, "a": "@object$",
455                          "k": { "object$": { "implicit": true } },
456                          "g": "pair,list,val,imp,jsonic" },
457                    ],
458                    "inject": { "append": true },
459                },
460            },
461            "list": {
462                "open": {
463                    "alts": [
464                        // Initial comma [, will insert null as [null,
465                        { "s": "#CA", "p": "elem", "b": 1, "g": "list,elem,val,imp,jsonic" },
466
467                        // Another element.
468                        { "p": "elem", "g": "list,elem,jsonic" },
469                    ],
470                    "inject": { "append": true },
471                },
472            },
473        },
474    })
475}
476
477// ---------------------------------------------------------------------------
478// Node helpers
479// ---------------------------------------------------------------------------
480
481/// Assign a rule's node: the Rust spelling of TypeScript `r.node = v`.
482///
483/// A pushed or replaced rule SHARES its parent's node cell, so writing
484/// through `rule.node.borrow_mut()` would overwrite the parent's node too.
485/// Assigning installs a fresh cell instead. The cell is borrowed directly
486/// only to mutate a container the rule genuinely shares (push onto the
487/// enclosing list, insert into the enclosing map).
488fn set_node(rule: &mut Rule, value: Value) {
489    rule.node = Rc::new(RefCell::new(value));
490}
491
492/// Take a container out of its `Arc`, copying only when it is shared.
493fn unwrap_arc<T: Clone>(shared: Arc<T>) -> T {
494    Arc::try_unwrap(shared).unwrap_or_else(|shared| (*shared).clone())
495}
496
497fn map_get(node: &Value, key: &str) -> Option<Value> {
498    match node {
499        Value::Object(map) => map.get(key).cloned(),
500        Value::MapRef(map) => map.value.get(key).cloned(),
501        _ => None,
502    }
503}
504
505/// Insert into a map node. A non-map node (a list carrying a `key:value`
506/// pair under `list.property`) takes nothing, as in the Go port: a JSON
507/// array has no properties to carry.
508fn map_insert(node: &mut Value, key: String, value: Value) {
509    match node {
510        Value::Object(map) => {
511            Arc::make_mut(map).insert(key, value);
512        }
513        Value::MapRef(map) => {
514            Arc::make_mut(map).value.insert(key, value);
515        }
516        _ => {}
517    }
518}
519
520fn list_push(node: &mut Value, value: Value) {
521    match node {
522        Value::Array(items) => Arc::make_mut(items).push(value),
523        Value::ListRef(list) => Arc::make_mut(list).value.push(value),
524        _ => {}
525    }
526}
527
528/// A scalar a plugin deliberately set: not the no-value sentinel, not
529/// null, not a container. TypeScript's test is `'object' !== typeof`, so
530/// a `Text` (a `String` object there) counts as a container.
531fn is_primitive(value: &Value) -> bool {
532    matches!(value, Value::Bool(_) | Value::Number(_) | Value::String(_))
533}
534
535fn flag(rule: &Rule, name: &str) -> bool {
536    matches!(rule.u.get(name), Some(Value::Bool(true)))
537}
538
539/// The completed child's node, with "no value" read as `null`, as JSON has
540/// no `undefined`.
541fn child_or_null(rule: &Rule) -> Value {
542    if rule.child_node.is_undefined() {
543        Value::Null
544    } else {
545        rule.child_node.clone()
546    }
547}
548
549fn is_fixed(tin: Tin, options: &Options) -> bool {
550    options.fixed.tokens.values().any(|token| token.tin == tin)
551}
552
553/// Whether a matched token carries no value, as `r.o0.resolveVal` reads
554/// it in the canonical engine: end of source, or a fixed token that is
555/// still as the lexer made it. This engine's lexer gives a fixed token its
556/// own source text as `val` (`}` carries `"}"`), where the canonical one
557/// gives it nothing, so the source text IS the no-value. Anything else on
558/// a fixed token was put there by a plugin action in `val` open (the
559/// `parser-mixed-token` shape, `r.o0.val = '@' + r.o1.val`) and is a
560/// value like any other.
561fn carries_no_value(token: &Token, options: &Options) -> bool {
562    token.tin == TIN_ZZ
563        || (is_fixed(token.tin, options)
564            && matches!(&token.val, Value::String(text) if text == token.src.as_str()))
565}
566
567/// Recursively merge `overlay` into `base`: objects by key, arrays by
568/// index, everything else replaced by the overlay. The port of the
569/// `deep()` utility the TypeScript grammar merges duplicate keys with,
570/// over the engine's native values, keeping the base's container kind
571/// (a `MapRef` stays a `MapRef` with its metadata). The prototype
572/// pollution guard is the same one: `__proto__`, `constructor` and
573/// `prototype` keys of the overlay are skipped.
574pub fn deep_merge(base: Value, overlay: Value) -> Value {
575    const DANGEROUS: [&str; 3] = ["__proto__", "constructor", "prototype"];
576    fn merge_entries(base: &mut IndexMap<String, Value>, overlay: IndexMap<String, Value>) {
577        for (key, value) in overlay {
578            if DANGEROUS.contains(&key.as_str()) {
579                continue;
580            }
581            let previous = base.get(&key).cloned().unwrap_or(Value::Undefined);
582            base.insert(key, deep_merge(previous, value));
583        }
584    }
585    fn merge_items(base: &mut Vec<Value>, overlay: Vec<Value>) {
586        for (index, value) in overlay.into_iter().enumerate() {
587            if index < base.len() {
588                let previous = std::mem::replace(&mut base[index], Value::Undefined);
589                base[index] = deep_merge(previous, value);
590            } else {
591                base.push(value);
592            }
593        }
594    }
595    match (base, overlay) {
596        (base, Value::Undefined) => base,
597        (Value::Object(base), Value::Object(overlay)) => {
598            let mut base = unwrap_arc(base);
599            merge_entries(&mut base, unwrap_arc(overlay));
600            Value::object(base)
601        }
602        (Value::Object(base), Value::MapRef(overlay)) => {
603            let mut base = unwrap_arc(base);
604            merge_entries(&mut base, unwrap_arc(overlay).value);
605            Value::object(base)
606        }
607        (Value::MapRef(base), Value::Object(overlay)) => {
608            let mut base = unwrap_arc(base);
609            merge_entries(&mut base.value, unwrap_arc(overlay));
610            Value::MapRef(Arc::new(base))
611        }
612        (Value::MapRef(base), Value::MapRef(overlay)) => {
613            let mut base = unwrap_arc(base);
614            merge_entries(&mut base.value, unwrap_arc(overlay).value);
615            Value::MapRef(Arc::new(base))
616        }
617        (Value::Array(base), Value::Array(overlay)) => {
618            let mut base = unwrap_arc(base);
619            merge_items(&mut base, unwrap_arc(overlay));
620            Value::array(base)
621        }
622        (Value::Array(base), Value::ListRef(overlay)) => {
623            let mut base = unwrap_arc(base);
624            merge_items(&mut base, unwrap_arc(overlay).value);
625            Value::array(base)
626        }
627        (Value::ListRef(base), Value::Array(overlay)) => {
628            let mut base = unwrap_arc(base);
629            merge_items(&mut base.value, unwrap_arc(overlay));
630            Value::ListRef(Arc::new(base))
631        }
632        (Value::ListRef(base), Value::ListRef(overlay)) => {
633            let mut base = unwrap_arc(base);
634            merge_items(&mut base.value, unwrap_arc(overlay).value);
635            Value::ListRef(Arc::new(base))
636        }
637        (_, overlay) => overlay,
638    }
639}
640
641/// Combine a repeated value with the one already stored: the `map.merge`
642/// function when the caller set one, else a deep merge under `map.extend`,
643/// else the later value replaces the earlier.
644fn combine(previous: Value, value: Value, rule: &mut Rule, context: &mut Context) -> Value {
645    if let Some(merge) = context.options.map.merge.clone() {
646        merge(previous, value, rule, context)
647    } else if context.options.map.extend {
648        deep_merge(previous, value)
649    } else {
650        value
651    }
652}
653
654// ---------------------------------------------------------------------------
655// The depth guard
656// ---------------------------------------------------------------------------
657
658/// How many nested containers a parse may hold before it is refused.
659///
660/// The engine's parse loop is iterative, but the value it hands back is a
661/// tree the engine walks with the call stack to display, convert or drop,
662/// one frame per level, and a source of a few thousand `[` ended the
663/// process with a stack overflow, an abort rather than an error, before
664/// this limit existed (past 6,000 levels in a release build and 1,500 in
665/// a debug build on a 2 MiB thread). TypeScript and Go have no limit,
666/// which is recorded in `DIVERGENCE.md`; a document a person writes does
667/// not come near this one. The number is the one `tabnas_json` uses, so
668/// the two Rust crates bound nesting the same way, and it is the depth
669/// `serde_json` accepts.
670const DEPTH_LIMIT: usize = 127;
671
672/// The name the depth check is installed under, as a parse guard.
673///
674/// A guard rather than the parse budget, because the budget is one slot
675/// that a caller's `parse_budget` replaces, and the bound went with it
676/// whenever a caller set a budget of its own. Nothing a caller does to
677/// the budget reaches a guard. The name is the one `tabnas_json` installs
678/// its check under, so jsonic's replaces json's; a grammar layered on
679/// jsonic that allows more depth (JSONC) or nests through other rules
680/// (INI's `dive`, YAML's block collections) installs its own check under
681/// this name to replace jsonic's.
682const DEPTH_GUARD: &str = "depth";
683
684/// Whether a rule of this name holds a container: a `map` or a `list`.
685fn is_container(name: &str) -> bool {
686    name == "map" || name == "list"
687}
688
689/// How many containers are open at this point in the parse: the `map` and
690/// `list` rules on the stack, plus the rule the loop is working on, which
691/// the engine hands over separately as `context.rule`. Counted from the
692/// rule NAMES rather than `rule_stack.len()`, because the stack holds
693/// about three rules per level (`val`, then `map` or `list`, then `pair`
694/// or `elem`) and a length-based limit would encode that ratio. A pair
695/// dive (`a:b:c:1`) opens one implicit map per key, so it counts too.
696fn depth(context: &Context) -> usize {
697    let current = usize::from(
698        context
699            .rule
700            .as_ref()
701            .is_some_and(|rule| is_container(&rule.name)),
702    );
703    containers_on_stack(context) + current
704}
705
706/// The containers on the stack, carried from one step to the next.
707///
708/// The guard runs at every step, so counting the whole stack each time
709/// cost a step as much as the stack is deep, and a parse nested through
710/// rules that are not containers took time growing with the square of its
711/// depth: XML's elements, which count as nothing here, took 2 s at 8,000
712/// levels (tabnas/jsonic#91). A grammar nested through containers never
713/// got deep enough to notice, since the limit stops it at 127.
714///
715/// The engine changes the stack only at the top: a pop truncates it and a
716/// push appends the new rule's snapshot, and the rules below the top stay
717/// as they were (the engine checks this in debug builds). A rule's
718/// ancestors are fixed for as long as it lives, so the containers at or
719/// below a stack position are known once the rule at that position is.
720/// The count is kept for each position with the id of the rule there,
721/// which is unique within a parse, and a step recounts only from the
722/// first position whose rule has changed, usually the top. A callback
723/// that writes into `context.rule_stack` below the top is not followed.
724struct StackCount {
725    /// The context the count describes, by address.
726    context: usize,
727    /// The last step counted. A parse's steps go up from 1, so a first
728    /// step, or one lower than the last, is a new parse in the same place;
729    /// the same step again is the same step, asked twice.
730    iteration: usize,
731    /// For each stack position, the id of the rule there and the
732    /// containers at or below it.
733    frames: Vec<(usize, usize)>,
734    /// Frames looked at, all told: what a step costs, for the tests.
735    #[cfg(test)]
736    examined: usize,
737}
738
739thread_local! {
740    // Per thread, as a parse runs on one; a nested parse on the same
741    // thread has a context of its own and starts the count afresh.
742    static STACK_COUNT: RefCell<StackCount> = const {
743        RefCell::new(StackCount {
744            context: 0,
745            iteration: 0,
746            frames: Vec::new(),
747            #[cfg(test)]
748            examined: 0,
749        })
750    };
751}
752
753fn containers_on_stack(context: &Context) -> usize {
754    let stack = &context.rule_stack;
755    STACK_COUNT.with(|count| {
756        let mut count = count.borrow_mut();
757        let here = context as *const Context as usize;
758        if count.context != here || context.iteration == 1 || context.iteration < count.iteration {
759            count.context = here;
760            count.frames.clear();
761        }
762        count.iteration = context.iteration;
763        let top = count.frames.len().min(stack.len());
764        let mut kept = top;
765        while kept > 0 && count.frames[kept - 1].0 != stack[kept - 1].i {
766            kept -= 1;
767        }
768        #[cfg(test)]
769        {
770            count.examined += (top - kept) + 1 + (stack.len() - kept);
771        }
772        count.frames.truncate(kept);
773        let mut containers = count.frames.last().map_or(0, |&(_, below)| below);
774        for rule in &stack[kept..] {
775            containers += usize::from(is_container(&rule.name));
776            count.frames.push((rule.i, containers));
777        }
778        containers
779    })
780}
781
782/// The depth guard: `DEPTH_LIMIT` levels parse, the next one is refused
783/// with the engine's `cancel` code.
784fn within_depth_limit(context: &Context) -> bool {
785    depth(context) <= DEPTH_LIMIT
786}
787
788// ---------------------------------------------------------------------------
789// The closures the grammar names
790// ---------------------------------------------------------------------------
791
792/// Resolve the matched open token to its value, as `r.o0.resolveVal` does:
793/// the end-of-source token and an untouched fixed token carry no value
794/// (see [`carries_no_value`]), and under `info.text` a string keeps its
795/// quote character.
796fn resolve_token(rule: &mut Rule, context: &mut Context) -> Value {
797    let Some(token) = rule.o0().cloned() else {
798        return Value::Undefined;
799    };
800    if carries_no_value(&token, &context.options) {
801        return Value::Undefined;
802    }
803    let value = token.resolve_val(rule, context);
804    if context.options.info.text && matches!(token.tin, TIN_ST | TIN_TX) {
805        if let Value::String(string) = value {
806            let quote = if token.tin == TIN_ST {
807                token
808                    .src
809                    .as_str()
810                    .chars()
811                    .next()
812                    .map(String::from)
813                    .unwrap_or_default()
814            } else {
815                String::new()
816            };
817            return Value::Text(Text { quote, string });
818        }
819    }
820    value
821}
822
823/// jsonic's `val` before-close coalescing, ordered: child container, then
824/// a deliberate primitive a plugin set in `val` open, then the matched
825/// scalar token (which beats a stale parent-seeded container), then a
826/// deliberate container a plugin set, else no value (implicit null).
827///
828/// The child is read through [`Rule::has_child_value`] /
829/// [`Rule::child_value`], never the raw `child_node` field. A child that
830/// never installed a node cell of its own wrote into THIS rule's cell,
831/// and the engine then leaves `child_node` undefined rather than hold a
832/// second copy-on-write handle on the container this rule is about to
833/// write into again. The accessors answer from the node in that case,
834/// which is what the canonical `r.child.node` reads — there the two are
835/// the same object. Reading the field directly makes such a val look
836/// childless, and `,` then parses as `null` instead of `[null]`.
837fn val_before_close(rule: &mut Rule, context: &mut Context) -> Result<(), ActionError> {
838    // Stash the value a plugin set in a val OPEN action (before any
839    // coalescing). json's @value$ close ALT action still runs after this
840    // and re-resolves the matched token, which would overwrite a plugin
841    // value; `val_after_close` restores it. A normal value rule @reset$s
842    // its node in open, so this is undefined except when a plugin
843    // deliberately set it.
844    let openval = rule.node.borrow().clone();
845    rule.u_mut().insert("openval".to_string(), openval.clone());
846
847    let node = if rule.has_child_value() {
848        rule.child_value()
849    } else if is_primitive(&openval) {
850        return Ok(());
851    } else if rule.os() != 0 {
852        resolve_token(rule, context)
853    } else if !openval.is_undefined() {
854        return Ok(());
855    } else {
856        Value::Undefined
857    };
858    set_node(rule, node);
859    Ok(())
860}
861
862/// After-close: json's @value$ close alt re-resolves the matched token and
863/// so overwrites a value a plugin set in a val open action. Restore the
864/// plugin's value, but only a PRIMITIVE one set with no child: a
865/// parent-seeded stale node is always a container.
866///
867/// The same re-resolution reads a fixed token's value, and this engine's
868/// fixed tokens carry their source text where the canonical engine's
869/// carry nothing: `a:,b:` would give `a` the value `","`. The value the
870/// canonical @value$ produces for a valueless token is put back here.
871///
872/// "With no child" is asked through [`Rule::has_child_value`] for the
873/// reason `val_before_close` reads the child through it.
874fn val_after_close(rule: &mut Rule, context: &mut Context) -> Result<(), ActionError> {
875    if rule.has_child_value() {
876        return Ok(());
877    }
878    let openval = rule.u.get("openval").cloned().unwrap_or(Value::Undefined);
879    if is_primitive(&openval) {
880        set_node(rule, openval);
881    } else if rule
882        .o0()
883        .is_some_and(|token| carries_no_value(token, &context.options))
884    {
885        set_node(rule, Value::Undefined);
886    }
887    Ok(())
888}
889
890fn bump(rule: &mut Rule, counter: &str) {
891    let depth = rule.n.get(counter).copied().unwrap_or(0);
892    rule.n_mut().insert(counter.to_string(), depth + 1);
893}
894
895fn map_before_open(rule: &mut Rule, _context: &mut Context) -> Result<(), ActionError> {
896    bump(rule, "dmap");
897    Ok(())
898}
899
900/// Increment the list depth and, for an implicit (bracket-less) list,
901/// allocate the array and promote the already-parsed first value into it.
902/// json's @array$ never runs here: its list-open alts only match `[`.
903fn list_before_open(rule: &mut Rule, context: &mut Context) -> Result<(), ActionError> {
904    bump(rule, "dlist");
905    let promoted = rule.prev_rule.as_ref().and_then(|prev| {
906        matches!(prev.u.get("implist"), Some(Value::Bool(true))).then(|| prev.node.borrow().clone())
907    });
908    if let Some(first) = promoted {
909        let first = if first.is_undefined() {
910            Value::Null
911        } else {
912            first
913        };
914        let list = if context.options.info.list {
915            Value::ListRef(Arc::new(ListRef {
916                value: vec![first],
917                implicit: true,
918                child: None,
919                meta: IndexMap::new(),
920            }))
921        } else {
922            Value::array(vec![first])
923        };
924        // In place, not a fresh cell: a replacing rule shares the cell of
925        // the rule it replaced, and that rule's snapshot is `prev`. This
926        // is `r.prev.node = r.node` in the canonical grammar.
927        *rule.node.borrow_mut() = list;
928    }
929    Ok(())
930}
931
932fn map_before_close(rule: &mut Rule, context: &mut Context) -> Result<(), ActionError> {
933    if context.options.info.map {
934        let implicit = rule.o0().is_none_or(|token| token.tin != TIN_OB);
935        if let Value::MapRef(map) = &mut *rule.node.borrow_mut() {
936            Arc::make_mut(map).implicit = implicit;
937        }
938    }
939    Ok(())
940}
941
942fn list_before_close(rule: &mut Rule, _context: &mut Context) -> Result<(), ActionError> {
943    let implicit = rule.o0().is_none_or(|token| token.tin != TIN_OS);
944    if let Value::ListRef(list) = &mut *rule.node.borrow_mut() {
945        Arc::make_mut(list).implicit = implicit;
946    }
947    Ok(())
948}
949
950/// Set `key: value` on the node, the port of the TypeScript `pairval`.
951/// The previous value at the key is read straight off the node so a
952/// repeated key (`a:1,a:2`) or a deep object can merge or extend.
953fn pairval(rule: &mut Rule, context: &mut Context) {
954    let Some(Value::String(key)) = rule.u.get("key").cloned() else {
955        return;
956    };
957    let value = child_or_null(rule);
958
959    // Do not set unsafe keys on arrays (objects have no prototype chain).
960    if flag(rule, "list")
961        && context.options.safe.key
962        && (key == "__proto__" || key == "constructor")
963    {
964        return;
965    }
966
967    // Drop keys that match the info marker to preserve metadata.
968    if context.options.info.map && key == context.options.info.marker {
969        return;
970    }
971
972    let previous = {
973        let node = rule.node.borrow();
974        map_get(&node, &key)
975    };
976    let value = match previous {
977        None | Some(Value::Null) | Some(Value::Undefined) => value,
978        Some(previous) => combine(previous, value, rule, context),
979    };
980    map_insert(&mut rule.node.borrow_mut(), key, value);
981}
982
983/// Store a bare-colon `:value` on the map's `child$` property, merging
984/// with an earlier one the way a repeated key merges.
985fn map_child(rule: &mut Rule, context: &mut Context) {
986    let value = child_or_null(rule);
987    let previous = {
988        let node = rule.node.borrow();
989        map_get(&node, "child$")
990    };
991    let value = match previous {
992        None | Some(Value::Undefined) => value,
993        Some(previous) => combine(previous, value, rule, context),
994    };
995    map_insert(&mut rule.node.borrow_mut(), "child$".to_string(), value);
996}
997
998/// Store a bare-colon `:value` on the list. A TypeScript array takes it as
999/// a `child$` property; here the list becomes a [`ListRef`] carrying it
1000/// as `child`, the same wrapper `info.list` produces, so a list that
1001/// received one is distinguishable from its plain elements.
1002fn list_child(rule: &mut Rule, context: &mut Context) {
1003    let value = child_or_null(rule);
1004    let previous = {
1005        let node = rule.node.borrow();
1006        match &*node {
1007            Value::ListRef(list) => list.child.as_deref().cloned(),
1008            _ => None,
1009        }
1010    };
1011    let value = match previous {
1012        None => value,
1013        Some(previous) => combine(previous, value, rule, context),
1014    };
1015    let mut node = rule.node.borrow_mut();
1016    let mut list = match std::mem::replace(&mut *node, Value::Undefined) {
1017        Value::Array(items) => ListRef {
1018            value: unwrap_arc(items),
1019            implicit: false,
1020            child: None,
1021            meta: IndexMap::new(),
1022        },
1023        Value::ListRef(list) => unwrap_arc(list),
1024        other => {
1025            *node = other;
1026            return;
1027        }
1028    };
1029    list.child = Some(Box::new(value));
1030    *node = Value::ListRef(Arc::new(list));
1031}
1032
1033fn pair_before_close(rule: &mut Rule, context: &mut Context) -> Result<(), ActionError> {
1034    if flag(rule, "pair") {
1035        pairval(rule, context);
1036    }
1037    if flag(rule, "child") {
1038        map_child(rule, context);
1039    }
1040    Ok(())
1041}
1042
1043/// jsonic's `elem` before-close: the done-guarded push (json's strict
1044/// version pushes every child, which would double-add the done-flagged
1045/// implicit nulls, pairs and children), then `list.pair` / `list.property`
1046/// pairs, then `list.child` values.
1047fn elem_before_close(rule: &mut Rule, context: &mut Context) -> Result<(), ActionError> {
1048    if !flag(rule, "done") && !rule.child_node.is_undefined() {
1049        let child = rule.child_node.clone();
1050        list_push(&mut rule.node.borrow_mut(), child);
1051    }
1052
1053    if flag(rule, "pair") {
1054        if context.options.list.pair {
1055            // list.pair: push pair as object element into the list.
1056            if let Some(Value::String(key)) = rule.u.get("key").cloned() {
1057                let mut pair = IndexMap::new();
1058                pair.insert(key, child_or_null(rule));
1059                list_push(&mut rule.node.borrow_mut(), Value::object(pair));
1060            }
1061        } else {
1062            pairval(rule, context);
1063        }
1064    }
1065
1066    if flag(rule, "child") {
1067        list_child(rule, context);
1068    }
1069    Ok(())
1070}
1071
1072/// Capture the pair key from the first open token: the decoded value of a
1073/// text or string token, the SOURCE of anything else, so `1:x` keys "1"
1074/// and `true:1` keys "true".
1075fn pairkey(rule: &mut Rule, _context: &mut Context) -> Result<(), ActionError> {
1076    let Some(token) = rule.o0().cloned() else {
1077        return Ok(());
1078    };
1079    let key = if matches!(token.tin, TIN_ST | TIN_TX) {
1080        match token.val {
1081            Value::String(text) => text,
1082            Value::Text(text) => text.string,
1083            Value::Number(number) if number.fract() == 0.0 && number.is_finite() => {
1084                format!("{number:.0}")
1085            }
1086            other => other.to_string(),
1087        }
1088    } else {
1089        token.src.as_str().to_string()
1090    };
1091    rule.u_mut().insert("key".to_string(), Value::String(key));
1092    Ok(())
1093}
1094
1095fn push_null(rule: &mut Rule, _context: &mut Context) -> Result<(), ActionError> {
1096    list_push(&mut rule.node.borrow_mut(), Value::Null);
1097    Ok(())
1098}
1099
1100/// Register every closure the grammar document names. Registered before
1101/// the document is installed, because the document is what looks them
1102/// up; re-registering on an instance that already has them is harmless.
1103fn register_refs(parser: &mut Tabnas) {
1104    parser.alt_error(FINISH, |_rule, context| {
1105        if context.options.rule.finish {
1106            return None;
1107        }
1108        // The CODE, not just the rejection: with finish off an
1109        // unterminated structure is `end_of_source`, as in TypeScript.
1110        let mut token = context.t0()?.clone();
1111        token.bad("end_of_source");
1112        Some(token)
1113    });
1114    parser.alt_error(VAL_CLOSE_ERROR, |rule, context| {
1115        if rule.d == 0 {
1116            context.t0().cloned()
1117        } else {
1118            None
1119        }
1120    });
1121    parser.alt_error(ELEM_PAIR_ERR, |_rule, context| context.t0().cloned());
1122    parser.alt_error(ELEM_CLOSE_ERR, |rule, _context| rule.c0().cloned());
1123
1124    parser.action_with_context(PAIRKEY, pairkey);
1125    parser.action_with_context(ELEM_DOUBLE_COMMA, push_null);
1126    parser.action_with_context(ELEM_SINGLE_COMMA, push_null);
1127
1128    parser.state_action_ref(VAL_BC, val_before_close);
1129    parser.state_action_ref(VAL_AC, val_after_close);
1130    parser.state_action_ref(MAP_BO, map_before_open);
1131    parser.state_action_ref(MAP_BC, map_before_close);
1132    parser.state_action_ref(LIST_BO, list_before_open);
1133    parser.state_action_ref(LIST_BC, list_before_close);
1134    parser.state_action_ref(PAIR_BC, pair_before_close);
1135    parser.state_action_ref(ELEM_BC, elem_before_close);
1136}
1137
1138/// Whether the relaxed grammar is already on this instance, judged by the
1139/// one thing only jsonic installs: its replacement of the `val`
1140/// before-close phase.
1141fn grammar_installed(parser: &Tabnas) -> bool {
1142    parser
1143        .rules
1144        .get("val")
1145        .is_some_and(|spec| spec.bc.iter().any(|action| action == VAL_BC))
1146}
1147
1148// ---------------------------------------------------------------------------
1149// Public surface
1150// ---------------------------------------------------------------------------
1151
1152/// Register the relaxed-JSON grammar rules (`val` / `map` / `list` /
1153/// `pair` / `elem`) on `parser` WITHOUT applying jsonic's option branding,
1154/// so other grammar plugins can layer their own syntax on the jsonic core
1155/// while managing their own option set. The counterpart of the TypeScript
1156/// `registerJsonicGrammar` export and the Go `RegisterJsonicGrammar`.
1157///
1158/// The standard-JSON core is installed first, through
1159/// [`tabnas_json::json`], then the relaxed alternates and lifecycle
1160/// actions are woven around it, and a parse guard refusing nesting past
1161/// 127 containers (with the engine's `cancel` code) goes on last, under
1162/// the name `depth`. A caller's `parse_budget` does not replace a guard,
1163/// so the bound holds whatever budget the caller sets. Registration is
1164/// idempotent: an instance that already carries the grammar is left
1165/// alone, so a plugin re-run cannot double the alternates.
1166///
1167/// ```
1168/// let mut parser = tabnas::Tabnas::new();
1169/// tabnas_jsonic::register_jsonic_grammar(&mut parser)?;
1170/// assert_eq!(parser.parse("a:b:1")?.to_string(), r#"{"a":{"b":1}}"#);
1171/// # Ok::<(), Box<dyn std::error::Error>>(())
1172/// ```
1173pub fn register_jsonic_grammar(parser: &mut Tabnas) -> Result<(), GrammarError> {
1174    if grammar_installed(parser) {
1175        return Ok(());
1176    }
1177    register_refs(parser);
1178
1179    // tabnas_json's one entry point applies its strict OPTIONS with its
1180    // rules. jsonic wants the rules alone, so the profile in force before
1181    // the call is put back after it.
1182    let relaxed = parser.config();
1183    tabnas_json::json(parser)?;
1184    parser
1185        .set_options(|options| restore_relaxed(options, &relaxed))
1186        .map_err(|error| GrammarError(error.0))?;
1187
1188    let options = parser.config();
1189    let phase_one = GrammarSpec::from_value(jsonic_document(&options))?;
1190    parser.grammar(&phase_one)?;
1191    let phase_two = GrammarSpec::from_value(jsonic_document_append())?;
1192    parser.grammar(&phase_two)?;
1193
1194    // A guard, not the budget: a budget the caller set, before the
1195    // grammar through `make_with` or after it, runs as it always did, and
1196    // the bound holds beside it (see `DEPTH_GUARD`). It replaces the guard
1197    // `tabnas_json` installed above, which counts the same containers
1198    // without carrying the count from one step to the next. Every step,
1199    // because a sampled check would let the parse run past the limit by
1200    // however many levels the sample missed.
1201    parser.parse_guard(DEPTH_GUARD, within_depth_limit);
1202    Ok(())
1203}
1204
1205/// Install jsonic on `parser`: the idiomatic engine plugin.
1206///
1207/// On a bare engine it applies jsonic's option defaults (the engine
1208/// already lexes relaxed JSON; this adds the jsonic error and hint
1209/// branding) and then registers the relaxed-JSON grammar. Use it before
1210/// any plugin that builds on jsonic's rules.
1211///
1212/// ```
1213/// let mut parser = tabnas::Tabnas::new();
1214/// tabnas_jsonic::jsonic(&mut parser)?;
1215/// let value = parser.parse("a:1,b:[x,y,z]")?;
1216/// assert_eq!(value.to_string(), r#"{"a":1,"b":["x","y","z"]}"#);
1217/// # Ok::<(), Box<dyn std::error::Error>>(())
1218/// ```
1219pub fn jsonic(parser: &mut Tabnas) -> Result<(), GrammarError> {
1220    apply_options(parser)?;
1221    register_jsonic_grammar(parser)
1222}
1223
1224/// The plugin form of [`jsonic`], for [`Tabnas::use_plugin`]. Installed
1225/// this way the grammar is re-applied to derived instances, as every
1226/// native plugin is.
1227///
1228/// ```
1229/// let mut parser = tabnas::Tabnas::new();
1230/// parser.use_plugin(tabnas_jsonic::plugin(), None)?;
1231/// assert_eq!(parser.parse("x,y,z")?.to_string(), r#"["x","y","z"]"#);
1232/// # Ok::<(), Box<dyn std::error::Error>>(())
1233/// ```
1234pub fn plugin() -> Plugin {
1235    Plugin::new(PLUGIN_NAME, |parser, _options| {
1236        jsonic(parser).map_err(|error| PluginError(error.0))
1237    })
1238}
1239
1240/// The grammar-only plugin [`make_with`] registers, so that a derived
1241/// instance rebuilds the grammar against its own options without the
1242/// branding overwriting a caller's error identity. The Go `Make` registers
1243/// its `grammarPlugin` for the same reason.
1244fn grammar_plugin() -> Plugin {
1245    Plugin::new(PLUGIN_NAME, |parser, _options| {
1246        register_jsonic_grammar(parser).map_err(|error| PluginError(error.0))
1247    })
1248}
1249
1250/// Build a relaxed-JSON parser with caller options: the counterpart of
1251/// `Jsonic.make(options)` and the Go `Make(opts)`.
1252///
1253/// jsonic's branding goes on first, then `configure` runs over the
1254/// options, so a caller's own `errmsg.name` or lexer setting wins, and
1255/// then the grammar is installed against the finished options, which is
1256/// what decides the option-conditional alternates (`map.child`,
1257/// `list.child`, `list.pair`). `rule.include` and `rule.exclude` are
1258/// honoured by the engine at parse time, so they may be set here too.
1259///
1260/// The parser declares `lex.window`, so that [`Tabnas::parse_reader`]
1261/// reads a reader a window at a time rather than whole (admin ADR-30):
1262/// every token of the relaxed grammar is cut by the engine's own matchers,
1263/// and its actions read tokens, never the source. The setting goes on with
1264/// the branding, before `configure`, so a caller who sets
1265/// `options.lex.window` to false reads a reader whole. A grammar built on
1266/// this parser declares its own setting after installing its plugin, as
1267/// every grammar in the fleet that starts from it does; [`jsonic`] and
1268/// [`plugin`] declare none, since a host installs them beneath matchers of
1269/// its own.
1270///
1271/// Infallible by design: the documents are fixed literals, so a failure
1272/// here is a bug in this crate rather than anything a caller did.
1273///
1274/// ```
1275/// let parser = tabnas_jsonic::make_with(|options| options.number.lex = false);
1276/// assert_eq!(parser.parse("a:1, b:2")?.to_string(), r#"{"a":"1","b":"2"}"#);
1277/// # Ok::<(), tabnas_jsonic::JsonicError>(())
1278/// ```
1279pub fn make_with(configure: impl FnOnce(&mut Options)) -> Tabnas {
1280    let mut parser = Tabnas::new();
1281    apply_options(&mut parser).expect("the jsonic option document is fixed and valid");
1282    parser
1283        .set_options(|options| options.lex.window = true)
1284        .expect("lex.window sets");
1285    parser
1286        .set_options(configure)
1287        .expect("the caller's options apply to a fresh engine");
1288    parser
1289        .use_plugin(grammar_plugin(), None)
1290        .expect("the jsonic grammar documents are fixed and valid");
1291    parser
1292}
1293
1294/// Build a relaxed-JSON parser with the default options. It declares
1295/// `lex.window`, as [`make_with`] says.
1296///
1297/// ```
1298/// let parser = tabnas_jsonic::make();
1299/// assert_eq!(parser.parse("a:b:c:1")?.to_string(), r#"{"a":{"b":{"c":1}}}"#);
1300/// assert!(parser.parse("}").is_err());
1301/// # Ok::<(), tabnas_jsonic::JsonicError>(())
1302/// ```
1303pub fn make() -> Tabnas {
1304    make_with(|_| {})
1305}
1306
1307/// Exactly a standard JSON number.
1308fn strict_number() -> &'static Regex {
1309    static RE: OnceLock<Regex> = OnceLock::new();
1310    RE.get_or_init(|| {
1311        Regex::new(r"^-?(0|[1-9][0-9]*)(\.[0-9]+)?([eE][+-]?[0-9]+)?$")
1312            .expect("the strict-number pattern is a literal and compiles")
1313    })
1314}
1315
1316/// Where the candidate literal starting at `src` ends: at the next JSON
1317/// structural character or whitespace, the run the engine's lenient
1318/// number matcher would consider. `None` when `src` ends first.
1319fn literal_end(src: &str) -> Option<usize> {
1320    src.find(|c: char| c.is_whitespace() || matches!(c, ',' | '}' | ']' | ':' | '"' | '/'))
1321}
1322
1323/// Reject anything the engine's lenient number matcher would accept that
1324/// standard JSON does not: a leading `+`, leading zeros, a bare leading
1325/// or trailing `.`. The TypeScript `number.exclude` is a negative
1326/// lookahead the `regex` crate cannot express, so the positive pattern
1327/// plus an inversion lives in a `check` hook, the shape the Go port uses.
1328///
1329/// The literal is read through the lexer's window, so that a grammar built
1330/// on jsonic may declare `lex.window` (admin ADR-30): in a parse from a
1331/// reader the window may end before the literal does, and is then asked to
1332/// fill and the literal read again, so that the check judges what the
1333/// whole text shows it. It asks for twice what the window holds, so a long
1334/// literal costs its length to read and not its square. In a whole text
1335/// the fill only answers.
1336fn strict_number_check(lexer: &mut Lexer<'_>) -> LexCheckResult {
1337    // The hook runs wherever a number COULD be lexed, not only where one
1338    // starts, so it says nothing, and reads no further, unless a
1339    // number-ish literal is actually here.
1340    let starts_number = lexer
1341        .window()
1342        .chars()
1343        .next()
1344        .is_some_and(|c| c == '-' || c == '+' || c == '.' || c.is_ascii_digit());
1345    if !starts_number {
1346        return LexCheckResult::Continue;
1347    }
1348    loop {
1349        let window = lexer.window();
1350        if let Some(end) = literal_end(window) {
1351            return judge_literal(&window[..end]);
1352        }
1353        let held = window.chars().count();
1354        if !lexer.fill(held.saturating_mul(2).max(held + 1)) {
1355            // The source ends within what was asked for, and the window
1356            // holds the rest of it: the literal runs to its end, or to a
1357            // terminator the fill brought in.
1358            let window = lexer.window();
1359            return judge_literal(&window[..literal_end(window).unwrap_or(window.len())]);
1360        }
1361    }
1362}
1363
1364/// Continue where `literal` is exactly a standard JSON number, and skip
1365/// the number matcher where it is not.
1366fn judge_literal(literal: &str) -> LexCheckResult {
1367    if strict_number().is_match(literal) {
1368        LexCheckResult::Continue
1369    } else {
1370        LexCheckResult::Skip
1371    }
1372}
1373
1374/// The strict-JSON option profile of `Jsonic.make('json')`, as one
1375/// document so the number hook can be bound by name.
1376fn strict_json_document() -> serde_json::Value {
1377    json!({
1378        "options": {
1379            "text": { "lex": false },
1380            "number": {
1381                "hex": false, "oct": false, "bin": false, "sep": null,
1382                "check": STRICT_NUMBER_CHECK,
1383            },
1384            "string": {
1385                "chars": "\"",
1386                "multiChars": "",
1387                "allowUnknown": false,
1388                "escape": { "v": null },
1389                // No `\xHH` or `\u{...}`; strict JSON has only `\uXXXX`.
1390                "escapeStrict": true,
1391            },
1392            "comment": { "lex": false },
1393            "map": { "extend": false },
1394            "lex": { "empty": false },
1395            "rule": { "finish": false, "include": "json" },
1396            // Strict JSON keys are quoted strings only, never text,
1397            // numbers or keywords: `{1:1}` and `{null:null}` are errors.
1398            //
1399            // The three trailing nulls are load-bearing, and are exactly
1400            // what the canonical `ts/src/grammar.ts` writes. The engine
1401            // overlays a token set INDEX-WISE, as TypeScript's deep merge
1402            // treats an array: a null clears that position and the
1403            // positions beyond the overlay's length keep the default. A
1404            // bare `["#ST"]` therefore replaces only slot 0 of the default
1405            // `KEY: ['#TX', '#NR', '#ST', '#VL']` and leaves `#NR`, `#ST`
1406            // and `#VL` live, so the strict parser still accepts `{1:1}`.
1407            "tokenSet": { "KEY": ["#ST", null, null, null] },
1408        },
1409    })
1410}
1411
1412/// Build a parser that accepts strict JSON only: the counterpart of
1413/// `Jsonic.make('json')` and the Go `MakeJSON`.
1414///
1415/// It installs the full jsonic grammar, restricts it to the `json`-tagged
1416/// alternates and tightens the lexer: no unquoted keys or values, no
1417/// comments, no hex, octal or binary numbers, no leading zeros, no
1418/// trailing commas, no single or backtick quoted strings, no empty input.
1419///
1420/// It declares `lex.window`, as [`make_with`] does: the strict-number check
1421/// it installs reads the literal through the lexer's window.
1422///
1423/// ```
1424/// let strict = tabnas_jsonic::make_json();
1425/// assert_eq!(strict.parse(r#"{"a":[1,2]}"#)?.to_string(), r#"{"a":[1,2]}"#);
1426/// assert!(strict.parse("a:1,").is_err());
1427/// assert!(strict.parse("[01]").is_err());
1428/// # Ok::<(), tabnas_jsonic::JsonicError>(())
1429/// ```
1430pub fn make_json() -> Tabnas {
1431    let mut parser = Tabnas::new();
1432    apply_options(&mut parser).expect("the jsonic option document is fixed and valid");
1433    parser.imperative_lex_check_ref(STRICT_NUMBER_CHECK, strict_number_check);
1434    let strict = GrammarSpec::from_value(strict_json_document())
1435        .expect("the strict-JSON option document is fixed and valid");
1436    parser
1437        .grammar(&strict)
1438        .expect("the strict-JSON options apply to a fresh engine");
1439    parser
1440        .use_plugin(grammar_plugin(), None)
1441        .expect("the jsonic grammar documents are fixed and valid");
1442    parser
1443        .set_options(|options| options.lex.window = true)
1444        .expect("lex.window sets");
1445    parser
1446}
1447
1448/// A parser with the jsonic configuration but no grammar rules, for
1449/// building a grammar from scratch. The counterpart of `Jsonic.empty()`
1450/// and the Go `Empty`.
1451///
1452/// It declares no `lex.window`: a grammar built on it brings rules and
1453/// matchers of its own, and declares the window itself once they read the
1454/// source only through it.
1455pub fn empty() -> Tabnas {
1456    let mut parser = make_with(|options| options.lex.window = false);
1457    for name in parser.rule_names() {
1458        parser.define_rule(name, |spec| {
1459            spec.clear();
1460        });
1461    }
1462    parser
1463}
1464
1465/// Parse a jsonic source string with the shared default parser.
1466///
1467/// The engine is built once, on first use, and reused after that, as the
1468/// other two runtimes do (`sync.Once` in `go/jsonic.go`, the root
1469/// instance in `ts/src/jsonic.ts`). Reuse is safe: [`Tabnas::parse`]
1470/// takes `&self` and builds a fresh parse context per call, and `Tabnas`
1471/// is `Send + Sync`, so concurrent callers share one installed grammar
1472/// instead of each rebuilding it, which is what dominates a small parse.
1473///
1474/// Use [`make`] or [`make_with`] instead when the parser needs
1475/// configuring: that returns a fresh instance and leaves this one alone.
1476///
1477/// ```
1478/// let value = tabnas_jsonic::parse("a:1, b:2")?;
1479/// assert_eq!(value.to_string(), r#"{"a":1,"b":2}"#);
1480/// assert_eq!(tabnas_jsonic::parse("]").unwrap_err().code, "unexpected");
1481/// # Ok::<(), tabnas_jsonic::JsonicError>(())
1482/// ```
1483pub fn parse(src: &str) -> Result<Value, JsonicError> {
1484    static DEFAULT: OnceLock<Tabnas> = OnceLock::new();
1485    DEFAULT.get_or_init(make).parse(src)
1486}
1487
1488/// One optional alchemy source and the entry point a host calls.
1489#[derive(Clone, Copy, Debug, Eq, PartialEq)]
1490pub struct TranslationPart {
1491    /// The entry point a host calls.
1492    pub entry: &'static str,
1493    /// The source text, or `None` for an entry supplied by alchemy.
1494    pub source: Option<&'static str>,
1495}
1496
1497/// The package-local structural translation interface.
1498#[derive(Clone, Copy, Debug, Eq, PartialEq)]
1499pub struct TranslationParts {
1500    /// The complete `tabnas.plugin.json` text.
1501    pub manifest: &'static str,
1502    /// An optional lift from the grammar's events to its first read shape.
1503    pub lift: Option<TranslationPart>,
1504    /// An optional embedding of a plain tree in the format's schema, with its reverse.
1505    pub embed: Option<TranslationPart>,
1506    /// An optional render from the write shape to text.
1507    pub render: Option<TranslationPart>,
1508    /// An optional transducer: the format's JSON events from its parser's
1509    /// rule passes, for a host that reads parser events.
1510    pub transduce: Option<TranslationPart>,
1511}
1512
1513const TRANSLATION: TranslationParts = TranslationParts {
1514    manifest: include_str!("../translate/manifest.json"),
1515    lift: None,
1516    embed: None,
1517    render: Some(TranslationPart {
1518        entry: "json",
1519        source: None,
1520    }),
1521    transduce: Some(TranslationPart {
1522        entry: "jsonic-transduce",
1523        source: Some(include_str!("../translate/transduce.alc")),
1524    }),
1525};
1526
1527/// Return jsonic's immutable translation parts.
1528#[must_use]
1529pub const fn translate() -> Option<TranslationParts> {
1530    Some(TRANSLATION)
1531}
1532
1533/// The plugin's manifest, `tabnas.plugin.json`, as the repository carries
1534/// it. Its `translate` object is what a host that translates reads: the
1535/// shape jsonic is read as and written from (`tree`), the root the render
1536/// takes (`any`), the render that writes it, which is the `json` render
1537/// alchemy carries rather than a file of this repository's, and the
1538/// sentences that say what that render does not keep. Its `transduce`
1539/// names the transducer part, `alchemy/transduce.alc`, the document's JSON
1540/// events from the grammar's rule passes under its default options,
1541/// through which a host that reads parser events reads a document. The crate embeds its own copies,
1542/// `translate/manifest.json` and `translate/transduce.alc`, since a
1543/// packaged crate holds nothing outside `rs/`; `tests/translate_test.rs`
1544/// holds each copy to its file.
1545///
1546/// ```
1547/// assert!(tabnas_jsonic::manifest_text().contains("\"translate\""));
1548/// ```
1549pub fn manifest_text() -> &'static str {
1550    TRANSLATION.manifest
1551}
1552
1553#[cfg(test)]
1554mod tests {
1555    use super::*;
1556    use std::sync::Mutex;
1557
1558    /// The count as it was taken before it was kept: the whole stack, at
1559    /// every step.
1560    fn walked(context: &Context) -> usize {
1561        let on_stack = context
1562            .rule_stack
1563            .iter()
1564            .filter(|rule| is_container(&rule.name))
1565            .count();
1566        let current = context
1567            .rule
1568            .as_ref()
1569            .is_some_and(|rule| is_container(&rule.name));
1570        on_stack + usize::from(current)
1571    }
1572
1573    #[test]
1574    fn the_kept_count_is_the_walked_count_at_every_step() {
1575        // The engine turns a panic in a guard into a parse error, so a
1576        // difference is written down and asserted after the parses. The
1577        // check replaces jsonic's own guard, so the count is kept once per
1578        // step, as it is in use.
1579        let differences = Arc::new(Mutex::new(Vec::new()));
1580        let steps = Arc::new(std::sync::atomic::AtomicUsize::new(0));
1581        let (seen, stepped) = (differences.clone(), steps.clone());
1582        let mut parser = make();
1583        parser.parse_guard(DEPTH_GUARD, move |context| {
1584            let (kept, walked) = (depth(context), walked(context));
1585            if kept != walked {
1586                seen.lock().unwrap().push((context.iteration, kept, walked));
1587            }
1588            stepped.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
1589            kept <= DEPTH_LIMIT
1590        });
1591        let nested = |open: &str, inner: &str, close: &str, n: usize| {
1592            format!("{}{inner}{}", open.repeat(n), close.repeat(n))
1593        };
1594        let sources = [
1595            "1".to_string(),
1596            "a:1,b:2".to_string(),
1597            "a,b,c".to_string(),
1598            "a:b:c:1,d:e:2".to_string(),
1599            "[a:1,b:[c:2,d]]".to_string(),
1600            "{a:[1,{b:[2,[3]]}],c:d:e:f}".to_string(),
1601            "[1,2".to_string(),
1602            "{a:".to_string(),
1603            "]".to_string(),
1604            nested("[", "", "]", 127),
1605            nested("[", "", "]", 128),
1606            nested("{a:", "1", "}", 127),
1607            nested("{a:", "1", "}", 200),
1608            "a:".repeat(130) + "1",
1609            nested("[{a:", "1", "}]", 40) + "," + &nested("[", "x", "]", 60),
1610        ];
1611        // Twice over, so each parse also follows one that ended, some of
1612        // them in an error, on the same thread.
1613        for source in sources.iter().chain(sources.iter()) {
1614            let _ = parser.parse(source);
1615        }
1616        assert!(steps.load(std::sync::atomic::Ordering::Relaxed) > 5_000);
1617        assert_eq!(*differences.lock().unwrap(), Vec::new());
1618    }
1619
1620    #[test]
1621    fn a_step_counts_what_changed_not_the_whole_stack() {
1622        // A grammar can nest through rules of its own that are not
1623        // containers, as XML nests through its elements: the limit never
1624        // trips, and the stack grows as deep as the input. Counting the
1625        // whole stack at every step made such a parse take time growing
1626        // with the square of its depth (tabnas/jsonic#91: XML took 2 s at
1627        // 8,000 levels). A `wrap` rule, nested through `val` by
1628        // parentheses, stands in for the elements here. The work is
1629        // counted rather than timed: in a debug build the engine checks
1630        // every buried frame at every step, which would swamp a timing.
1631        let wrap = tabnas::Plugin::new("wrap", |parser, _options| {
1632            parser.token_with_source("#LP", "(");
1633            parser.token_with_source("#RP", ")");
1634            let spec = GrammarSpec::from_value(json!({
1635                "rule": {
1636                    "val": {
1637                        "open": [ { "s": "#LP", "p": "wrap", "b": 1, "g": "wrap" } ],
1638                        "close": [ { "s": "#RP", "b": 1, "g": "wrap" } ]
1639                    },
1640                    "wrap": {
1641                        "open": [ { "s": "#LP", "p": "val", "g": "wrap" } ],
1642                        "close": [ { "s": "#RP", "g": "wrap" } ]
1643                    }
1644                }
1645            }))
1646            .map_err(|error| tabnas::PluginError(error.0))?;
1647            parser
1648                .grammar(&spec)
1649                .map(|_| ())
1650                .map_err(|error| tabnas::PluginError(error.0))
1651        });
1652        let steps = Arc::new(std::sync::atomic::AtomicUsize::new(0));
1653        let walk = Arc::new(std::sync::atomic::AtomicUsize::new(0));
1654        let (stepped, walked) = (steps.clone(), walk.clone());
1655        let mut parser = make();
1656        parser.use_plugin(wrap, None).expect("wrap");
1657        // Replaces jsonic's own guard, counting its work as it goes.
1658        parser.parse_guard(DEPTH_GUARD, move |context| {
1659            stepped.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
1660            walked.fetch_add(
1661                context.rule_stack.len(),
1662                std::sync::atomic::Ordering::Relaxed,
1663            );
1664            within_depth_limit(context)
1665        });
1666        let levels = 500;
1667        let src = format!("{}1{}", "(".repeat(levels), ")".repeat(levels));
1668        let examined = || STACK_COUNT.with(|count| count.borrow().examined);
1669        let before = examined();
1670        parser.parse(&src).expect("parses");
1671        let work = examined() - before;
1672        let steps = steps.load(std::sync::atomic::Ordering::Relaxed);
1673        let walk = walk.load(std::sync::atomic::Ordering::Relaxed);
1674        // The stack reaches 1,000 rules: a count of all of it at every
1675        // step would look at hundreds of frames a step (500 on average
1676        // here), and the kept count looks at one or two.
1677        assert!(steps > 2 * levels, "{steps} steps");
1678        assert!(
1679            walk > levels / 2 * steps,
1680            "a shallow stack: {walk} frames in {steps} steps"
1681        );
1682        assert!(
1683            work <= 3 * steps,
1684            "{work} frames looked at in {steps} steps"
1685        );
1686    }
1687}