tabnas-json5 0.5.20

The JSON5 grammar plugin for the tabnas parsing engine, over the jsonic base grammar
Documentation
# Agents Guide: rs/

The Rust port of the canonical TypeScript in [`../ts`](../ts). Read
[`../AGENTS.md`](../AGENTS.md) first: it holds the cross-runtime rules,
and this file only covers what is specific to this crate.

## Layout

| Path | |
|---|---|
| `src/lib.rs` | the whole port: `Json5Options`, the embedded grammar text, the lexer checks, the value transforms, the pair-key validator, `json5`, `plugin`, `make`, `make_with` (which declare `lex.window`), `parse_with`, `parse`, `check_reader`, `parse_reader_with`, and the translation parts `manifest_text` and `render_text`, `include_str!` of the copies in `translate/` |
| `tests/parity_test.rs` | every `../test/spec/*.tsv` fixture through `tabnas_support::Runner`, a fresh parser per row for the `opts` column, plus two tripwires: every fixture has the standard shape, and the row CENSUS is the one recorded |
| `tests/suite_test.rs` | the vendored `../test/json5-tests` corpus against `../test/json5-tests-expected.json`, both halves, plus the derived truncation and trailing probes |
| `tests/divergent_test.rs` | the register `../test/divergent.tsv`, `rust` column |
| `tests/text_ender_test.rs` | the P1/P2 pin: a quote does not end a text run |
| `tests/json5_test.rs` | in-language behaviour: the `go/json5_test.go` cases, the API, threads |
| `tests/untrusted_test.rs` | playbook section 7: deep nesting, very long input, unterminated constructs, control characters, wide containers |
| `tests/reader_test.rs` | a parse from a reader, a window at a time: every fixture row, corpus document and derived probe, strings the window's edge cuts at every place, the values the text check judges, long documents; `make` declares the window; `check_reader` reads only the leading trivia (see `../AGENTS.md`, "A document read from a reader, a window at a time") |
| `tests/perf_test.rs` | reuse of one instance must beat rebuilding per parse, and cost must grow about linearly with input size |
| `tests/version_test.rs` | Cargo.toml == `VERSION` == ts/package.json |
| `tests/translate_test.rs` | the translation parts: the embedded manifest is `../tabnas.plugin.json`, the render it names is the one `render_text()` embeds, the embed it names is the one `translate()` carries (none, for JSON5), the manifest's shapes, root and loss lines, and every render definition named `json5-...` |
| `translate/` | the crate's copies of `../tabnas.plugin.json` (as `manifest.json`) and `../alchemy/render.alc`, which a packaged crate needs, written by `npm run embed` in `../ts`; `tests/translate_test.rs` holds them to the files |
| `tests/common/mod.rs` | shared helpers: spec dir, the hand-written value conversion, the `opts` reader, the register outcome |
| `README.md` | the crate front page, prose-gated; its `rust` fences are doctests of this crate (see below) |

Crate `tabnas-json5`, library `tabnas_json5`. The engine (`tabnas`), the
base grammar (`tabnas-jsonic`, which takes `tabnas-json` by path in
turn) and the fixture runner (`tabnas-support`, dev only) are **path
dependencies on sibling checkouts** (`../../parser/rs`,
`../../jsonic/rs`, `../../json/rs`, `../../support/rs`). All of them
are on crates.io, but the committed manifest names them by path alone,
so there is no registry version to fall back on.

```bash
cargo build --all-targets
cargo test --all-targets && cargo test --doc
cargo clippy --all-targets --all-features -- -D warnings
cargo fmt
```

`make test-rs` from the repository root is the fast loop; `ci/rust/run.sh`
is the full gate and adds `fmt --check`, the lockfile check and the MSRV
pin. Use `CARGO_BUILD_JOBS=2` on a shared box.

## The grammar is the embedded jsonic TEXT, parsed at install

`../json5-grammar.jsonic` is embedded verbatim between the
`BEGIN/END EMBEDDED` markers in `src/lib.rs`, as a `r#"..."#` raw
string, by `../ts/embed-grammar.js` (which writes the TypeScript and Go
sources too, and writes this one when `rs/` exists). **Never hand-edit
the text between the markers.** The grammar cannot contain `"#`; the
script refuses one that does.

At install, `grammar_document` parses that text with
`tabnas_jsonic::make()`, exactly as the other two ports parse it, then
patches it before `GrammarSpec::from_value`:

- the `JSON5_*` placeholders become the real character sets;
- the JSON5 `LineTerminator` set is SPLIT, where TypeScript and Go write
  all four characters into `line.chars`. CR and LF go into `line.chars`
  and LS and PS into `line.fixed`. Both halves end a line everywhere a
  line can end, because the engine asks `line.chars` plus `line.fixed`
  for that; the one place that asks `line.chars` ALONE is the string
  lexer's unprintable test, and JSON5 5.2 admits an unescaped U+2028 or
  U+2029 inside a string literal where any other line terminator must be
  escaped. Carrying all four in `line.chars` made a string holding a raw
  U+2028 `unprintable` here, while TypeScript and Go both returned the
  string. `char_sets()` in the engine's `options.rs` documents the
  asymmetry as deliberate, so this is a seam rather than a workaround.
  All three runtimes execute it, through the rows in
  `../test/spec/strings.tsv` whose input cells carry the raw characters
  (the fixture escape codec is `\n \r \t \\` and has no `\uXXXX`, so a
  cell reading `\u2028` would test the JSON5 escape instead); pinned
  here as well by
  `a_line_separator_is_legal_inside_a_string_but_still_ends_a_line` in
  `tests/json5_test.rs`;
- the option-dependent overrides (`hex`, `oct`, `bin`, `sep`, hash
  comment, `lex.empty`, `tokenSet.VAL`) are applied from `Json5Options`;
- `number.exclude` loses its `@/.../` wrapper. The engine reads that
  field as a BARE pattern and stores whatever string it is given, so the
  serialized form compiled to a regex that never matched and `010`
  parsed as ten. `value.def.*.match` DOES take the serialized form; the
  two are not symmetric.

Two things go on AFTER the document, through `set_options`:

- the `Infinity` / `NaN` family, because the values cannot travel as
  JSON (same reason as in TypeScript and Go);
- the `null` keyword's value. The document says `null: { val: null }`,
  and the engine's loader reads a JSON null `val` as "no value", so the
  keyword came back as the text `"null"`. `null_keywords` collects every
  definition whose `val` is null and puts `Value::Null` back.

## The refs the grammar names

Every `@name` in the grammar is registered on the instance BEFORE the
document is installed, because the document is what looks them up:

- `@fixed-check` is an `imperative_lex_check_ref` that reads every
  string holding a line continuation (`read_continued_string`), as the
  TypeScript and Go fixed checks do: it moves the cursor with the
  engine's own `advance_chars`, so rows, columns and offsets after the
  string are the engine's count of the source as it is, and returns the
  `#ST` token, or a bad token sited where `match_string` would site its
  error. The engine's escape map would read four of the five forms, but
  not `\` before CRLF, and it ends a pending surrogate pair at each, so
  the check takes them all. A check cannot read the live options, so the
  string options it needs (quotes, multi-line quotes, the escape map,
  `allowUnknown`, `escapeStrict`, `allowControl`) are copied from the
  document at install, `StringSyntax`. Until tabnas/json5#80 the check
  was a no-op and `parse_with` stripped continuations from the source,
  which put every later token a row early.
- `@text-check` returns `Skip` for unquoted text that cannot start an
  `IdentifierName` and is not a value keyword or value regex; an
  unclaimed character is the engine's `unexpected`. The keyword list is
  captured at install from the document plus the `Infinity` family:
  the check has no access to the live config.
- `@string-check` scans from the quote for the escapes ES5.1 forbids
  (`\1`..`\9`, `\0<digit>`, `\u{`) and returns `Skip`. It shares the
  walk, `scan_string_escapes`, with the fixed check, which refuses a
  continuation string holding one the same way, since such a string
  never reaches this check.

All three are `imperative_lex_check_ref`s, which take the lexer: a
`lex_check_ref` takes the text to the window's end and cannot read the
window on. They read through `Lexer::window` and `Lexer::fill`
(`scan_string_at`, `hold_text`, `read_on`), each only as far as its own
answer needs: where a matcher before a check read to the window's end,
the engine cuts the token again over the window the check's fill left
(tabnas/parser#326, from tabnas-parser 0.12.17); `../AGENTS.md`, "A
document read from a reader, a window at a time", has more.
- `@parse-trailing-dec-exp` and `@parse-uppercase-hex` are
  `value_transform_ref`s. Note the Rust number lexer already accepts
  `0X` and `5.e4`, so the regex definitions mostly pin agreement --
  and `@parse-uppercase-hex` does not run at all under the default
  options, because the number lexer claims `0X` first. See below.
- `@json5-pair-key` is a `state_action_with_next_ref` pushed onto
  `pair.ao` by name through `define_rule`. It rejects a `#TX` key that
  is not an `IdentifierName` (returns the token marked `unexpected`) and
  writes the decoded name onto both the token and `u.key`, because
  jsonic's `@pairkey` has already copied the raw source there.

## Base-prefixed numbers are re-read exactly

`0x`, `0o` and `0b` literals are read as an EXACT integer and rounded to
a double ONCE, half to even, which is what the canonical coercion does
on the same digits. Folding the digits into an `f64` one at a time
instead rounds at every digit, and past the 53-bit exact integer range
the roundings accumulate and the answer drifts.

The engine used to fold that way, so this crate carried a `subscribe_lex`
hook that re-derived the value of every base-prefixed token. That defect
is fixed upstream, in `parser`'s `match_number`, and the hook is gone:
the engine now answers correctly under the default options, where
`number.hex` is on and its lexer claims `0x` and `0X` before any value
definition sees them. Removing the hook was measured rather than assumed,
by running this suite against the fixed engine with the hook gone, and
again against the old engine with the hook gone, where the bit-pinning
test fails.

`radix_literal_value` and `digits_to_f64` stay, because
`@parse-uppercase-hex` still needs them: that value definition owns `0X`
when `hex` is false, which is the one configuration where the engine's
lexer never sees the literal.

Pinned by `../test/spec/numbers.tsv`, the `hex:false` rows in
`../test/spec/options.tsv`, and
`wide_base_prefixed_literals_round_once_from_the_exact_integer` in
`tests/json5_test.rs`, which asserts the IEEE-754 bits a decimal
expectation cannot show. Verified against node over 4,000 random
literals in all three bases.

## Token sets do not reach pre-built alternates

`AltSpec.s` holds resolved tins, so the `tokenSet` the document
declares does not change jsonic's already-installed `val` and `pair`
alternates. `json5()` filters `#TX` out of every val-tagged alternate
(under `strict_value`) and `#NR` out of every pair-tagged one, on every
rule, exactly as the Go port's `filterTinFromAlts` does. Then it drops
the `comma,jsonic` alternate from `pair.open` and, under
`require_value`, the `#ZZ jsonic` alternate from `val.open`.

## Why `parse_with` and `parse_reader_with` exist

The Go port's `Parse(j, src)`, for the same reason: the engine runs a
`parser.start` hook INSTEAD of the parse, not before it, so a plugin
cannot wrap the parse the way the TypeScript one does. `parse_with`
reads the options the plugin recorded as a decoration (`json5$options`),
applies the requireValue codes, delegates a no-value source to
`parse("")` when the option is off (so the grammar's `emptyResult` is
written once), and parses. A parser without the decoration is parsed as
it is.

`Tabnas::parse` on the instance parses JSON5 exactly as `parse_with`
does, line continuations included, since the fixed check reads them in
the lexer; only the two requireValue codes need the wrapper.

`parse_reader_with` is the same for a reader: `check_reader` applies the
rule to the reader's leading whitespace and comments only, with the walk
`has_value` makes of a text resumed as bytes arrive (`ValueScan`), and
hands back a reader (`Checked`) that gives the bytes it read and then the
rest, and a read that failed where it failed; the parser then reads that
through `Tabnas::parse_reader`, a window at a time. A host with a reader
source of its own calls `check_reader` first. Every
fixture goes through `parse_with`, and the continuation tests in
`tests/json5_test.rs` hold the two entry points to the same answer.

## The divergence register

`tests/divergent_test.rs` reads the `rust` column of
`../test/divergent.tsv` with a LOCAL runner mirroring
`go/divergent_test.go`, not `tabnas_support::Register`. The register's
only rows record a position disagreement under one code (the astral
column: TypeScript counts UTF-16 units, Go and Rust count characters),
and the support crate's register compares error cells by code alone, so
it would refuse every row as recording no divergence. When it compares
positions, this file collapses to a `Register::new(runner, "rust",
&["go", "ts", "rust"])` call.

Every divergence, register row or not, also has a MEASURED table in
`../DIVERGENCE.md` with the reason and who owns the repair. Only the
nesting bound is the Rust port's alone: `tabnas_jsonic`'s `DEPTH_LIMIT`,
inherited rather than added here, and unable to be a row for the reason
below. The rest are shared with Go.

A divergence asserts that a difference CANNOT be repaired. Where the
canonical is simply wrong, the repair belongs in `ts/src/json5.ts` and
the rows belong in a shared fixture, not here. Two entries were removed
on 2026-09-21 on exactly that ground. The astral `IdentifierStart` one:
its own comment named the canonical defect, so recording it was a claim
of impossibility about something a one-line change fixed. The
hash-comment-only one: it parked the repair on the claim that the
canonical could not learn the `#` form without changing its
`requireValue` control row, and the canonical turned out to call that
scan from two separate `requireValue` branches. Before recording
anything, MEASURE the reason it cannot be repaired.

### What the register cannot hold

Four shapes of divergence do not fit this file. None is a reason to
widen the cell format; each is recorded where it can be executed.

A divergence that survives is pinned PER COLUMN, not only here. A test
in this crate alone holds the Rust figure still and lets the TypeScript
and Go ones drift while every suite stays green, which is what the
2026-09-21 audit of `../DIVERGENCE.md` was for: each entry that remains
names a test in `ts/test/json5.test.ts` and one in `go/json5_test.go` as
well, and each of those walks or reads what its figure claims rather
than only checking that the call returned.

- **A lone surrogate.** `"\uD800"` is that character in TypeScript and
  U+FFFD here, because a Rust `String` is UTF-8. The register's cells
  are JSON values, and every reader but JavaScript's folds `\ud800` to
  U+FFFD, so a `ts` cell of `"\ud800"` and a `rust` cell of `"\ufffd"`
  MEAN the same thing to the Go and Rust halves, which then refuse the
  row as recording no divergence. Measured: both halves were run against
  exactly that row. `tabnas_support::lone_surrogate_at` exists to refuse
  the same cell in a shared `test/spec` fixture. Pinned instead by
  `a_lone_surrogate_folds_to_the_replacement_character` in
  `tests/json5_test.rs`, with
  `lone-surrogate-survives-as-a-code-unit` in `ts/test/json5.test.ts`
  and `TestLoneSurrogateFoldsToTheReplacementCharacter` in
  `go/json5_test.go` holding the other two columns.
- **Anything needing non-default options.** The three REGISTER runners
  build one parser from the defaults and `test/divergent.tsv` has no
  `opts` column. The shared `test/spec` fixtures DO have one, so an
  option-dependent difference belongs there the moment the three
  runtimes agree on it. A hash-comment-only source under `hashComment`
  and `requireValue: false` was recorded here as such a case until
  2026-09-21, on the ground that the three could not be made to agree.
  They could: the canonical's no-value scan is told which comment forms
  the configuration has, from its `requireValue`-OFF branch alone, so
  all three answer the declared empty result and the inputs are rows of
  `../test/spec/options.tsv` with their two controls. `has_value` here
  takes the same flag for the same reason. Nothing in this crate pins
  that entry any more, because there is no entry.
- **Anything only THIS port diverges on.** `ts/test/divergent.test.ts`
  and `go/divergent_test.go` each compare their own column against ONE
  other (`ts` against `go`, and back), and the first thing each does is
  fail a row whose two columns agree. A row where TypeScript and Go
  agree and only Rust differs therefore fails both of those halves
  before either parses anything, however true it is. The nesting bound
  is that shape, and its input would otherwise fit a cell. Measured, not
  assumed: that check is `same(mine, theirs)` at the top of each loop.
  Recorded in `../DIVERGENCE.md` and pinned by
  `nesting_is_capped_at_the_budget_jsonic_installs` in
  `tests/json5_test.rs`, with `nesting-is-unbounded` in
  `ts/test/json5.test.ts` and `TestNestingIsUnbounded` in
  `go/json5_test.go` holding the absence of a bound in the other two.
  It becomes a row when those two halves read every runtime column,
  which is the same change that collapses this file's runner into
  `tabnas_support::Register`.

- **Anything whose answer is the TOOLCHAIN's rather than the port's.**
  An unquoted key is an ES5.1 `IdentifierName`, whose `IdentifierStart`
  is a Unicode letter, and the specification names no Unicode VERSION.
  So each runtime answers from the tables its platform ships: the
  canonical from the host Node's ICU, Go from its `unicode` package, and
  this crate from the `regex` crate. Measured over every code point in
  both positions on 2026-09-22, the three agree on 2,204,801 of
  2,224,126 probes; of the rest, 9,979 are letters this crate and the
  canonical accept and Go does not, and 9,346 are letters only the
  canonical accepts. The other three exclusions above are about what a
  cell can SPELL. This one is about what a cell MEANS: a register cell
  states what a PORT does, so a changed cell reports a repair or a
  regression, and these cells change when a toolchain moves without a
  line of any port changing. Recorded in `../DIVERGENCE.md` and pinned
  per column by `unquoted_keys_follow_this_crates_unicode_tables` in
  `tests/json5_test.rs`, with
  `unquoted-keys-follow-the-hosts-unicode-tables` in
  `ts/test/json5.test.ts` and
  `TestUnquotedKeysFollowThisToolchainsUnicodeTables` in
  `go/json5_test.go`. All three assert DELEGATION, which survives a
  toolchain move; only the Rust one also hard-codes the current verdicts,
  because only this crate's tables come from a dependency this repository
  locks.

The untrusted-input suite splits the same way. Only
`nesting_far_past_the_budget_is_refused_rather_than_run` in
`tests/untrusted_test.rs` is this port's own; the rest is ordinary JSON5
behaviour, so the short cases are rows of `../test/spec/options.tsv` and
the long ones are mirrored case for case and size for size in
`ts/test/untrusted.test.ts` and `go/untrusted_test.go`.

## The corpus grader never skips

`tests/suite_test.rs` panics when the corpus or the oracle is missing.
Do not turn that into an early return or an `#[ignore]`: a conformance
run that silently does not happen is the defect the grader exists to
prevent. The canonical value form is duplicated in four places
(`scripts/gen-json5-expected.js`, `ts/test/suite.test.ts`,
`go/suite_test.go`, this file) and must stay byte-compatible: strings
walk UTF-16 code units, numbers are the IEEE-754 bits.

## The docs are gated

`README.md` is in the published set: no em dashes in prose, no first
person singular, no links to any `AGENTS.md`, no project history. This
file is internal and may be blunt.

## The README is doctested

`src/lib.rs` includes `README.md` as rustdoc under `#[cfg(doctest)]`, so
every `rust` fence in it runs on `cargo test --doc` (they show up as
`readme_examples (line N)`). rustdoc runs each fence as written, so a
fence must be a complete program: wrap it in
`fn main() -> Result<(), Box<dyn std::error::Error>> { ... Ok(()) }`
rather than using `?` at the top level, and never use hidden `# ` lines,
which render as garbage on GitHub. The `toml` and `bash` fences are not
run.