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