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.20";
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 the TypeScript `make(opts)`, which is
607/// `new Tabnas().use(jsonic).use(Zon, opts)`.
608///
609/// It declares `lex.window`, so that [`Tabnas::parse_reader`] reads a
610/// reader a window at a time rather than whole (admin ADR-30): the
611/// matchers this crate installs read the source only through the lexer's
612/// window, and jsonic's base is the engine's own matchers. The window is
613/// declared here, on the parser this crate makes whole, and not in
614/// [`zon`] or [`plugin`], which a host may install beneath matchers of
615/// its own.
616///
617/// Reuse the result: building the grammar dominates a parse.
618///
619/// Infallible by design: the documents are fixed literals, so a failure
620/// here is a bug in this crate rather than anything a caller did.
621///
622/// ```
623/// let parser = tabnas_zon::make_with(&tabnas_zon::ZonOptions {
624///     enum_tag: Some("$enum".to_string()),
625///     ..Default::default()
626/// });
627/// assert_eq!(
628///     parser.parse(".{ .kind = .red }")?.to_string(),
629///     r#"{"kind":{"$enum":"red"}}"#
630/// );
631/// # Ok::<(), tabnas_zon::ZonError>(())
632/// ```
633pub fn make_with(options: &ZonOptions) -> Tabnas {
634    let mut parser = tabnas_jsonic::make();
635    parser
636        .use_plugin(plugin(), Some(options.to_value()))
637        .expect("the zon grammar documents are fixed and valid");
638    parser
639        .set_options(|options| options.lex.window = true)
640        .expect("lex.window sets");
641    parser
642}
643
644/// Build a ZON parser with the default options.
645///
646/// ```
647/// let parser = tabnas_zon::make();
648/// assert_eq!(parser.parse(".{ .a = .{ .b = 1 } }")?.to_string(), r#"{"a":{"b":1}}"#);
649/// assert!(parser.parse("{ a = 1 }").is_err());
650/// # Ok::<(), tabnas_zon::ZonError>(())
651/// ```
652pub fn make() -> Tabnas {
653    make_with(&ZonOptions::default())
654}
655
656/// Parse a ZON source string with the shared default parser.
657///
658/// The engine is built once, on first use, and reused after that, as the
659/// Go `Parse` does through `sync.Once`. Reuse is safe: [`Tabnas::parse`]
660/// takes `&self` and builds a fresh parse context per call, and `Tabnas`
661/// is `Send + Sync`, so concurrent callers share one installed grammar.
662///
663/// Use [`make_with`] or [`parse_with`] when the parser needs options.
664///
665/// ```
666/// let value = tabnas_zon::parse(".{ .paths = .{ \"build.zig\", \"src\" } }")?;
667/// assert_eq!(value.to_string(), r#"{"paths":["build.zig","src"]}"#);
668/// assert_eq!(tabnas_zon::parse("0X2A").unwrap_err().code, "zon_number");
669/// # Ok::<(), tabnas_zon::ZonError>(())
670/// ```
671pub fn parse(src: &str) -> Result<Value, ZonError> {
672    static DEFAULT: OnceLock<Tabnas> = OnceLock::new();
673    DEFAULT.get_or_init(make).parse(src)
674}
675
676/// Parse a ZON source string with the given options, on a dedicated
677/// instance built for the call: the Go `Parse(src, opts)`. For many
678/// parses with the same options, build one parser with [`make_with`].
679///
680/// ```
681/// let options = tabnas_zon::ZonOptions { char_as_number: true, ..Default::default() };
682/// assert_eq!(tabnas_zon::parse_with("'\\n'", &options)?.to_string(), "10");
683/// # Ok::<(), tabnas_zon::ZonError>(())
684/// ```
685pub fn parse_with(src: &str, options: &ZonOptions) -> Result<Value, ZonError> {
686    make_with(options).parse(src)
687}
688
689/// One optional alchemy translation source and its explicit entry point.
690#[derive(Clone, Copy, Debug, Eq, PartialEq)]
691pub struct TranslationPart {
692    /// The definition a host calls after linking the source.
693    pub entry: &'static str,
694    /// The source text, or `None` for an entry supplied by alchemy.
695    pub source: Option<&'static str>,
696}
697
698/// The package-local structural translation interface.
699#[derive(Clone, Copy, Debug, Eq, PartialEq)]
700pub struct TranslationParts {
701    /// The complete `tabnas.plugin.json` text.
702    pub manifest: &'static str,
703    /// An optional lift from the grammar's events to its first read shape.
704    pub lift: Option<TranslationPart>,
705    /// An optional embedding of a plain tree in the format's schema, with its reverse.
706    pub embed: Option<TranslationPart>,
707    /// An optional render from the write shape to text.
708    pub render: Option<TranslationPart>,
709    /// An optional transducer: the format's JSON events from its parser's
710    /// rule passes, for a host that reads parser events.
711    pub transduce: Option<TranslationPart>,
712}
713
714const TRANSLATION: TranslationParts = TranslationParts {
715    manifest: include_str!("../translate/manifest.json"),
716    lift: None,
717    embed: None,
718    render: Some(TranslationPart {
719        entry: "zon-render",
720        source: Some(include_str!("../translate/render.alc")),
721    }),
722    transduce: Some(TranslationPart {
723        entry: "zon-transduce",
724        source: Some(include_str!("../translate/transduce.alc")),
725    }),
726};
727
728/// Return ZON's immutable translation parts.
729#[must_use]
730pub const fn translate() -> Option<TranslationParts> {
731    Some(TRANSLATION)
732}
733
734/// The plugin's manifest, `tabnas.plugin.json`, as the repository carries
735/// it. Its `translate` object is what a host that translates reads: the
736/// shape ZON is read as and written from (`tree`), the file that holds
737/// the render, and the sentences that say what the render does not keep.
738/// It also names the transducer part, `alchemy/transduce.alc`, the
739/// document's JSON events from the grammar's rule passes, through which a
740/// host that reads parser events reads a document. The crate embeds its
741/// own copies, `translate/manifest.json` and `translate/transduce.alc`,
742/// since a packaged crate holds nothing outside `rs/`;
743/// `tests/translate_test.rs` holds each copy to its file.
744///
745/// ```
746/// assert!(tabnas_zon::manifest_text().contains("\"translate\""));
747/// ```
748pub fn manifest_text() -> &'static str {
749    TRANSLATION.manifest
750}
751
752/// ZON's render, `alchemy/render.alc`, the file the manifest's
753/// `translate.render` names: a library of alchemy definitions, with no
754/// `export`, whose entry point `zon-render` writes a tree's events as one
755/// ZON document, a struct or tuple literal per container with every
756/// field name in the quoted identifier form. A host links it with its
757/// own program. The crate embeds its own copy, `translate/render.alc`,
758/// held to the file as the manifest's is.
759///
760/// ```
761/// assert!(tabnas_zon::render_text().contains("def zon-render [input]"));
762/// ```
763pub fn render_text() -> &'static str {
764    match TRANSLATION.render {
765        Some(part) => part.source.unwrap_or_default(),
766        None => "",
767    }
768}
769
770// ---------------------------------------------------------------------------
771// The option overrides, against the canonical plugin
772// ---------------------------------------------------------------------------
773
774#[cfg(test)]
775mod tests {
776    use super::options_document;
777    use std::fs;
778    use std::path::Path;
779
780    /// The canonical plugin's `grammarDef.options` literal, read out of
781    /// `ts/src/zon.ts`. It is TypeScript source rather than JSON, so the
782    /// body is walked rather than parsed.
783    fn canonical_overrides() -> String {
784        let source =
785            fs::read_to_string(Path::new(env!("CARGO_MANIFEST_DIR")).join("../ts/src/zon.ts"))
786                .expect("ts/src/zon.ts is readable");
787        let at = source
788            .find("grammarDef.options = ")
789            .expect("ts/src/zon.ts assigns grammarDef.options");
790        object_body(&source, at).to_string()
791    }
792
793    /// The body of the first object literal at or after `from`, with its
794    /// braces stripped. Line comments and single-quoted strings are
795    /// skipped so a `{`, `}` or `'` inside one cannot close the literal
796    /// early. Nothing in the literals read here uses a template literal,
797    /// a regular expression or a double-quoted string.
798    fn object_body(src: &str, from: usize) -> &str {
799        let bytes = src.as_bytes();
800        let mut i = from;
801        while i < bytes.len() && bytes[i] != b'{' {
802            i += 1;
803        }
804        assert!(i < bytes.len(), "no object literal after byte {from}");
805        let start = i + 1;
806        let mut depth = 1usize;
807        i = start;
808        while i < bytes.len() && 0 < depth {
809            match bytes[i] {
810                b'/' if bytes.get(i + 1) == Some(&b'/') => {
811                    while i < bytes.len() && bytes[i] != b'\n' {
812                        i += 1;
813                    }
814                }
815                b'\'' => {
816                    i += 1;
817                    while i < bytes.len() && bytes[i] != b'\'' {
818                        i += if bytes[i] == b'\\' { 2 } else { 1 };
819                    }
820                    i += 1;
821                }
822                b'{' => {
823                    depth += 1;
824                    i += 1;
825                }
826                b'}' => {
827                    depth -= 1;
828                    i += 1;
829                }
830                _ => i += 1,
831            }
832        }
833        assert_eq!(depth, 0, "unbalanced object literal after byte {from}");
834        &src[start..i - 1]
835    }
836
837    /// Every key of the object literal whose body this is, in source
838    /// order, paired with the byte index just past its colon. A key at
839    /// brace depth zero is recorded; anything nested belongs to an inner
840    /// literal and is left to a second call on that one.
841    fn entries(body: &str) -> Vec<(String, usize)> {
842        let bytes = body.as_bytes();
843        let mut out = Vec::new();
844        let mut word = String::new();
845        let mut depth = 0usize;
846        let mut i = 0usize;
847        while i < bytes.len() {
848            match bytes[i] {
849                b'/' if bytes.get(i + 1) == Some(&b'/') => {
850                    while i < bytes.len() && bytes[i] != b'\n' {
851                        i += 1;
852                    }
853                }
854                b'\'' => {
855                    let start = i + 1;
856                    i += 1;
857                    while i < bytes.len() && bytes[i] != b'\'' {
858                        i += if bytes[i] == b'\\' { 2 } else { 1 };
859                    }
860                    if 0 == depth {
861                        word = body[start..i].to_string();
862                    }
863                    i += 1;
864                }
865                b'{' | b'[' | b'(' => {
866                    depth += 1;
867                    i += 1;
868                }
869                b'}' | b']' | b')' => {
870                    depth -= 1;
871                    i += 1;
872                }
873                b':' if 0 == depth => {
874                    assert!(!word.is_empty(), "a value with no key in:\n{body}");
875                    out.push((std::mem::take(&mut word), i + 1));
876                    i += 1;
877                }
878                b',' if 0 == depth => {
879                    word.clear();
880                    i += 1;
881                }
882                c => {
883                    if 0 == depth {
884                        if c.is_ascii_alphanumeric() || b'_' == c || b'$' == c {
885                            word.push(c as char);
886                        } else {
887                            word.clear();
888                        }
889                    }
890                    i += 1;
891                }
892            }
893        }
894        out
895    }
896
897    fn keys(body: &str) -> Vec<String> {
898        entries(body).into_iter().map(|(key, _)| key).collect()
899    }
900
901    /// The body of the object literal bound to `key`.
902    fn field<'a>(body: &'a str, key: &str) -> &'a str {
903        let (_, at) = entries(body)
904            .into_iter()
905            .find(|(name, _)| name == key)
906            .unwrap_or_else(|| panic!("the canonical literal has no {key} key"));
907        object_body(body, at)
908    }
909
910    /// The keys of a `serde_json` object, in insertion order.
911    fn ported_keys(value: &serde_json::Value) -> Vec<String> {
912        value
913            .as_object()
914            .expect("an object")
915            .keys()
916            .cloned()
917            .collect()
918    }
919
920    /// AGENTS.md rule 4 requires the jsonic option overrides to exist in
921    /// all three runtimes and stay in step. Nothing measured that: the
922    /// two lists were kept aligned by reading them side by side. This
923    /// reads the canonical list out of `ts/src/zon.ts` and compares it
924    /// with the one this port installs, key by key, so an override added
925    /// or renamed there fails here instead of drifting silently.
926    #[test]
927    fn the_option_override_surface_is_the_canonical_one() {
928        let canonical = canonical_overrides();
929        let ported = options_document();
930        assert_eq!(keys(&canonical), ported_keys(&ported));
931
932        // The three tables AGENTS.md names cell by cell rather than by
933        // their presence alone: the error catalogue is the code contract
934        // a fixture pins, the fixed-token remap is what makes `.{` the
935        // only opener, and the matcher orders are what put zonDot ahead
936        // of the fixed-token matcher and zonDocComment ahead of the
937        // comment matcher.
938        assert_eq!(
939            keys(field(&canonical, "error")),
940            ported_keys(&ported["error"])
941        );
942        assert_eq!(
943            keys(field(field(&canonical, "fixed"), "token")),
944            ported_keys(&ported["fixed"]["token"])
945        );
946        let matchers = field(field(&canonical, "lex"), "match");
947        assert_eq!(keys(matchers), ported_keys(&ported["lex"]["match"]));
948        for (name, at) in entries(matchers) {
949            let body = object_body(matchers, at);
950            let (_, order_at) = entries(body)
951                .into_iter()
952                .find(|(field, _)| "order" == field)
953                .unwrap_or_else(|| panic!("{name} declares no order"));
954            let text: String = body[order_at..]
955                .chars()
956                .skip_while(char::is_ascii_whitespace)
957                .take_while(|c| !c.is_whitespace() && ',' != *c)
958                .collect();
959            let want: f64 = text
960                .parse()
961                .unwrap_or_else(|_| panic!("{name} has a non-numeric order {text:?}"));
962            assert_eq!(
963                ported["lex"]["match"][&name]["order"].as_f64(),
964                Some(want),
965                "{name}"
966            );
967        }
968    }
969
970    /// The two places this port's override document deliberately differs
971    /// from the canonical one. Both are asserted rather than left to
972    /// prose, so a repair in the engine that removes the reason for one
973    /// fails here and the note in `README.md` comes out with it.
974    #[test]
975    fn the_two_override_differences_are_the_documented_ones() {
976        let canonical = canonical_overrides();
977        let ported = options_document();
978
979        // `null` is left to the engine's default definition: a
980        // serialized `"val": null` reads as "no value" rather than as
981        // the null value, so restating it would switch the keyword off.
982        // The keyword still lexes, which `test/spec/scalars.tsv` pins.
983        assert_eq!(
984            keys(field(field(&canonical, "value"), "def")),
985            ["true", "false", "null"]
986        );
987        assert_eq!(ported_keys(&ported["value"]["def"]), ["true", "false"]);
988
989        // The canonical plugin also calls `tn.options` with a
990        // `config.modify` hook that hangs human token descriptions off
991        // `cfg.tokenDesc`, which `@tabnas/railroad` reads for a diagram
992        // legend. This engine's config has no such field, and the Rust
993        // railroad crate takes the descriptions from its own
994        // `ExtractOptions::token_desc` instead, so there is nothing for
995        // the plugin to attach and the override document carries no
996        // `config` block.
997        let source =
998            fs::read_to_string(Path::new(env!("CARGO_MANIFEST_DIR")).join("../ts/src/zon.ts"))
999                .expect("ts/src/zon.ts is readable");
1000        assert!(source.contains("'zon-tokendesc'"));
1001        assert!(source.contains("cfg.tokenDesc"));
1002        assert_eq!(ported.get("config"), None);
1003    }
1004}