Skip to main content

tabnas_zon/
lib.rs

1/* Copyright (c) 2025-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 and the jsonic crate allow the
6// lint at their own roots for the same reason; boxing here would make
7// `parse` return a different shape from `Tabnas::parse`.
8#![allow(clippy::result_large_err)]
9
10//! The Zig Object Notation (ZON) grammar plugin for the `tabnas` parsing
11//! engine.
12//!
13//! ZON is the data format of Zig `build.zig.zon` manifests, built on Zig
14//! anonymous struct literals:
15//!
16//! ```zon
17//! .{
18//!     .name = "example",
19//!     .version = "0.0.1",
20//!     .dependencies = .{ .foo = .{ .url = "https://..." } },
21//!     .paths = .{ "build.zig", "src" },
22//! }
23//! ```
24//!
25//! This is a jsonic plugin: it layers on the relaxed-JSON grammar of
26//! [`tabnas_jsonic`] and reshapes it into ZON, exactly as the canonical
27//! TypeScript plugin in `ts/src/zon.ts` does. It switches the jsonic
28//! extensions off (`rule.exclude: jsonic,imp`), remaps the fixed tokens
29//! (`.{` opens both structs and tuples, `}` closes both, `=` separates a
30//! field from its value), adds six lex matchers for Zig syntax, and
31//! prepends the grammar alternates in `zon-grammar.jsonic`, which every
32//! runtime embeds.
33//!
34//! ```
35//! let value = tabnas_zon::parse(".{ .name = \"Alice\", .age = 30 }")?;
36//! assert_eq!(value.to_string(), r#"{"name":"Alice","age":30}"#);
37//! # Ok::<(), tabnas_zon::ZonError>(())
38//! ```
39//!
40//! TypeScript is canonical: `ts/src/zon.ts` defines behaviour and option
41//! defaults. The shared fixtures in `test/spec/*.tsv` and the two zig
42//! reference corpora are the parity contract across TypeScript, Go and
43//! Rust.
44
45use std::cell::RefCell;
46use std::rc::Rc;
47use std::sync::OnceLock;
48
49use indexmap::IndexMap;
50use serde::{Deserialize, Serialize};
51use serde_json::json;
52use tabnas::{
53    ActionError, Context, GrammarSetting, GrammarSpec, Plugin, PluginError, Rule, RuleSnapshot,
54    Tabnas, Token, Value,
55};
56
57mod lex;
58mod number;
59
60/// This crate's version. It MUST equal `ts/package.json` "version": the
61/// release orchestrator rewrites both, and `tests/version_test.rs` fails
62/// the build if they drift. Mirrors `VERSION` in `ts/src/zon.ts` and
63/// `const VERSION` in `go/zon.go`.
64pub const VERSION: &str = "0.5.13";
65
66/// The README's Rust examples run as doctests, so a stale one fails the
67/// gate rather than misleading the reader. Its `toml` and `bash` fences
68/// are skipped; rustdoc runs only the `rust` ones.
69#[cfg(doctest)]
70#[doc = include_str!("../README.md")]
71mod readme_examples {}
72
73/// The error a failed parse produces, re-exported so callers need not
74/// depend on the engine crate directly.
75pub use tabnas::TabnasError as ZonError;
76
77/// The key of the object an integer literal becomes when no IEEE-754
78/// double holds its exact value: `{ "$big": "<decimal digits>" }`.
79///
80/// The canonical runtime returns such an integer as a `bigint`, the Go
81/// port as a `*big.Int`. The engine's [`Value`] has no big-integer
82/// variant, so this port keeps the digits instead of rounding them, in
83/// the shape the zig reference corpora already use to spell one. A
84/// smaller integer, `2^64` included, is a plain [`Value::Number`].
85pub const BIG_KEY: &str = "$big";
86
87// --- BEGIN EMBEDDED zon-grammar.jsonic ---
88pub const GRAMMAR_TEXT: &str = r##"
89# ZON Grammar Definition
90# Parses Zig Object Notation (ZON) - a data format based on Zig anonymous
91# struct literals.
92#
93# Example:
94#   .{
95#       .name = "example",
96#       .version = "0.0.1",
97#       .deps = .{ .foo = .{ .url = "https://..." } },
98#       .paths = .{ "build.zig", "src" },
99#   }
100#
101# The custom zon-dot lex matcher distinguishes struct (map) and tuple (list)
102# openings at lex time by peeking ahead:
103#   .{  followed by  .ident =    -> emits #OB  (struct / map)
104#   .{  otherwise                -> emits #OS  (tuple / list)
105# Both close on } which lexes as #CB. The list rules below use #CB (not
106# the default #CS) as the list terminator so that the single } character
107# closes both struct and tuple literals.
108#
109# A bare .identifier emits #TX with val = identifier (the leading dot is
110# stripped). This token is both a valid KEY (when followed by =) and a
111# valid VAL (when used as an enum literal).
112#
113# The grammar is applied with { rule: { alt: { g: 'zon' } } } so every
114# alt below is automatically tagged with the 'zon' group.
115
116{
117  rule: val: open: [
118    # Empty .{} -> empty list.
119    { s: '#OS #CB' b: 2 p: list g: 'list,empty' }
120  ]
121
122  rule: list: open: [
123    # @array$ allocates the list node (an empty array). Under the new core
124    # the list node is no longer auto-seeded: @tabnas/json's @array$ only
125    # runs on its own #OS open alts, which ZON replaces here. Without this
126    # the elem rule's @elem-bc/replace would push onto an undefined node.
127    { s: '#OS #CB' b: 1 a: '@array$' g: 'list,empty' }
128    { s: '#OS' p: elem a: '@array$' g: 'list,open' }
129  ]
130  rule: list: close: [
131    { s: '#CB' g: 'list,close' }
132  ]
133
134  rule: elem: close: [
135    { s: '#CA #CB' b: 1 g: 'elem,trailing,comma' }
136    { s: '#CA' r: elem g: 'elem,next,comma' }
137    { s: '#CB' b: 1 g: 'elem,end' }
138  ]
139
140  rule: pair: close: [
141    { s: '#CA #CB' b: 1 g: 'pair,trailing,comma' }
142    { s: '#CA' r: pair g: 'pair,next,comma' }
143    { s: '#CB' b: 1 g: 'pair,end' }
144  ]
145}
146"##;
147// --- END EMBEDDED zon-grammar.jsonic ---
148
149/// The name the plugin registers under, and so the namespace of its
150/// options on the instance.
151const PLUGIN_NAME: &str = "zon";
152
153/// The decoration that marks an instance the plugin has already
154/// configured, so a re-run cannot prepend the alternates twice. The Go
155/// port's `zon-init` guard.
156const INIT_MARK: &str = "zon-init";
157
158/// The duplicate-field guard. `/prepend`, so it runs before jsonic's own
159/// `@pair-bc`, which performs the assignment (last one wins) and would
160/// hide the collision by `@pair-ac`.
161const PAIR_BC: &str = "@pair-bc/prepend";
162
163/// The enum-tag rewrap. jsonic takes the `val` before-close phase with
164/// `/replace`, which suppresses any `/prepend` on it, so the rewrap runs
165/// after close instead, as it does in TypeScript. Here it is `/prepend`
166/// rather than the bare name TypeScript uses: the engine wires a bare
167/// `@val-ac` only when no `@val-ac/append` is registered, and jsonic
168/// registers one. Order within the phase does not matter, because
169/// jsonic's after-close leaves an enum token's node alone.
170const VAL_AC: &str = "@val-ac/prepend";
171
172// ---------------------------------------------------------------------------
173// Options
174// ---------------------------------------------------------------------------
175
176/// Plugin options. [`Default`] is the canonical `Zon.defaults`: character
177/// literals as one-character strings, enum literals as bare strings.
178#[derive(Debug, Clone, PartialEq, Eq, Default, Serialize, Deserialize)]
179#[serde(default, rename_all = "camelCase")]
180pub struct ZonOptions {
181    /// Parse Zig character literals (`'x'`) as numeric code points rather
182    /// than as one-character strings.
183    pub char_as_number: bool,
184
185    /// When set, wrap an enum literal used as a value (`.foo`) in
186    /// `{ "<enumTag>": "foo" }` instead of producing the bare string
187    /// `"foo"`. An empty string means unset, as in the Go port.
188    pub enum_tag: Option<String>,
189}
190
191impl ZonOptions {
192    /// The options as the engine's plugin option bag.
193    pub fn to_value(&self) -> Value {
194        Value::from_json(&serde_json::to_value(self).expect("the options serialise"))
195    }
196
197    /// The options read from a plugin option bag. A missing field is its
198    /// default and an unknown field is ignored, as the canonical plugin
199    /// reads `options.charAsNumber` and `options.enumTag` and nothing
200    /// else.
201    ///
202    /// Each field is read ON ITS OWN, and by JavaScript truthiness, which
203    /// is what `!!options.charAsNumber` and `options.enumTag || null`
204    /// mean in `ts/src/zon.ts`. Deserializing the bag as a whole instead
205    /// let one ill-typed field discard a well-typed one: the bag
206    /// `{"charAsNumber": true, "enumTag": false}` failed to deserialize
207    /// at `enumTag` and fell back to the DEFAULTS, so `'A'` parsed as
208    /// `"A"` where both other runtimes give `65`.
209    ///
210    /// The bag is read as the ENGINE value it is, never through
211    /// [`Value::to_json`]. That projection turns a non-finite number into
212    /// `null`, and `null` is falsy where `Infinity` is not: a
213    /// `charAsNumber` of `Infinity` is true in the canonical runtime and
214    /// would have read as false here, and an `enumTag` of `Infinity`
215    /// names the key `Infinity` there and would have read as unset here.
216    ///
217    /// The conversion is LOSSLESS for a string, the empty one included,
218    /// so that `from_value(&options.to_value())` returns the options it
219    /// was given. `tag` applies the canonical `|| null` filter at the
220    /// point of use instead.
221    pub fn from_value(value: &Value) -> Self {
222        let field = |name: &str| match value {
223            Value::Object(fields) => fields.get(name),
224            Value::MapRef(map) => map.value.get(name),
225            _ => None,
226        };
227        ZonOptions {
228            char_as_number: field("charAsNumber").is_some_and(truthy),
229            enum_tag: field("enumTag").and_then(tag_of),
230        }
231    }
232
233    fn tag(&self) -> Option<String> {
234        self.enum_tag.clone().filter(|tag| !tag.is_empty())
235    }
236}
237
238/// JavaScript truthiness, which is how the canonical plugin reads an
239/// option bag: `false`, `null`, `undefined`, `0`, `-0`, `NaN` and `""`
240/// are false, and every other value, `Infinity` and an empty array or
241/// object included, is true.
242fn truthy(value: &Value) -> bool {
243    match value {
244        Value::Undefined | Value::Null => false,
245        Value::Bool(flag) => *flag,
246        Value::Number(number) => *number != 0.0 && !number.is_nan(),
247        Value::String(text) => !text.is_empty(),
248        Value::Text(text) => !text.string.is_empty(),
249        _ => true,
250    }
251}
252
253/// The `enumTag` option as this port's `Option<String>`.
254///
255/// A string is kept VERBATIM, an empty one included: the conversion
256/// layer is lossless and the semantic filter belongs at the point of
257/// use, which is [`ZonOptions::tag`]. Anything else is outside the
258/// option's declared `null | string`, and the canonical
259/// `options.enumTag || null` has already discarded a falsy one before it
260/// can become a computed property key, so a falsy one is unset here too.
261fn tag_of(value: &Value) -> Option<String> {
262    match value {
263        Value::String(text) => Some(text.clone()),
264        Value::Text(text) => Some(text.string.clone()),
265        other if truthy(other) => Some(key_of(other)),
266        _ => None,
267    }
268}
269
270/// A truthy `enumTag` as the key it names. The option's type is
271/// `null | string`, and a string is itself; the canonical plugin uses
272/// whatever else it is given as a computed property key, which
273/// stringifies it. A boolean spells itself, and a number spells itself as
274/// `Number::toString` does, which is neither Rust's shortest form nor
275/// serde_json's: `10000000000000000` is written out in full and `1e21`
276/// is not. An ARRAY or an OBJECT, further outside the option's type
277/// still, keeps its JSON spelling here rather than taking the
278/// `Array.prototype.toString` and `[object Object]` of JavaScript, which
279/// `DIVERGENCE.md` records, along with the `null` a non-finite element
280/// of one becomes on the way through `to_json`.
281fn key_of(value: &Value) -> String {
282    match value {
283        Value::String(text) => text.clone(),
284        Value::Text(text) => text.string.clone(),
285        Value::Number(number) => number::js_number_to_string(*number),
286        Value::Bool(flag) => flag.to_string(),
287        // Neither reaches here through `tag_of`, which discards a falsy
288        // value first, as `options.enumTag || null` does. They are the
289        // spellings JavaScript would use if one ever did.
290        Value::Null => "null".to_string(),
291        Value::Undefined => "undefined".to_string(),
292        // A container, where this port stops matching anyway. Every
293        // option number is an engine `f64`, so `1` inside one arrives as
294        // `1.0`; the same restoration the grammar document needs puts
295        // the integer spelling back.
296        other => integral_numbers(other.to_json()).to_string(),
297    }
298}
299
300// ---------------------------------------------------------------------------
301// The grammar document
302// ---------------------------------------------------------------------------
303
304/// The jsonic option overrides, as the serialized `options` block of the
305/// grammar document, so the plugin applies them atomically alongside its
306/// rule alternates: the `grammarDef.options` of the canonical plugin.
307fn options_document() -> serde_json::Value {
308    json!({
309        "rule": {
310            // Remove the jsonic extensions (implicit maps and lists,
311            // top-level commas, path dives). ZON uses explicit struct
312            // literals only.
313            "exclude": "jsonic,imp",
314            "start": "val",
315        },
316        "fixed": {
317            "token": {
318                // Bare `{`, `[`, `]` are not valid in ZON. Struct opening
319                // is `.{`, which the zonDot lex matcher handles.
320                "#OB": null,
321                "#OS": null,
322                "#CS": null,
323                // `=` replaces `:` as the key/value separator.
324                "#CL": "=",
325            },
326        },
327        "tokenSet": {
328            // ZON field names are identifiers (`.ident` or `.@"..."`) only.
329            //
330            // Mirrors the TS `KEY: ['#TX', null, null, null]`, and the
331            // three trailing nulls are LOAD-BEARING. The engine overlays a
332            // named token set onto the installed one BY INDEX, so a bare
333            // `["#TX"]` overwrites slot 0 and leaves the default `#NR`,
334            // `#ST` and `#VL` live behind it -- and `.{ .a = 1, "b" = 2 }`
335            // parsed. A `null` member clears its position.
336            //
337            // It takes effect in this port too. tabnas-jsonic's `#KEY #CL`
338            // alternates are installed before this plugin runs, and the
339            // engine resolves a token set against the options in force
340            // (tabnas/parser#217, engine 0.12.3); pinned by
341            // `a_field_name_that_is_not_a_field_is_refused`.
342            "KEY": ["#TX", null, null, null],
343        },
344        // The engine's string matcher is off: `"..."` is lexed by the
345        // zonString matcher with Zig's escape set, which is narrower than
346        // the relaxed-JSON one and refuses a surrogate `\u{...}`.
347        "string": {
348            "lex": false,
349        },
350        // The relaxed number lexer accepts `+1`, `.5`, `5.`, `0123`,
351        // `1__0` and friends, none of which are ZON. The zonNumber matcher
352        // implements Zig's numeric literal grammar exactly instead.
353        "number": {
354            "lex": false,
355        },
356        "error": {
357            "zon_number": "invalid ZON number literal: {src}",
358            "zon_ident": "invalid ZON identifier: {src}",
359            "zon_char": "invalid ZON character literal: {src}",
360            "zon_doc_comment": "doc comments are not allowed in ZON: {src}",
361            "zon_dup_field": "duplicate struct field name: {src}",
362        },
363        // A hint for each code, keyed alike. Without one the engine falls
364        // back to its hint for an UNKNOWN code, which tells the reader the
365        // error is probably a bug in jsonic or a plugin.
366        "hint": {
367            "zon_number": "A ZON number is a Zig literal, such as 0, 42, 1_000, 3.14, 1.e3, 0x2a,\n0x1.8p3, 0o17 or 0b101. After a lowercase base prefix every digit is of\nthat base, and there is at least one. A decimal integer part other\nthan 0 does not start with 0. Only decimal and hex numbers take a\nfraction or an exponent (e, or p for hex), and an exponent needs\ndigits. An underscore goes only between two digits. A negative zero is\nwritten -0.0, not -0, and nan takes no sign.",
368            "zon_ident": "A ZON field name is .name, a letter or underscore then letters, digits\nand underscores, or .@\"text\" for any other name; the quoted form must\nnot be empty or hold an invalid escape.",
369            "zon_char": "A ZON character literal holds exactly one character or escape between\nsingle quotes, as in 'a', and names a code point no higher than U+10FFFF.",
370            "zon_doc_comment": "ZON allows only plain // comments. Doc comments, /// and //!, belong to\nZig source; change them to //.",
371            "zon_dup_field": "A struct literal may name each field only once, and {src} appears\nagain. Remove or rename the repeated field.",
372        },
373        // Only `//` line comments in ZON.
374        "comment": {
375            "lex": true,
376            "def": {
377                "hash": { "lex": false },
378                "slash": { "line": true, "start": "//", "lex": true, "eatline": false },
379                "multi": { "lex": false },
380            },
381        },
382        // `true`, `false` and `null` still lex with the text matcher off,
383        // because the value matcher runs on its own. The engine's default
384        // definitions are exactly these three; `true` and `false` are
385        // restated as the canonical plugin states them, and `null` is
386        // left to the default because a serialized `"val": null` reads as
387        // "no value" rather than as the null value.
388        "value": {
389            "lex": true,
390            "def": {
391                "true": { "val": true },
392                "false": { "val": false },
393            },
394        },
395        // The text matcher is off: identifiers only ever appear as
396        // `.ident` / `.@"..."` and are produced by zonDot.
397        "text": {
398            "lex": false,
399        },
400        "lex": {
401            "match": {
402                "zonDot": { "order": 1e5, "make": lex::DOT },
403                "zonMultiString": { "order": 1.1e5, "make": lex::MULTI_STRING },
404                "zonChar": { "order": 1.2e5, "make": lex::CHAR },
405                "zonNumber": { "order": 1.3e5, "make": lex::NUMBER },
406                // Must out-order the comment matcher so `//!` and `///`
407                // are rejected instead of being eaten as line comments.
408                "zonDocComment": { "order": 1.4e5, "make": lex::DOC_COMMENT },
409                "zonString": { "order": 1.5e5, "make": lex::STRING },
410            },
411        },
412    })
413}
414
415/// The grammar document: [`GRAMMAR_TEXT`] parsed with jsonic, as the
416/// canonical plugin parses it (`new Tabnas().use(jsonic).parse(grammarText)`),
417/// with the option overrides attached.
418///
419/// The text is parsed once per process: it is a fixed literal, so every
420/// instance gets the same rule table.
421fn grammar_document() -> Result<serde_json::Value, PluginError> {
422    static RULES: OnceLock<Result<serde_json::Value, String>> = OnceLock::new();
423    let rules = RULES.get_or_init(|| {
424        let parsed = tabnas_jsonic::parse(GRAMMAR_TEXT)
425            .map_err(|error| format!("zon: failed to parse grammar text: {error}"))?;
426        let document = integral_numbers(parsed.to_json());
427        if !document
428            .get("rule")
429            .is_some_and(serde_json::Value::is_object)
430        {
431            return Err("zon: grammar text did not parse to a rule table".to_string());
432        }
433        Ok(document)
434    });
435    let mut document = rules.clone().map_err(PluginError)?;
436    document["options"] = options_document();
437    Ok(document)
438}
439
440/// jsonic's numbers are doubles, so `b: 2` arrives as `2.0`; the alternate
441/// decoder reads an integer field as an integer. Put every whole number
442/// back into integer form.
443fn integral_numbers(value: serde_json::Value) -> serde_json::Value {
444    match value {
445        serde_json::Value::Number(number) => match number.as_f64() {
446            Some(f) if f.fract() == 0.0 && f.abs() < 9.0e15 => json!(f as i64),
447            _ => serde_json::Value::Number(number),
448        },
449        serde_json::Value::Array(items) => {
450            serde_json::Value::Array(items.into_iter().map(integral_numbers).collect())
451        }
452        serde_json::Value::Object(fields) => serde_json::Value::Object(
453            fields
454                .into_iter()
455                .map(|(key, value)| (key, integral_numbers(value)))
456                .collect(),
457        ),
458        other => other,
459    }
460}
461
462// ---------------------------------------------------------------------------
463// Lifecycle hooks
464// ---------------------------------------------------------------------------
465
466/// Zig rejects a struct literal that repeats a field name. jsonic's own
467/// `@pair-bc` performs the assignment (last one wins), so this guard runs
468/// before it, and fails the parse by handing back the key's token marked
469/// `zon_dup_field`, as the canonical hook returns it.
470fn pair_duplicate_guard(
471    rule: &mut Rule,
472    context: &mut Context,
473    _next: Option<&RuleSnapshot>,
474    _out: Option<Token>,
475) -> Result<Option<Token>, ActionError> {
476    if !matches!(rule.u.get("pair"), Some(Value::Bool(true))) {
477        return Ok(None);
478    }
479    let Some(Value::String(key)) = rule.u.get("key").cloned() else {
480        return Ok(None);
481    };
482    let present = match &*rule.node.borrow() {
483        Value::Object(fields) => fields.contains_key(&key),
484        Value::MapRef(map) => map.value.contains_key(&key),
485        _ => false,
486    };
487    if !present {
488        return Ok(None);
489    }
490    let Some(mut token) = rule.o0().cloned().or_else(|| context.t0().cloned()) else {
491        return Ok(None);
492    };
493    token.bad_with_details("zon_dup_field", [("key".to_string(), Value::String(key))]);
494    Ok(Some(token))
495}
496
497/// With `enumTag` set, wrap the node an enum literal token produced in
498/// `{ [enumTag]: name }`. The token carries the mark the zonDot matcher
499/// set, which is what tells `.foo` from the string `"foo"`.
500fn enum_rewrap(tag: String) -> impl Fn(&mut Rule, &mut Context) -> Result<(), ActionError> {
501    move |rule, _context| {
502        if !rule.child_node.is_undefined() || rule.os() == 0 {
503            return Ok(());
504        }
505        let Some(token) = rule.o0() else {
506            return Ok(());
507        };
508        if !matches!(
509            token.use_data().get(lex::ENUM_MARK),
510            Some(Value::Bool(true))
511        ) {
512            return Ok(());
513        }
514        let Value::String(name) = token.val.clone() else {
515            return Ok(());
516        };
517        let mut wrapped = IndexMap::new();
518        wrapped.insert(tag.clone(), Value::String(name));
519        // A fresh cell: the rule's node is ASSIGNED, never written through
520        // the cell it may share with its parent.
521        rule.node = Rc::new(RefCell::new(Value::object(wrapped)));
522        Ok(())
523    }
524}
525
526// ---------------------------------------------------------------------------
527// Public surface
528// ---------------------------------------------------------------------------
529
530/// Install the ZON grammar on a jsonic-enabled instance, with typed
531/// options: the plugin function itself.
532///
533/// The instance must already carry the relaxed-JSON grammar, from
534/// [`tabnas_jsonic::make`] or [`tabnas_jsonic::jsonic`]; ZON reshapes
535/// jsonic's `val` / `map` / `list` / `pair` / `elem` rules rather than
536/// declaring its own. A second call on the same instance is a no-op, as
537/// in the Go port, so a plugin re-run cannot double the alternates.
538///
539/// ```
540/// let mut parser = tabnas_jsonic::make();
541/// tabnas_zon::zon(&mut parser, &tabnas_zon::ZonOptions::default())?;
542/// assert_eq!(parser.parse(".{ 1, 2, 3 }")?.to_string(), "[1,2,3]");
543/// # Ok::<(), Box<dyn std::error::Error>>(())
544/// ```
545pub fn zon(parser: &mut Tabnas, options: &ZonOptions) -> Result<(), PluginError> {
546    if parser.decoration::<bool>(INIT_MARK).is_some() {
547        return Ok(());
548    }
549    // ZON reshapes jsonic's rules rather than declaring its own, so an
550    // instance without them (a bare engine) gets a clear refusal now
551    // instead of a grammar that can parse nothing later.
552    let names = parser.rule_names();
553    let missing: Vec<&str> = ["val", "map", "list", "pair", "elem"]
554        .into_iter()
555        .filter(|rule| !names.iter().any(|name| name.as_str() == *rule))
556        .collect();
557    if !missing.is_empty() {
558        return Err(PluginError(format!(
559            "zon: the instance has no {} rule; install the jsonic grammar first",
560            missing.join(", ")
561        )));
562    }
563
564    // Every closure the grammar names, registered before the document
565    // that names them is installed.
566    parser.state_action_with_next_ref(PAIR_BC, pair_duplicate_guard);
567    if let Some(tag) = options.tag() {
568        parser.state_action_ref(VAL_AC, enum_rewrap(tag));
569    }
570    lex::register(parser, options.char_as_number);
571
572    let spec = GrammarSpec::from_value(grammar_document()?)
573        .map_err(|error| PluginError(format!("zon: invalid grammar document: {error}")))?;
574    // Every alternate is tagged `zon`, so a caller can exclude them with
575    // `rule.exclude`.
576    parser
577        .grammar_with_setting(&spec, &GrammarSetting::groups("zon"))
578        .map_err(|error| PluginError(format!("zon: failed to apply grammar: {error}")))?;
579    // Marked only once everything above succeeded: a failed install (a
580    // bare engine, say) must not turn the next call into a silent no-op.
581    parser.decorate(INIT_MARK, true);
582    Ok(())
583}
584
585/// The plugin form of [`zon`], for [`Tabnas::use_plugin`]. Its defaults
586/// are [`ZonOptions::default`], and the option bag a caller passes is
587/// merged over them by the engine, as `UseDefaults` merges them in Go.
588///
589/// ```
590/// let mut parser = tabnas_jsonic::make();
591/// parser.use_plugin(
592///     tabnas_zon::plugin(),
593///     Some(tabnas_zon::ZonOptions { char_as_number: true, ..Default::default() }.to_value()),
594/// )?;
595/// assert_eq!(parser.parse("'A'")?.to_string(), "65");
596/// # Ok::<(), Box<dyn std::error::Error>>(())
597/// ```
598pub fn plugin() -> Plugin {
599    Plugin::new(PLUGIN_NAME, |parser, options| {
600        zon(parser, &ZonOptions::from_value(options))
601    })
602    .with_defaults(ZonOptions::default().to_value())
603}
604
605/// Build a ZON parser with the given options: the counterpart of the Go
606/// `MakeJsonic(opts)` and of `new Tabnas().use(jsonic).use(Zon, opts)`.
607///
608/// Reuse the result: building the grammar dominates a parse.
609///
610/// Infallible by design: the documents are fixed literals, so a failure
611/// here is a bug in this crate rather than anything a caller did.
612///
613/// ```
614/// let parser = tabnas_zon::make_with(&tabnas_zon::ZonOptions {
615///     enum_tag: Some("$enum".to_string()),
616///     ..Default::default()
617/// });
618/// assert_eq!(
619///     parser.parse(".{ .kind = .red }")?.to_string(),
620///     r#"{"kind":{"$enum":"red"}}"#
621/// );
622/// # Ok::<(), tabnas_zon::ZonError>(())
623/// ```
624pub fn make_with(options: &ZonOptions) -> Tabnas {
625    let mut parser = tabnas_jsonic::make();
626    parser
627        .use_plugin(plugin(), Some(options.to_value()))
628        .expect("the zon grammar documents are fixed and valid");
629    parser
630}
631
632/// Build a ZON parser with the default options.
633///
634/// ```
635/// let parser = tabnas_zon::make();
636/// assert_eq!(parser.parse(".{ .a = .{ .b = 1 } }")?.to_string(), r#"{"a":{"b":1}}"#);
637/// assert!(parser.parse("{ a = 1 }").is_err());
638/// # Ok::<(), tabnas_zon::ZonError>(())
639/// ```
640pub fn make() -> Tabnas {
641    make_with(&ZonOptions::default())
642}
643
644/// Parse a ZON source string with the shared default parser.
645///
646/// The engine is built once, on first use, and reused after that, as the
647/// Go `Parse` does through `sync.Once`. Reuse is safe: [`Tabnas::parse`]
648/// takes `&self` and builds a fresh parse context per call, and `Tabnas`
649/// is `Send + Sync`, so concurrent callers share one installed grammar.
650///
651/// Use [`make_with`] or [`parse_with`] when the parser needs options.
652///
653/// ```
654/// let value = tabnas_zon::parse(".{ .paths = .{ \"build.zig\", \"src\" } }")?;
655/// assert_eq!(value.to_string(), r#"{"paths":["build.zig","src"]}"#);
656/// assert_eq!(tabnas_zon::parse("0X2A").unwrap_err().code, "zon_number");
657/// # Ok::<(), tabnas_zon::ZonError>(())
658/// ```
659pub fn parse(src: &str) -> Result<Value, ZonError> {
660    static DEFAULT: OnceLock<Tabnas> = OnceLock::new();
661    DEFAULT.get_or_init(make).parse(src)
662}
663
664/// Parse a ZON source string with the given options, on a dedicated
665/// instance built for the call: the Go `Parse(src, opts)`. For many
666/// parses with the same options, build one parser with [`make_with`].
667///
668/// ```
669/// let options = tabnas_zon::ZonOptions { char_as_number: true, ..Default::default() };
670/// assert_eq!(tabnas_zon::parse_with("'\\n'", &options)?.to_string(), "10");
671/// # Ok::<(), tabnas_zon::ZonError>(())
672/// ```
673pub fn parse_with(src: &str, options: &ZonOptions) -> Result<Value, ZonError> {
674    make_with(options).parse(src)
675}
676
677/// One optional alchemy translation source and its explicit entry point.
678#[derive(Clone, Copy, Debug, Eq, PartialEq)]
679pub struct TranslationPart {
680    /// The definition a host calls after linking the source.
681    pub entry: &'static str,
682    /// The source text, or `None` for an entry supplied by alchemy.
683    pub source: Option<&'static str>,
684}
685
686/// The package-local structural translation interface.
687#[derive(Clone, Copy, Debug, Eq, PartialEq)]
688pub struct TranslationParts {
689    /// The complete `tabnas.plugin.json` text.
690    pub manifest: &'static str,
691    /// An optional lift from the grammar's events to its first read shape.
692    pub lift: Option<TranslationPart>,
693    /// An optional render from the write shape to text.
694    pub render: Option<TranslationPart>,
695}
696
697const TRANSLATION: TranslationParts = TranslationParts {
698    manifest: include_str!("../translate/manifest.json"),
699    lift: None,
700    render: Some(TranslationPart {
701        entry: "zon-render",
702        source: Some(include_str!("../translate/render.alc")),
703    }),
704};
705
706/// Return ZON's immutable translation parts.
707#[must_use]
708pub const fn translate() -> Option<TranslationParts> {
709    Some(TRANSLATION)
710}
711
712/// The plugin's manifest, `tabnas.plugin.json`, as the repository carries
713/// it. Its `translate` object is what a host that translates reads: the
714/// shape ZON is read as and written from (`tree`), the file that holds
715/// the render, and the sentences that say what the render does not keep.
716/// The crate embeds its own copy, `translate/manifest.json`, since a
717/// packaged crate holds nothing outside `rs/`; `tests/translate_test.rs`
718/// holds the copy to the file.
719///
720/// ```
721/// assert!(tabnas_zon::manifest_text().contains("\"translate\""));
722/// ```
723pub fn manifest_text() -> &'static str {
724    TRANSLATION.manifest
725}
726
727/// ZON's render, `alchemy/render.alc`, the file the manifest's
728/// `translate.render` names: a library of alchemy definitions, with no
729/// `export`, whose entry point `zon-render` writes a tree's events as one
730/// ZON document, a struct or tuple literal per container with every
731/// field name in the quoted identifier form. A host links it with its
732/// own program. The crate embeds its own copy, `translate/render.alc`,
733/// held to the file as the manifest's is.
734///
735/// ```
736/// assert!(tabnas_zon::render_text().contains("def zon-render [input]"));
737/// ```
738pub fn render_text() -> &'static str {
739    match TRANSLATION.render {
740        Some(part) => part.source.unwrap_or_default(),
741        None => "",
742    }
743}
744
745// ---------------------------------------------------------------------------
746// The option overrides, against the canonical plugin
747// ---------------------------------------------------------------------------
748
749#[cfg(test)]
750mod tests {
751    use super::options_document;
752    use std::fs;
753    use std::path::Path;
754
755    /// The canonical plugin's `grammarDef.options` literal, read out of
756    /// `ts/src/zon.ts`. It is TypeScript source rather than JSON, so the
757    /// body is walked rather than parsed.
758    fn canonical_overrides() -> String {
759        let source =
760            fs::read_to_string(Path::new(env!("CARGO_MANIFEST_DIR")).join("../ts/src/zon.ts"))
761                .expect("ts/src/zon.ts is readable");
762        let at = source
763            .find("grammarDef.options = ")
764            .expect("ts/src/zon.ts assigns grammarDef.options");
765        object_body(&source, at).to_string()
766    }
767
768    /// The body of the first object literal at or after `from`, with its
769    /// braces stripped. Line comments and single-quoted strings are
770    /// skipped so a `{`, `}` or `'` inside one cannot close the literal
771    /// early. Nothing in the literals read here uses a template literal,
772    /// a regular expression or a double-quoted string.
773    fn object_body(src: &str, from: usize) -> &str {
774        let bytes = src.as_bytes();
775        let mut i = from;
776        while i < bytes.len() && bytes[i] != b'{' {
777            i += 1;
778        }
779        assert!(i < bytes.len(), "no object literal after byte {from}");
780        let start = i + 1;
781        let mut depth = 1usize;
782        i = start;
783        while i < bytes.len() && 0 < depth {
784            match bytes[i] {
785                b'/' if bytes.get(i + 1) == Some(&b'/') => {
786                    while i < bytes.len() && bytes[i] != b'\n' {
787                        i += 1;
788                    }
789                }
790                b'\'' => {
791                    i += 1;
792                    while i < bytes.len() && bytes[i] != b'\'' {
793                        i += if bytes[i] == b'\\' { 2 } else { 1 };
794                    }
795                    i += 1;
796                }
797                b'{' => {
798                    depth += 1;
799                    i += 1;
800                }
801                b'}' => {
802                    depth -= 1;
803                    i += 1;
804                }
805                _ => i += 1,
806            }
807        }
808        assert_eq!(depth, 0, "unbalanced object literal after byte {from}");
809        &src[start..i - 1]
810    }
811
812    /// Every key of the object literal whose body this is, in source
813    /// order, paired with the byte index just past its colon. A key at
814    /// brace depth zero is recorded; anything nested belongs to an inner
815    /// literal and is left to a second call on that one.
816    fn entries(body: &str) -> Vec<(String, usize)> {
817        let bytes = body.as_bytes();
818        let mut out = Vec::new();
819        let mut word = String::new();
820        let mut depth = 0usize;
821        let mut i = 0usize;
822        while i < bytes.len() {
823            match bytes[i] {
824                b'/' if bytes.get(i + 1) == Some(&b'/') => {
825                    while i < bytes.len() && bytes[i] != b'\n' {
826                        i += 1;
827                    }
828                }
829                b'\'' => {
830                    let start = i + 1;
831                    i += 1;
832                    while i < bytes.len() && bytes[i] != b'\'' {
833                        i += if bytes[i] == b'\\' { 2 } else { 1 };
834                    }
835                    if 0 == depth {
836                        word = body[start..i].to_string();
837                    }
838                    i += 1;
839                }
840                b'{' | b'[' | b'(' => {
841                    depth += 1;
842                    i += 1;
843                }
844                b'}' | b']' | b')' => {
845                    depth -= 1;
846                    i += 1;
847                }
848                b':' if 0 == depth => {
849                    assert!(!word.is_empty(), "a value with no key in:\n{body}");
850                    out.push((std::mem::take(&mut word), i + 1));
851                    i += 1;
852                }
853                b',' if 0 == depth => {
854                    word.clear();
855                    i += 1;
856                }
857                c => {
858                    if 0 == depth {
859                        if c.is_ascii_alphanumeric() || b'_' == c || b'$' == c {
860                            word.push(c as char);
861                        } else {
862                            word.clear();
863                        }
864                    }
865                    i += 1;
866                }
867            }
868        }
869        out
870    }
871
872    fn keys(body: &str) -> Vec<String> {
873        entries(body).into_iter().map(|(key, _)| key).collect()
874    }
875
876    /// The body of the object literal bound to `key`.
877    fn field<'a>(body: &'a str, key: &str) -> &'a str {
878        let (_, at) = entries(body)
879            .into_iter()
880            .find(|(name, _)| name == key)
881            .unwrap_or_else(|| panic!("the canonical literal has no {key} key"));
882        object_body(body, at)
883    }
884
885    /// The keys of a `serde_json` object, in insertion order.
886    fn ported_keys(value: &serde_json::Value) -> Vec<String> {
887        value
888            .as_object()
889            .expect("an object")
890            .keys()
891            .cloned()
892            .collect()
893    }
894
895    /// AGENTS.md rule 4 requires the jsonic option overrides to exist in
896    /// all three runtimes and stay in step. Nothing measured that: the
897    /// two lists were kept aligned by reading them side by side. This
898    /// reads the canonical list out of `ts/src/zon.ts` and compares it
899    /// with the one this port installs, key by key, so an override added
900    /// or renamed there fails here instead of drifting silently.
901    #[test]
902    fn the_option_override_surface_is_the_canonical_one() {
903        let canonical = canonical_overrides();
904        let ported = options_document();
905        assert_eq!(keys(&canonical), ported_keys(&ported));
906
907        // The three tables AGENTS.md names cell by cell rather than by
908        // their presence alone: the error catalogue is the code contract
909        // a fixture pins, the fixed-token remap is what makes `.{` the
910        // only opener, and the matcher orders are what put zonDot ahead
911        // of the fixed-token matcher and zonDocComment ahead of the
912        // comment matcher.
913        assert_eq!(
914            keys(field(&canonical, "error")),
915            ported_keys(&ported["error"])
916        );
917        assert_eq!(
918            keys(field(field(&canonical, "fixed"), "token")),
919            ported_keys(&ported["fixed"]["token"])
920        );
921        let matchers = field(field(&canonical, "lex"), "match");
922        assert_eq!(keys(matchers), ported_keys(&ported["lex"]["match"]));
923        for (name, at) in entries(matchers) {
924            let body = object_body(matchers, at);
925            let (_, order_at) = entries(body)
926                .into_iter()
927                .find(|(field, _)| "order" == field)
928                .unwrap_or_else(|| panic!("{name} declares no order"));
929            let text: String = body[order_at..]
930                .chars()
931                .skip_while(char::is_ascii_whitespace)
932                .take_while(|c| !c.is_whitespace() && ',' != *c)
933                .collect();
934            let want: f64 = text
935                .parse()
936                .unwrap_or_else(|_| panic!("{name} has a non-numeric order {text:?}"));
937            assert_eq!(
938                ported["lex"]["match"][&name]["order"].as_f64(),
939                Some(want),
940                "{name}"
941            );
942        }
943    }
944
945    /// The two places this port's override document deliberately differs
946    /// from the canonical one. Both are asserted rather than left to
947    /// prose, so a repair in the engine that removes the reason for one
948    /// fails here and the note in `README.md` comes out with it.
949    #[test]
950    fn the_two_override_differences_are_the_documented_ones() {
951        let canonical = canonical_overrides();
952        let ported = options_document();
953
954        // `null` is left to the engine's default definition: a
955        // serialized `"val": null` reads as "no value" rather than as
956        // the null value, so restating it would switch the keyword off.
957        // The keyword still lexes, which `test/spec/scalars.tsv` pins.
958        assert_eq!(
959            keys(field(field(&canonical, "value"), "def")),
960            ["true", "false", "null"]
961        );
962        assert_eq!(ported_keys(&ported["value"]["def"]), ["true", "false"]);
963
964        // The canonical plugin also calls `tn.options` with a
965        // `config.modify` hook that hangs human token descriptions off
966        // `cfg.tokenDesc`, which `@tabnas/railroad` reads for a diagram
967        // legend. This engine's config has no such field, and the Rust
968        // railroad crate takes the descriptions from its own
969        // `ExtractOptions::token_desc` instead, so there is nothing for
970        // the plugin to attach and the override document carries no
971        // `config` block.
972        let source =
973            fs::read_to_string(Path::new(env!("CARGO_MANIFEST_DIR")).join("../ts/src/zon.ts"))
974                .expect("ts/src/zon.ts is readable");
975        assert!(source.contains("'zon-tokendesc'"));
976        assert!(source.contains("cfg.tokenDesc"));
977        assert_eq!(ported.get("config"), None);
978    }
979}