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