tabnas_jsonc/lib.rs
1// Copyright (c) 2021-2026 Richard Rodger, MIT License
2
3// The engine's error carries a code, position, hint and a formatted
4// report, so it is large by design and `Result<_, TabnasError>` trips
5// clippy's `result_large_err`. The engine allows the lint at its own
6// crate root for the same reason, and so does tabnas-jsonic; boxing here
7// would make `parse` return a different shape from `Tabnas::parse` and
8// from `tabnas_jsonic::parse`.
9#![allow(clippy::result_large_err)]
10
11//! A JSONC (JSON with comments) grammar plugin for the `tabnas` parsing
12//! engine.
13//!
14//! JSONC is the dialect of editor and tool configuration files
15//! (`tsconfig.json`, `settings.json`): standard JSON plus single-line
16//! (`//`) and block (`/* */`) comments, with optional trailing commas in
17//! objects and arrays.
18//!
19//! The plugin is not standalone. It layers on the relaxed-JSON grammar of
20//! [`tabnas_jsonic`] (the `val` / `map` / `list` / `pair` / `elem` rules)
21//! and adds no rules of its own: it installs an end-of-input alternate on
22//! `val`, the trailing-comma alternates on `pair` and `elem`, and pulls
23//! the lexer, number, string and map options back toward standard JSON.
24//! Two plugin options switch behaviour: [`JsoncOptions::disallow_comments`]
25//! (strict JSON, no comments) and [`JsoncOptions::allow_trailing_comma`].
26//! Nesting is bounded at [`DEPTH_LIMIT`] levels, which the canonical
27//! plugin does not do; see that constant for why.
28//!
29//! ```
30//! let value = tabnas_jsonc::parse(r#"{ "foo": /* hello */ true }"#)?;
31//! assert_eq!(value.to_string(), r#"{"foo":true}"#);
32//! # Ok::<(), tabnas_jsonc::JsoncError>(())
33//! ```
34//!
35//! This is the Rust port; the TypeScript package (`ts/src/jsonc.ts`) is
36//! canonical and the Go port (`go/jsonc.go`) is the nearer structural
37//! model. The grammar itself is authored once, in `jsonc-grammar.jsonic`
38//! at the repository root, and embedded verbatim into all three runtimes.
39//! The shared `test/spec/*.tsv` fixtures are the parity contract.
40
41use std::sync::OnceLock;
42
43use serde_json::Value as JsonValue;
44use tabnas::{
45 Context, GrammarError, GrammarSetting, GrammarSpec, Plugin, PluginError, Tabnas, Value,
46};
47
48/// The README's Rust examples run as doctests, so a stale one fails the
49/// gate rather than misleading the reader. Its `toml` and `bash` fences
50/// are skipped; rustdoc runs only the `rust` ones.
51#[cfg(doctest)]
52#[doc = include_str!("../README.md")]
53mod readme_examples {}
54
55/// This crate's version. It MUST equal `ts/package.json` "version": the
56/// release orchestrator rewrites both, and `tests/version_test.rs` fails
57/// the build if they drift. Mirrors `VERSION` in `ts/src/jsonc.ts` and
58/// `const VERSION` in `go/jsonc.go`.
59pub const VERSION: &str = "0.5.13";
60
61/// The error a failed parse produces, re-exported so callers need not
62/// depend on the engine crate directly. Every code jsonc raises is
63/// inherited from the engine or from jsonic; the plugin declares none of
64/// its own.
65pub use tabnas::TabnasError as JsoncError;
66
67/// The name the plugin registers under, and so the namespace of its
68/// option bag on the engine. Mirrors the TypeScript plugin function name
69/// `Jsonc`, which is what the engine records in its plugin stack.
70pub const PLUGIN_NAME: &str = "Jsonc";
71
72// --- BEGIN EMBEDDED jsonc-grammar.jsonic ---
73const GRAMMAR_TEXT: &str = r##"
74# JSONC Grammar Definition
75# Parsed by a standard Jsonic instance and passed to jsonic.grammar()
76# Extends standard JSON grammar with end-of-input value handling.
77
78{
79 options: text: { lex: false }
80 options: number: { hex: false oct: false bin: false sep: null exclude: "@/^\\./" }
81 options: string: { chars: '"' multiChars: '' allowUnknown: false escapeStrict: true }
82 options: string: escape: { v: null }
83 options: comment: def: hash: { lex: false }
84 options: map: { extend: false }
85 options: lex: { empty: false }
86 options: rule: { finish: false }
87
88 rule: val: open: {
89 alts: [
90 { s: '#ZZ' g: jsonc }
91 ]
92 inject: { append: true }
93 }
94
95 rule: pair: close: {
96 alts: [
97 { s: '#CA #CB' b: 1 g: comma }
98 ]
99 inject: {}
100 }
101
102 rule: elem: close: {
103 alts: [
104 { s: '#CA #CS' b: 1 g: comma }
105 ]
106 inject: {}
107 }
108}
109"##;
110// --- END EMBEDDED jsonc-grammar.jsonic ---
111
112/// The embedded grammar text, exactly as `jsonc-grammar.jsonic` holds it
113/// (with the leading newline the embedding adds). It is jsonic, not JSON:
114/// the plugin parses it with a jsonic instance at install time, as the
115/// TypeScript and Go plugins do, so the file at the repository root stays
116/// the single source of truth for every runtime.
117pub fn grammar_text() -> &'static str {
118 GRAMMAR_TEXT
119}
120
121/// The plugin options. Mirrors the TypeScript `JsoncOptions` type and the
122/// `pluginOpts` map the Go `Jsonc` reads; both keys are off by default.
123///
124/// ```
125/// use tabnas_jsonc::JsoncOptions;
126///
127/// let options = JsoncOptions::new().with_allow_trailing_comma(true);
128/// let parser = tabnas_jsonc::make_with(options);
129/// assert_eq!(parser.parse("[1, 2, ]")?.to_string(), "[1,2]");
130/// # Ok::<(), tabnas_jsonc::JsoncError>(())
131/// ```
132#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
133pub struct JsoncOptions {
134 /// Accept a trailing comma before a closing `}` or `]`. Off, the
135 /// `comma` alternates are excluded from the grammar and `[1,]` is
136 /// rejected, which is what the JSONC dialect specifies by default.
137 pub allow_trailing_comma: bool,
138
139 /// Reject `//` and `/* */` comments, leaving strict JSON (plus the
140 /// number and key relaxations jsonic keeps; see the README).
141 pub disallow_comments: bool,
142}
143
144impl JsoncOptions {
145 /// The default options: comments on, trailing commas off.
146 pub fn new() -> Self {
147 Self::default()
148 }
149
150 /// Set [`JsoncOptions::allow_trailing_comma`].
151 pub fn with_allow_trailing_comma(mut self, allow: bool) -> Self {
152 self.allow_trailing_comma = allow;
153 self
154 }
155
156 /// Set [`JsoncOptions::disallow_comments`].
157 pub fn with_disallow_comments(mut self, disallow: bool) -> Self {
158 self.disallow_comments = disallow;
159 self
160 }
161
162 /// Read the options out of an engine plugin option bag, the shape
163 /// [`Tabnas::use_plugin`] hands the plugin: `allowTrailingComma` and
164 /// `disallowComments`, each on only when it is exactly `true`, as the
165 /// Go `toBool` reads them. Anything else in the bag is ignored.
166 pub fn from_value(value: &Value) -> Self {
167 let bag = value.to_json();
168 let flag = |name: &str| bag.get(name).and_then(JsonValue::as_bool).unwrap_or(false);
169 Self {
170 allow_trailing_comma: flag("allowTrailingComma"),
171 disallow_comments: flag("disallowComments"),
172 }
173 }
174
175 /// The options as an engine plugin option bag, with the TypeScript
176 /// key names, for [`Tabnas::use_plugin`].
177 pub fn to_value(&self) -> Value {
178 Value::from_json(&serde_json::json!({
179 "allowTrailingComma": self.allow_trailing_comma,
180 "disallowComments": self.disallow_comments,
181 }))
182 }
183}
184
185/// The deepest nesting of objects and arrays a document may have.
186///
187/// This port's one deliberate departure from the canonical TypeScript
188/// plugin, which sets no limit. The Rust engine's cost per rule grows
189/// with the height of its rule stack, so a parse costs time quadratic in
190/// the nesting depth: measured in a debug build, 100 levels cost 0.07 s
191/// and 500 levels 1.6 s, so the RFC 8259 corpus's
192/// `n_structure_100000_opening_arrays` would take hours to reject. A
193/// parse guard stops such a document at the limit with the `cancel` code
194/// instead.
195///
196/// The limit is also what keeps a deep document from ending the process.
197/// [`Value::to_json`] RECURSES once per level, about 2.2 KiB of stack per
198/// level in a debug build, and a thread created with the standard library
199/// default gets 2 MiB: measured, that stack aborts somewhere between 920
200/// and 950 levels, and an abort cannot be caught. So the limit has to sit
201/// below what the smallest realistic caller can walk, not merely below
202/// what the engine can parse.
203///
204/// That leaves a narrow band, and 512 sits in it. The conformance pin in
205/// `test/known-lenient.json` requires the corpus's 500-level
206/// `i_structure_500_nested_arrays` to be ACCEPTED, which is the floor;
207/// the stack is the ceiling. JSONC is the dialect of editor and tool
208/// configuration, which nests a handful of levels, so the band is
209/// generous for the format even though it is narrow in the abstract.
210/// Recorded in `DIVERGENCE.md` at the repository root;
211/// `tests/jsonc_test.rs` measures both the parse boundary and the walk of
212/// a limit-deep value on a 2 MiB stack.
213pub const DEPTH_LIMIT: usize = 512;
214
215/// How many containers are open at this point in the parse.
216///
217/// Counted from the RULE NAMES rather than from `rule_stack.len()`. The
218/// stack holds about three rules per level (`val`, then `map`/`list`,
219/// then `pair`/`elem`), so a length-based limit would encode that ratio
220/// and shift silently the first time the grammar gains an alternate.
221/// Counting the container rules is the depth a reader of the document
222/// would count. The rule the loop is working on is not in `rule_stack`
223/// (the engine hands it over separately as `context.rule`), and a
224/// container is open from the moment it is that rule, so it is counted
225/// too. This is the shape `tabnas_json` uses for its own limit.
226fn depth(context: &Context) -> usize {
227 let is_container = |name: &str| name == "map" || name == "list";
228 let ancestors = context
229 .rule_stack
230 .iter()
231 .filter(|rule| is_container(&rule.name))
232 .count();
233 let current = usize::from(
234 context
235 .rule
236 .as_ref()
237 .is_some_and(|rule| is_container(&rule.name)),
238 );
239 ancestors + current
240}
241
242/// The depth guard: `DEPTH_LIMIT` levels parse, the next one does not.
243fn within_depth_limit(context: &Context) -> bool {
244 depth(context) <= DEPTH_LIMIT
245}
246
247/// The name the depth check is installed under, as a parse guard.
248///
249/// It is the name jsonic installs its own 127-level check under, so this
250/// one replaces it: that is how JSONC allows 512 levels on a grammar built
251/// on jsonic. A guard rather than the parse budget, because the budget is
252/// one slot that a caller's `parse_budget` replaces, and the limit went
253/// with it whenever a caller set a budget of its own.
254const DEPTH_GUARD: &str = "depth";
255
256/// The serialized `@/pattern/flags` regular expression reference, as a
257/// bare pattern for the `regex` crate.
258///
259/// The grammar text spells `number.exclude` in the reference form the
260/// three runtimes share. The TypeScript and Go engines resolve that form
261/// wherever it appears in an option document; the Rust engine takes
262/// `number.exclude` as the pattern itself, so the reference is unwrapped
263/// here, before the document is installed. The JavaScript flags with a
264/// `regex` counterpart travel as an inline group; `g`, `u` and `y` mean
265/// nothing to a single anchored match and are dropped.
266fn bare_pattern(source: &str) -> Option<String> {
267 let body = source.strip_prefix("@/")?;
268 let slash = body.rfind('/')?;
269 let (pattern, flags) = (&body[..slash], &body[slash + 1..]);
270 let flags: String = flags
271 .chars()
272 .filter(|flag| matches!(flag, 'i' | 'm' | 's'))
273 .collect();
274 Some(if flags.is_empty() {
275 pattern.to_string()
276 } else {
277 format!("(?{flags}){pattern}")
278 })
279}
280
281/// Put whole-valued numbers back as integers.
282///
283/// jsonic's value model has one number type, `f64`, so the `b: 1` of a
284/// backtrack count comes out of the parse as `1.0`, and the engine's
285/// document reader rightly refuses a float where it wants a count. The
286/// TypeScript and Go runtimes never see the question: a JavaScript
287/// number is a JavaScript number, and the Go reader accepts a whole
288/// `float64`. Only finite numbers with no fractional part change.
289fn integers(document: &mut JsonValue) {
290 match document {
291 JsonValue::Number(number) => {
292 if let Some(float) = number.as_f64() {
293 if float.is_finite() && float.fract() == 0.0 && float.abs() < 9.0e15 {
294 *number = serde_json::Number::from(float as i64);
295 }
296 }
297 }
298 JsonValue::Array(items) => items.iter_mut().for_each(integers),
299 JsonValue::Object(entries) => entries.values_mut().for_each(integers),
300 _ => {}
301 }
302}
303
304/// Unwrap the one regular expression reference the grammar carries; see
305/// [`bare_pattern`]. A document without it is left alone.
306fn resolve_number_exclude(document: &mut JsonValue) {
307 if let Some(exclude) = document.pointer_mut("/options/number/exclude") {
308 if let Some(pattern) = exclude.as_str().and_then(bare_pattern) {
309 *exclude = JsonValue::String(pattern);
310 }
311 }
312}
313
314/// The embedded grammar as the engine's serialized document.
315///
316/// The text is jsonic, so it is parsed by a jsonic instance, exactly the
317/// `new Tabnas().use(jsonic).parse(grammarText)` of the TypeScript plugin
318/// and the `GrammarText` of the Go one; the shared default jsonic parser
319/// serves, since the text is fixed. The result is converted once and
320/// cached: every install of the plugin, on every instance, reads the same
321/// document.
322fn grammar_document() -> Result<&'static JsonValue, GrammarError> {
323 static DOCUMENT: OnceLock<Result<JsonValue, GrammarError>> = OnceLock::new();
324 DOCUMENT
325 .get_or_init(|| {
326 let parsed = tabnas_jsonic::parse(GRAMMAR_TEXT).map_err(|error| {
327 GrammarError(format!(
328 "tabnas-jsonc: the embedded jsonc-grammar.jsonic does not parse as jsonic: {error}"
329 ))
330 })?;
331 let mut document = parsed.to_json();
332 integers(&mut document);
333 resolve_number_exclude(&mut document);
334 Ok(document)
335 })
336 .as_ref()
337 .map_err(Clone::clone)
338}
339
340/// Install JSONC on an engine that ALREADY carries the jsonic grammar:
341/// the body of the TypeScript `Jsonc(tn, options)` plugin function and
342/// the Go `Jsonc(j, pluginOpts)`.
343///
344/// In order, as they do: the embedded grammar is installed with every
345/// alternate tagged `jsonc` (the static options, the `#ZZ` alternate on
346/// `val.open`, the `comma` alternates on `pair.close` and `elem.close`),
347/// and then the two argument-dependent options are applied on top:
348/// `comment.lex` from `disallow_comments`, and `rule.include` of
349/// `jsonc,json` with `rule.exclude` of `comma` unless
350/// `allow_trailing_comma` keeps the trailing-comma alternates active.
351///
352/// The order matters: installing a grammar re-applies its own options,
353/// so the runtime ones go on afterwards, where nothing can clobber them.
354///
355/// ```
356/// let mut parser = tabnas::Tabnas::new();
357/// tabnas_jsonic::jsonic(&mut parser)?;
358/// tabnas_jsonc::jsonc(&mut parser, &tabnas_jsonc::JsoncOptions::new())?;
359/// assert_eq!(parser.parse("[1, /* two */ 2]")?.to_string(), "[1,2]");
360/// assert!(parser.parse("[1, 2, ]").is_err());
361/// # Ok::<(), Box<dyn std::error::Error>>(())
362/// ```
363///
364/// An engine without the jsonic rules is reported as a [`GrammarError`]
365/// that names the repair, rather than growing alternates on rules that
366/// do not exist. Prefer [`plugin`] with [`Tabnas::use_plugin`] when the
367/// instance may be derived from: a plugin installed that way is re-run on
368/// the derived instance.
369pub fn jsonc(parser: &mut Tabnas, options: &JsoncOptions) -> Result<(), GrammarError> {
370 if !parser.rule_names().iter().any(|name| name == "val") {
371 return Err(GrammarError(
372 "tabnas-jsonc: the jsonic grammar must be installed first: \
373 call tabnas_jsonic::jsonic(&mut parser) before tabnas_jsonc::jsonc(...), \
374 or use make()"
375 .into(),
376 ));
377 }
378
379 let comment_lex = !options.disallow_comments;
380 let rule_exclude = if options.allow_trailing_comma {
381 ""
382 } else {
383 "comma"
384 };
385
386 // Apply the grammar: static options, and the end-of-input and
387 // trailing-comma alternates, every one tagged `jsonc`.
388 let spec = GrammarSpec::from_value(grammar_document()?.clone())?;
389 parser.grammar_with_setting(&spec, &GrammarSetting::groups("jsonc"))?;
390
391 // Runtime options that depend on plugin arguments.
392 parser
393 .set_options(|engine| {
394 engine.comment.lex = comment_lex;
395 engine.rule.include = "jsonc,json".into();
396 engine.rule.exclude = rule_exclude.into();
397 })
398 .map_err(|error| GrammarError(error.0))?;
399
400 // A guard, not the budget (see `DEPTH_GUARD`): it replaces jsonic's,
401 // and a budget the caller sets runs beside it. Checked every step,
402 // because the check is what bounds the engine's quadratic cost on a
403 // deeply nested source; a sampled check would let the parse run past
404 // the limit by however many levels the sample missed.
405 parser.parse_guard(DEPTH_GUARD, within_depth_limit);
406
407 Ok(())
408}
409
410/// The plugin form of [`jsonc`], for [`Tabnas::use_plugin`]: the Rust
411/// counterpart of `tn.use(Jsonc, options)` and `j.Use(Jsonc, opts)`.
412///
413/// The option bag is the TypeScript one, `allowTrailingComma` and
414/// `disallowComments`, read through [`JsoncOptions::from_value`]; both
415/// default to off. Installed this way the plugin is re-applied to derived
416/// instances, as every native plugin is.
417///
418/// ```
419/// let mut parser = tabnas_jsonic::make();
420/// let options = tabnas_jsonc::JsoncOptions::new().with_disallow_comments(true);
421/// parser.use_plugin(tabnas_jsonc::plugin(), Some(options.to_value()))?;
422/// assert_eq!(parser.parse(r#"{"a":[1,2]}"#)?.to_string(), r#"{"a":[1,2]}"#);
423/// assert!(parser.parse("[1] // no comments").is_err());
424/// # Ok::<(), Box<dyn std::error::Error>>(())
425/// ```
426pub fn plugin() -> Plugin {
427 Plugin::new(PLUGIN_NAME, |parser, options| {
428 jsonc(parser, &JsoncOptions::from_value(options)).map_err(|error| PluginError(error.0))
429 })
430 .with_defaults(JsoncOptions::default().to_value())
431}
432
433/// Build a JSONC parser with the given options: a jsonic instance with
434/// the plugin installed through [`Tabnas::use_plugin`], which is the
435/// `new Tabnas().use(jsonic).use(Jsonc, options)` of the TypeScript
436/// suite and the `jsonic.Make()` then `j.Use(Jsonc, opts)` of the Go one.
437///
438/// Infallible by design: the grammar text is fixed and the jsonic base is
439/// installed one line earlier, so a failure here is a bug in this crate
440/// rather than anything a caller did.
441///
442/// ```
443/// let parser = tabnas_jsonc::make_with(
444/// tabnas_jsonc::JsoncOptions::new().with_allow_trailing_comma(true),
445/// );
446/// assert_eq!(parser.parse(r#"{ "hello": [], }"#)?.to_string(), r#"{"hello":[]}"#);
447/// # Ok::<(), tabnas_jsonc::JsoncError>(())
448/// ```
449pub fn make_with(options: JsoncOptions) -> Tabnas {
450 let mut parser = tabnas_jsonic::make();
451 parser
452 .use_plugin(plugin(), Some(options.to_value()))
453 .expect("the embedded jsonc grammar is fixed and installs on a fresh jsonic instance");
454 parser
455}
456
457/// Build a JSONC parser with the default options: comments on, trailing
458/// commas off.
459///
460/// ```
461/// let parser = tabnas_jsonc::make();
462/// assert_eq!(parser.parse("// a comment\n[1, 2]")?.to_string(), "[1,2]");
463/// assert_eq!(parser.parse("[1, 2, ]").unwrap_err().code, "unexpected");
464/// # Ok::<(), tabnas_jsonc::JsoncError>(())
465/// ```
466pub fn make() -> Tabnas {
467 make_with(JsoncOptions::default())
468}
469
470/// Parse a JSONC source string with the shared default parser.
471///
472/// The engine is built once, on first use, and reused after that; reuse
473/// is safe because [`Tabnas::parse`] takes `&self` and builds a fresh
474/// parse context per call, and `Tabnas` is `Send + Sync`. Building the
475/// grammar dominates a small parse, so this is what a caller with no
476/// options should use. The TypeScript package and the Go module have no
477/// package-level parse of their own; this one is the Rust convenience the
478/// sibling crates all offer.
479///
480/// Use [`make`] or [`make_with`] instead when the parser needs
481/// configuring: that returns a fresh instance and leaves this one alone.
482///
483/// A document that holds only trivia (whitespace and comments) has no
484/// value. The TypeScript plugin returns `undefined` for it; the Rust
485/// engine folds a top-level undefined into `Value::Null` at the end of
486/// every parse, so here it is `null`, which is also what the Go port's
487/// `nil` serializes as.
488///
489/// ```
490/// let value = tabnas_jsonc::parse(r#"{ "a": 1, /* one */ "b": [2] }"#)?;
491/// assert_eq!(value.to_string(), r#"{"a":1,"b":[2]}"#);
492/// assert_eq!(tabnas_jsonc::parse("// only a comment")?, tabnas::Value::Null);
493/// # Ok::<(), tabnas_jsonc::JsoncError>(())
494/// ```
495pub fn parse(src: &str) -> Result<Value, JsoncError> {
496 static DEFAULT: OnceLock<Tabnas> = OnceLock::new();
497 DEFAULT.get_or_init(make).parse(src)
498}
499
500/// One optional alchemy source and the entry point a host calls.
501#[derive(Clone, Copy, Debug, Eq, PartialEq)]
502pub struct TranslationPart {
503 /// The entry point a host calls.
504 pub entry: &'static str,
505 /// The source text, or `None` for an entry supplied by alchemy.
506 pub source: Option<&'static str>,
507}
508
509/// The package-local structural translation interface.
510#[derive(Clone, Copy, Debug, Eq, PartialEq)]
511pub struct TranslationParts {
512 /// The complete `tabnas.plugin.json` text.
513 pub manifest: &'static str,
514 /// An optional lift from the grammar's events to its first read shape.
515 pub lift: Option<TranslationPart>,
516 /// An optional render from the write shape to text.
517 pub render: Option<TranslationPart>,
518}
519
520const TRANSLATION: TranslationParts = TranslationParts {
521 manifest: include_str!("../translate/manifest.json"),
522 lift: None,
523 render: Some(TranslationPart {
524 entry: "json",
525 source: None,
526 }),
527};
528
529/// Return JSONC's immutable translation parts.
530#[must_use]
531pub const fn translate() -> Option<TranslationParts> {
532 Some(TRANSLATION)
533}
534
535/// The plugin's manifest, `tabnas.plugin.json`, as the repository carries
536/// it. Its `translate` object is what a host that translates reads: the
537/// shape JSONC is read as and written from (`tree`), the render that
538/// writes it, which is the `json` render alchemy carries rather than a
539/// file of this repository's, and the sentences that say what that render
540/// does not keep. The crate embeds its own copy, `translate/manifest.json`,
541/// since a packaged crate holds nothing outside `rs/`;
542/// `tests/translate_test.rs` holds the copy to the file.
543///
544/// ```
545/// assert!(tabnas_jsonc::manifest_text().contains("\"translate\""));
546/// ```
547pub fn manifest_text() -> &'static str {
548 TRANSLATION.manifest
549}