Skip to main content

tabnas_xml/
lib.rs

1/* Copyright (c) 2021-2026 Richard Rodger and other contributors, MIT License */
2
3// The engine's error carries a code, position, hint and a formatted
4// report, so it is large by design and `Result<_, TabnasError>` trips
5// clippy's `result_large_err`. The engine allows the lint at its own crate
6// root for the same reason; boxing here would make `parse` return a
7// different shape from `Tabnas::parse` and from the other two ports.
8#![allow(clippy::result_large_err)]
9
10//! The XML grammar plugin for the `tabnas` parsing engine.
11//!
12//! Parses XML text into a tree of elements: attributes, mixed content,
13//! namespaces, entities (the five predefined plus numeric character
14//! references, custom entities, and DOCTYPE `<!ENTITY>` declarations),
15//! CDATA sections, comments, processing instructions and DOCTYPE
16//! declarations (including `<!ATTLIST>` attribute defaults and
17//! `xml:space` / `xml:lang` inheritance).
18//!
19//! ```
20//! let value = tabnas_xml::parse(r#"<greeting lang="en">Hi <b>world</b></greeting>"#)?;
21//! assert_eq!(
22//!     value.to_string(),
23//!     r#"{"name":"greeting","localName":"greeting","attributes":{"lang":"en"},"children":["Hi ",{"name":"b","localName":"b","attributes":{},"children":["world"]}]}"#
24//! );
25//! # Ok::<(), tabnas_xml::XmlError>(())
26//! ```
27//!
28//! The plugin is layered on the relaxed-JSON grammar of
29//! [`tabnas_jsonic`], as the canonical plugin is layered on
30//! `@tabnas/jsonic`: `use(jsonic)` first, then `use(Xml)`. In the default
31//! pure-XML mode the XML rules replace the JSON value rules; in embed
32//! mode (`embed: true`) they sit beside them so an XML element can appear
33//! wherever a jsonic value can.
34//!
35//! TypeScript is canonical: `ts/src/xml.ts` defines behaviour, option
36//! names and defaults, and `xml-grammar.jsonic` at the repository root
37//! defines the rule chain, embedded below as JSON. The shared fixtures in
38//! `test/spec/*.tsv` are the parity contract across TypeScript, Go and
39//! Rust.
40
41use std::cell::RefCell;
42use std::rc::Rc;
43use std::sync::{Arc, OnceLock};
44
45use indexmap::IndexMap;
46use tabnas::{
47    Context, LexMatcher, Options, Plugin, PluginError, Rule, Tabnas, Token, Value, TIN_CM, TIN_LN,
48    TIN_SP,
49};
50
51mod bom;
52mod entity;
53mod lex;
54mod namespace;
55
56pub use bom::{decode_bom, strip_bom};
57
58/// This crate's version. It MUST equal `ts/package.json` "version": the
59/// release orchestrator rewrites both, and `tests/version_test.rs` fails
60/// the build if they drift. Mirrors `VERSION` in `ts/src/xml.ts` and
61/// `const VERSION` in `go/xml.go`.
62pub const VERSION: &str = "0.7.12";
63
64/// The README's Rust examples run as doctests, so a stale one fails the
65/// gate rather than misleading the reader. Its `toml` and `bash` fences
66/// are skipped; rustdoc runs only the `rust` ones.
67#[cfg(doctest)]
68#[doc = include_str!("../README.md")]
69mod readme_examples {}
70
71/// The error a failed parse produces, re-exported so callers need not
72/// depend on the engine crate directly.
73pub use tabnas::TabnasError as XmlError;
74
75// --- BEGIN EMBEDDED xml-grammar.jsonic ---
76/// The grammar, as the JSON that `xml-grammar.jsonic` at the repository
77/// root parses to. The TypeScript plugin parses that file's text with
78/// jsonic at load time; this crate carries the parsed form so it needs no
79/// jsonic parse of its own to start, and `tests/xml_test.rs` holds the two
80/// to the same value.
81pub const GRAMMAR_TEXT: &str = r##"
82{
83  "rule": {
84    "xml": {
85      "open": [
86        {
87          "s": "#ZZ"
88        },
89        {
90          "s": "#TX",
91          "r": "xml",
92          "a": "@doc-text-open"
93        },
94        {
95          "p": "element",
96          "c": "@no-root-yet"
97        }
98      ],
99      "close": [
100        {
101          "s": "#ZZ",
102          "g": "end"
103        },
104        {
105          "s": "#TX",
106          "r": "xml",
107          "a": "@doc-text-close",
108          "g": "comma"
109        }
110      ]
111    },
112    "element": {
113      "open": [
114        {
115          "s": "#XSC",
116          "a": "@element-selfclose",
117          "u": {
118            "selfclose": 1
119          }
120        },
121        {
122          "s": "#XOP",
123          "p": "content",
124          "a": "@element-open"
125        }
126      ],
127      "close": [
128        {
129          "c": "@element-is-selfclosed"
130        },
131        {
132          "s": "#XCL",
133          "a": "@element-close",
134          "g": "close"
135        }
136      ]
137    },
138    "content": {
139      "open": [
140        {
141          "s": "#XCL",
142          "b": 1
143        },
144        {
145          "p": "child"
146        }
147      ],
148      "close": [
149        {
150          "s": "#XCL",
151          "b": 1,
152          "g": "close"
153        },
154        {
155          "r": "content"
156        }
157      ]
158    },
159    "child": {
160      "open": [
161        {
162          "s": "#TX",
163          "a": "@child-text"
164        },
165        {
166          "s": "#XOP",
167          "b": 1,
168          "p": "element"
169        },
170        {
171          "s": "#XSC",
172          "b": 1,
173          "p": "element"
174        }
175      ]
176    }
177  }
178}"##;
179// --- END EMBEDDED xml-grammar.jsonic ---
180
181/// The name the plugin registers under, and so the namespace of its
182/// plugin options.
183const PLUGIN_NAME: &str = "xml";
184
185// The function references the grammar names, registered on the instance
186// before the document is installed. The two lifecycle hooks are wired by
187// name to their rule and phase when the rule is installed.
188const XML_BC: &str = "@xml-bc";
189const CHILD_BC: &str = "@child-bc";
190const ELEMENT_BC: &str = "@element-bc";
191const NO_ROOT_YET: &str = "@no-root-yet";
192const DOC_TEXT_OPEN: &str = "@doc-text-open";
193const DOC_TEXT_CLOSE: &str = "@doc-text-close";
194const ELEMENT_OPEN: &str = "@element-open";
195const ELEMENT_SELFCLOSE: &str = "@element-selfclose";
196const ELEMENT_CLOSE: &str = "@element-close";
197const CHILD_TEXT: &str = "@child-text";
198const ELEMENT_IS_SELFCLOSED: &str = "@element-is-selfclosed";
199
200/// Plugin options. [`Default`] is the canonical default set: namespaces
201/// resolved, entities decoded, no custom entities, undeclared entities an
202/// error, unbound prefixes accepted, pure-XML mode.
203#[derive(Debug, Clone, PartialEq, Eq)]
204pub struct XmlOptions {
205    /// Resolve namespaces: annotate elements with `prefix`, `localName`
206    /// and `namespace`. Default: true.
207    pub namespaces: bool,
208    /// Decode the five predefined entities and numeric character
209    /// references in character data. Default: true.
210    pub entities: bool,
211    /// Additional named entities beyond the five predefined ones.
212    pub custom_entities: IndexMap<String, String>,
213    /// Enforce XML 1.0 4.1: every named entity reference must resolve to
214    /// a declared entity (predefined, custom, or a DOCTYPE `<!ENTITY>`
215    /// declaration). Default: true. When off, a reference to an unknown
216    /// name is left as it is in the output.
217    pub strict_entities: bool,
218    /// Enforce the Namespaces in XML 1.0 rule that every prefix on an
219    /// element or attribute name be bound by an in-scope `xmlns:prefix`
220    /// declaration. Default: false. XML 1.0 well-formedness and
221    /// Namespaces in XML are separate specifications: `<a><foo:b/></a>`
222    /// is well-formed XML, merely not namespace-well-formed, so an
223    /// unbound prefix is reported only when this is on. Either way the
224    /// element keeps its `prefix` and `localName`; an unbound prefix
225    /// leaves `namespace` unset.
226    pub strict_namespaces: bool,
227    /// Embed mode. When false (the default) the parser is configured for
228    /// pure-XML input: `xml` becomes the start rule, the JSON structural
229    /// tokens are dropped and every non-XML lexer is switched off. When
230    /// true the jsonic grammar stays in place and an alternate is added
231    /// to its `val` rule so a literal element (`<tag>...</tag>` or
232    /// `<tag/>`) appears wherever jsonic expects a value.
233    pub embed: bool,
234}
235
236impl Default for XmlOptions {
237    fn default() -> Self {
238        XmlOptions {
239            namespaces: true,
240            entities: true,
241            custom_entities: IndexMap::new(),
242            strict_entities: true,
243            strict_namespaces: false,
244            embed: false,
245        }
246    }
247}
248
249impl XmlOptions {
250    /// Read an option bag the way `ts/src/xml.ts` reads it: each field on
251    /// its own terms (`namespaces !== false`, `embed === true`, and so
252    /// on), so one field of the wrong type leaves only that field at its
253    /// default. The bag is the JSON shape a fixture's `opts` column
254    /// carries and the shape [`plugin`] receives.
255    pub fn from_value(value: &Value) -> Self {
256        let bag = value.to_json();
257        let field = |name: &str| bag.get(name);
258        let not_false = |name: &str| field(name) != Some(&serde_json::Value::Bool(false));
259        let is_true = |name: &str| field(name) == Some(&serde_json::Value::Bool(true));
260        // Read the replacements from the engine value, not from the JSON
261        // projection: `to_json` spells `undefined`, `NaN` and an infinity
262        // all three `null`, and the canonical coercion tells them apart.
263        let custom_entities = custom_entities(value);
264        XmlOptions {
265            namespaces: not_false("namespaces"),
266            entities: not_false("entities"),
267            custom_entities,
268            strict_entities: not_false("strictEntities"),
269            strict_namespaces: is_true("strictNamespaces"),
270            embed: is_true("embed"),
271        }
272    }
273
274    /// The option bag, with the canonical camel-case keys.
275    pub fn to_value(&self) -> Value {
276        let mut custom = IndexMap::new();
277        for (name, text) in &self.custom_entities {
278            custom.insert(name.clone(), Value::String(text.clone()));
279        }
280        let mut bag = IndexMap::new();
281        bag.insert("namespaces".to_string(), Value::Bool(self.namespaces));
282        bag.insert("entities".to_string(), Value::Bool(self.entities));
283        bag.insert("customEntities".to_string(), Value::object(custom));
284        bag.insert(
285            "strictEntities".to_string(),
286            Value::Bool(self.strict_entities),
287        );
288        bag.insert(
289            "strictNamespaces".to_string(),
290            Value::Bool(self.strict_namespaces),
291        );
292        bag.insert("embed".to_string(), Value::Bool(self.embed));
293        Value::object(bag)
294    }
295}
296
297/// The `customEntities` replacements of a loose option bag.
298///
299/// The canonical plugin hands each replacement straight back from the
300/// `String.prototype.replace` callback in `buildEntityDecoder`, so
301/// JavaScript coerces it with `ToString`: an object becomes
302/// `[object Object]`, an array joins its elements with commas, and a
303/// number spells itself the way `Number::toString` does. [`js_string`]
304/// is that coercion.
305///
306/// `undefined` is the one value the callback never coerces: the guard
307/// there is `undefined !== baseEntities[ref]`, so the name counts as
308/// declared (no `undeclared_entity`) while the reference is left in the
309/// text exactly as written. The replacement text recorded here is that
310/// verbatim reference, which reads back identically. The one input where
311/// the two part company is a name that a DOCTYPE internal subset also
312/// declares: the canonical decoder falls through to the DTD value, while
313/// this map answers first. A `String` replacement cannot express "no
314/// replacement", and [`XmlOptions::custom_entities`] is a map of them.
315fn custom_entities(bag: &Value) -> IndexMap<String, String> {
316    // A bag built by the engine's plugin merge is an `Object`; one handed
317    // in from a parse result may still be the `MapRef` the parse built,
318    // and every other field here reads that shape through `to_json`.
319    let fields = match bag {
320        Value::Object(fields) => &**fields,
321        Value::MapRef(map) => &map.value,
322        _ => return IndexMap::new(),
323    };
324    let entries = match fields.get("customEntities") {
325        Some(Value::Object(entries)) => &**entries,
326        Some(Value::MapRef(map)) => &map.value,
327        _ => return IndexMap::new(),
328    };
329    entries
330        .iter()
331        .map(|(name, replacement)| {
332            let text = match replacement {
333                Value::String(text) => text.clone(),
334                Value::Text(text) => text.string.clone(),
335                Value::Undefined => format!("&{name};"),
336                other => js_string(other),
337            };
338            (name.clone(), text)
339        })
340        .collect()
341}
342
343/// `String(value)` as JavaScript spells it.
344///
345/// Ported from the same helper in the yaml and csv crates. An array
346/// joins its elements with commas, rendering `null` and `undefined` as
347/// nothing at all (`Array.prototype.join`), and any object is the bare
348/// `[object Object]`, since a value parsed out of an option bag carries
349/// no `toString` of its own.
350fn js_string(value: &Value) -> String {
351    match value {
352        Value::Undefined => "undefined".to_string(),
353        Value::Null => "null".to_string(),
354        Value::Bool(flag) => flag.to_string(),
355        Value::Number(number) => js_number_to_string(*number),
356        Value::String(text) => text.clone(),
357        Value::Text(text) => text.string.clone(),
358        Value::Array(items) => items
359            .iter()
360            .map(|item| match item {
361                Value::Undefined | Value::Null => String::new(),
362                other => js_string(other),
363            })
364            .collect::<Vec<_>>()
365            .join(","),
366        Value::ListRef(list) => js_string(&Value::array(list.value.clone())),
367        Value::Object(_) | Value::MapRef(_) => "[object Object]".to_string(),
368    }
369}
370
371/// `String(number)` as JavaScript spells it (ECMA-262 6.1.6.1.20): the
372/// shortest digit string that reads back as the same double, in plain
373/// decimal while the decimal point stays inside `(-6, 21]` and in
374/// exponent form outside it.
375///
376/// Rust's own formatting differs in three ways that reach a replacement
377/// text: it keeps the sign of negative zero, it never switches to
378/// exponent form, and a large integral float prints its exact binary
379/// value rather than its shortest round-tripping digits. Ported from
380/// `js_number_to_string` in the csv and yaml crates.
381fn js_number_to_string(number: f64) -> String {
382    if number.is_nan() {
383        return "NaN".to_string();
384    }
385    // Catches -0.0 as well: JavaScript spells both zeros "0".
386    if number == 0.0 {
387        return "0".to_string();
388    }
389    if number < 0.0 {
390        return format!("-{}", js_number_to_string(-number));
391    }
392    if number.is_infinite() {
393        return "Infinity".to_string();
394    }
395
396    // The specification wants the shortest digit string `s` that round
397    // trips (length `k`), and `n`, the position of the decimal point
398    // relative to it. Rust's `{:e}` yields digits of exactly that length.
399    let shortest = format!("{number:e}");
400    let shortest_k = shortest
401        .split_once('e')
402        .map(|(mantissa, _)| mantissa.chars().filter(char::is_ascii_digit).count())
403        .expect("a finite f64 always formats with an exponent");
404
405    // Re-render to that same length to settle a tie. Where two digit
406    // strings of length `k` are equally close to `number`, the
407    // specification takes the one ending in an even digit; Rust's
408    // shortest form does not, but its exactly-rounded fixed-precision
409    // form does.
410    let exponential = format!("{:.*e}", shortest_k - 1, number);
411    let (mantissa, exponent) = exponential
412        .split_once('e')
413        .expect("a finite f64 always formats with an exponent");
414    // Rounding can leave trailing zeros (and, on a carry, one digit too
415    // many); dropping them keeps `s` shortest, which is what `k` means.
416    let digits = mantissa
417        .chars()
418        .filter(|digit| *digit != '.')
419        .collect::<String>();
420    let digits = digits.trim_end_matches('0');
421    let digits = if digits.is_empty() { "0" } else { digits };
422    let k = digits.len() as i32;
423    let n = exponent
424        .parse::<i32>()
425        .expect("a formatted exponent is an integer")
426        + 1;
427
428    // The four cases of the specification, in its order. The range bounds
429    // are `k <= n <= 21`, `0 < n <= 21` and `-6 < n <= 0`.
430    if (k..=21).contains(&n) {
431        // Integral, with n - k trailing zeros to restore.
432        let mut text = digits.to_string();
433        text.push_str(&"0".repeat((n - k) as usize));
434        text
435    } else if (1..=21).contains(&n) {
436        let point = n as usize;
437        format!("{}.{}", &digits[..point], &digits[point..])
438    } else if (-5..=0).contains(&n) {
439        format!("0.{}{}", "0".repeat(-n as usize), digits)
440    } else {
441        // Exponent form. `n - 1` is never 0 here, so the sign is never "+0".
442        let sign = if n - 1 < 0 { '-' } else { '+' };
443        let power = (n - 1).abs();
444        if k == 1 {
445            format!("{digits}e{sign}{power}")
446        } else {
447            format!("{}.{}e{sign}{power}", &digits[..1], &digits[1..])
448        }
449    }
450}
451
452// ---------------------------------------------------------------------------
453// Node helpers
454// ---------------------------------------------------------------------------
455
456/// Assign a rule's node: the Rust spelling of TypeScript `r.node = v`.
457///
458/// A pushed or replaced rule SHARES its parent's node cell, so writing
459/// through `rule.node.borrow_mut()` would overwrite the parent's node too.
460/// Assigning installs a fresh cell instead; the `content` and `child`
461/// rules an element pushes then share THAT cell, which is what lets them
462/// append to the element's children in place.
463fn set_node(rule: &mut Rule, value: Value) {
464    rule.node = Rc::new(RefCell::new(value));
465}
466
467fn flag(rule: &Rule, name: &str) -> bool {
468    matches!(rule.u.get(name), Some(Value::Bool(true)))
469}
470
471fn token_string(token: Option<&Token>) -> Option<String> {
472    match token.map(|token| &token.val) {
473        Some(Value::String(text)) => Some(text.clone()),
474        _ => None,
475    }
476}
477
478/// The element an open or self-closing tag token describes: `name`,
479/// `localName`, `attributes` (with the DOCTYPE defaults filled in) and an
480/// empty `children` list, in that order.
481fn element_of(token: Option<&Token>, context: &Context) -> Value {
482    let (name, attributes) = match token.map(|token| &token.val) {
483        Some(Value::Object(tag)) => {
484            let name = match tag.get("name") {
485                Some(Value::String(name)) => name.clone(),
486                _ => String::new(),
487            };
488            let attributes = match tag.get("attributes") {
489                Some(Value::Object(attributes)) => (**attributes).clone(),
490                _ => IndexMap::new(),
491            };
492            (name, attributes)
493        }
494        _ => (String::new(), IndexMap::new()),
495    };
496    let attributes = apply_attr_defaults(attributes, &name, context);
497    let mut element = IndexMap::new();
498    element.insert("name".to_string(), Value::String(name.clone()));
499    element.insert("localName".to_string(), Value::String(name));
500    element.insert("attributes".to_string(), Value::object(attributes));
501    element.insert("children".to_string(), Value::array(Vec::new()));
502    Value::object(element)
503}
504
505/// Fill in DOCTYPE-supplied default attribute values (`<!ATTLIST element
506/// attr ... "default">`) for any attribute the element does not carry.
507fn apply_attr_defaults(
508    mut attributes: IndexMap<String, Value>,
509    element: &str,
510    context: &Context,
511) -> IndexMap<String, Value> {
512    if let Some(defaults) = lex::dtd_attr_defaults(context, element) {
513        for (name, value) in defaults {
514            if !attributes.contains_key(&name) {
515                attributes.insert(name, value);
516            }
517        }
518    }
519    attributes
520}
521
522/// Append to the element's `children`.
523fn push_child(node: &mut Value, child: Value) {
524    if let Some(children) = node
525        .as_object_mut()
526        .and_then(|element| element.get_mut("children"))
527        .and_then(Value::as_array_mut)
528    {
529        children.push(child);
530    }
531}
532
533/// XML 1.0 2.1 [1] `document ::= prolog element Misc*`: at document level
534/// only Misc (comments, PIs, white space) may appear, so character data
535/// before or after the root element is not well-formed. Comments, PIs and
536/// the DOCTYPE arrive as `#XIG` and are ignored by the token set, so the
537/// only document-level token to police is `#TX`.
538///
539/// The token policed here is one of the few this plugin does not mint:
540/// outside the root element the matcher claims nothing, so the engine's
541/// own text matcher cuts it, and its column has not been through
542/// [`lex::discount_bom`] yet.
543fn check_doc_text(token: Option<&Token>, context: &Context) -> Option<Token> {
544    let token = token?;
545    let Value::String(text) = &token.val else {
546        return None;
547    };
548    if text
549        .bytes()
550        .all(|byte| matches!(byte, b' ' | b'\t' | b'\n' | b'\r'))
551    {
552        return None;
553    }
554    let mut bad = token.clone();
555    lex::discount_bom(context, &mut bad.site);
556    bad.bad("text_at_top_level");
557    Some(bad)
558}
559
560// ---------------------------------------------------------------------------
561// The plugin
562// ---------------------------------------------------------------------------
563
564/// Install the XML grammar on `parser`, which should already carry the
565/// jsonic grammar (as [`make`] arranges): the port of the `Xml` plugin
566/// function.
567///
568/// In pure mode the parser is reconfigured for XML alone: `xml` becomes
569/// the start rule, the JSON structural tokens and every non-XML lexer are
570/// switched off, and jsonic's value rules are removed. In embed mode the
571/// jsonic grammar stays and XML elements become values. Installation is
572/// idempotent: an instance that already carries the `xml` rule is left
573/// alone.
574///
575/// ```
576/// let mut parser = tabnas_jsonic::make();
577/// tabnas_xml::xml(&mut parser, &tabnas_xml::XmlOptions::default())?;
578/// assert_eq!(
579///     parser.parse("<a x='1'/>")?.to_string(),
580///     r#"{"name":"a","localName":"a","attributes":{"x":"1"},"children":[]}"#
581/// );
582/// # Ok::<(), Box<dyn std::error::Error>>(())
583/// ```
584pub fn xml(parser: &mut Tabnas, options: &XmlOptions) -> Result<(), PluginError> {
585    if parser.rules.contains_key("xml") {
586        return Ok(());
587    }
588    let embed = options.embed;
589    let namespaces = options.namespaces;
590    let strict_namespaces = options.strict_namespaces;
591
592    // Reserve the XML tokens so they have stable identities before the
593    // grammar references them; the matcher closes over them.
594    let tokens = lex::Tokens {
595        xig: parser.token("#XIG"),
596        xop: parser.token("#XOP"),
597        xcl: parser.token("#XCL"),
598        xsc: parser.token("#XSC"),
599    };
600    let state = Arc::new(lex::MatcherState {
601        decoder: entity::EntityDecoder::new(&options.custom_entities),
602        entities: options.entities,
603        strict: options.strict_entities,
604        tokens,
605    });
606    let matcher = lex::matcher(state);
607
608    parser.set_options(|o: &mut Options| {
609        // The custom matcher runs first, ahead of every engine matcher.
610        o.lex.matchers.insert(
611            "xmltag".to_string(),
612            LexMatcher {
613                name: "xmltag".to_string(),
614                order: 100_000.0,
615                matcher: None,
616                imperative: Some(matcher),
617                factory: None,
618            },
619        );
620        o.lex.empty_result = Value::Undefined;
621        // Terminate jsonic text at `<` so a tag start is never absorbed
622        // into a text run.
623        o.ender = vec!["<".to_string()];
624
625        if !embed {
626            // Pure XML mode: the jsonic value grammar is unreachable and
627            // every lexer other than the tag matcher is quiescent. No
628            // `text.modify` hook: while the root element is open the tag
629            // matcher emits the text tokens itself, and the engine's text
630            // matcher only sees white space before and after the root.
631            o.rule.start = "xml".to_string();
632            o.rule.exclude = "jsonic,imp".to_string();
633            for name in ["#OB", "#CB", "#OS", "#CS", "#CL", "#CA"] {
634                o.fixed.tokens.shift_remove(name);
635            }
636            o.number.lex = false;
637            o.value.lex = false;
638            o.string.lex = false;
639            o.comment.lex = false;
640            o.space.lex = false;
641            o.line.lex = false;
642            // XML 1.0 2.1: a well-formed document has exactly ONE document
643            // element. Input that parses to no value at all (a prolog on
644            // its own, a lone comment, white space) satisfies every other
645            // rule and then yields nothing, which a caller cannot tell
646            // from a successful parse of nothing. It is the
647            // well-formedness error it is. Both spellings of "no value"
648            // are listed: which one a no-value parse lands on depends on
649            // whether the start rule ran at all.
650            o.result.fail = vec![Value::Undefined, Value::Null];
651            // ...and the same rule makes empty input ill-formed. The
652            // engine short-circuits `""` before the rule loop, so
653            // `result.fail` never sees it; `lex.empty` governs that path.
654            o.lex.empty = false;
655        }
656
657        // Drop `#XIG` (comments, PIs, DOCTYPE) with the default ignored
658        // tokens. In pure mode the space, line and comment tokens are
659        // never produced, but listing them is harmless.
660        o.token_set.insert(
661            "IGNORE".to_string(),
662            vec![TIN_SP, TIN_LN, TIN_CM, tokens.xig],
663        );
664
665        // Error templates and hints, in both modes. A template
666        // interpolates `{key}` against the failing token's details.
667        for (code, message) in ERROR_MESSAGES {
668            o.error.insert((*code).to_string(), (*message).to_string());
669        }
670        for (code, hint) in ERROR_HINTS {
671            o.hint.insert((*code).to_string(), (*hint).to_string());
672        }
673    })?;
674
675    register_refs(parser, namespaces, strict_namespaces, embed);
676
677    parser
678        .grammar_json(GRAMMAR_TEXT)
679        .map_err(|error| PluginError(format!("xml: apply grammar: {error}")))?;
680
681    if embed {
682        // Splice XML literals into the jsonic `val` rule: on `#XOP` or
683        // `#XSC`, push `element`, backtracking by one so `element.open`
684        // reads the same token and dispatches. A bare alternate list is
685        // prepended, as the canonical `rs.open([...])` prepends.
686        let splice = serde_json::json!({
687            "rule": {
688                "val": {
689                    "open": [
690                        { "s": "#XOP", "b": 1, "p": "element", "g": "xml" },
691                        { "s": "#XSC", "b": 1, "p": "element", "g": "xml" },
692                    ],
693                },
694            },
695        });
696        let splice = tabnas::GrammarSpec::from_value(splice)
697            .map_err(|error| PluginError(format!("xml: embed grammar: {error}")))?;
698        parser
699            .grammar(&splice)
700            .map_err(|error| PluginError(format!("xml: embed grammar: {error}")))?;
701    } else {
702        // Pure XML mode: the `xml` start rule reaches only the XML rules,
703        // so jsonic's value rules are dead. Remove them, so the parser
704        // (and a railroad diagram of it) carries only the rules XML uses.
705        for name in ["val", "map", "list", "pair", "elem"] {
706            parser.remove_rule(name);
707        }
708    }
709
710    // The nesting limit is the lexer's (see `lex::DEPTH_LIMIT`), not a
711    // budget: a caller's `parse_budget` replaces the budget in place, and
712    // would take a limit kept there with it.
713    Ok(())
714}
715
716/// Register every function reference the grammar names.
717fn register_refs(parser: &mut Tabnas, namespaces: bool, strict_namespaces: bool, embed: bool) {
718    // The root element lands on the `xml` rule's child; copy it to the
719    // document node, mark the root as seen so `@no-root-yet` refuses a
720    // second one, and resolve namespaces over the finished tree.
721    parser.state_action_with_next_ref(XML_BC, move |rule, context, _next, _out| {
722        if rule.child_node.is_undefined() {
723            return Ok(None);
724        }
725        let mut root = rule.child_node.clone();
726        context.u.insert("rootSeen".to_string(), Value::Bool(true));
727        if namespaces {
728            if let Err(code) = namespace::resolve_namespaces(&mut root, strict_namespaces) {
729                // The canonical writes `ctx.t0.bad(nsErr)` here. Namespace
730                // resolution runs at DOCUMENT CLOSE, where no token is
731                // current, so the canonical's `t0` is the no-token
732                // sentinel, and its report lands at the start of the
733                // source (row 1, column 1). Marking the same sentinel
734                // keeps the failure inside the engine's error machinery,
735                // which is what renders the template registered for
736                // `code`. An `ActionError` here would bypass that and
737                // hand the caller a literal stand-in message instead.
738                let mut token = context.t0().cloned().unwrap_or_else(Token::no_token);
739                token.bad(code);
740                return Ok(Some(token));
741            }
742        }
743        // The start rule's cell IS the document node, so it is written
744        // in place; `root.node = r.child.node` in the canonical grammar.
745        *rule.node.borrow_mut() = root;
746        Ok(None)
747    });
748
749    // Only let `xml` push an `element` while the document has produced
750    // no root (XML 1.0 2.1).
751    parser.alt_condition(NO_ROOT_YET, |_rule, context| {
752        !matches!(context.u.get("rootSeen"), Some(Value::Bool(true)))
753    });
754
755    parser.action_with_match_ref(DOC_TEXT_OPEN, |rule, context, _matched| {
756        Ok(check_doc_text(rule.o0(), context))
757    });
758    parser.action_with_match_ref(DOC_TEXT_CLOSE, |rule, context, _matched| {
759        Ok(check_doc_text(rule.c0(), context))
760    });
761
762    parser.action_with_context(ELEMENT_OPEN, |rule, context| {
763        let element = element_of(rule.o0(), context);
764        set_node(rule, element);
765        Ok(())
766    });
767    parser.action_with_context(ELEMENT_SELFCLOSE, |rule, context| {
768        let element = element_of(rule.o0(), context);
769        set_node(rule, element);
770        Ok(())
771    });
772
773    // The close tag must name the open tag. The offending close tag
774    // itself is marked (not the lookahead token) so the caret lands on
775    // `</b>`, and the two names ride on the token as details, which is
776    // where the `{openname}` / `{closename}` placeholders resolve from.
777    parser.action_with_match_ref(ELEMENT_CLOSE, |rule, _context, _matched| {
778        let open_name = match &*rule.node.borrow() {
779            Value::Object(element) => match element.get("name") {
780                Some(Value::String(name)) => name.clone(),
781                _ => String::new(),
782            },
783            _ => String::new(),
784        };
785        let close_name = token_string(rule.c0()).unwrap_or_default();
786        if open_name == close_name {
787            return Ok(None);
788        }
789        let Some(mut token) = rule.c0().cloned() else {
790            return Ok(None);
791        };
792        token.bad_with_details(
793            "xml_mismatched_tag",
794            [
795                ("openname".to_string(), Value::String(open_name)),
796                ("closename".to_string(), Value::String(close_name)),
797            ],
798        );
799        Ok(Some(token))
800    });
801
802    parser.action_with_context(CHILD_TEXT, |rule, _context| {
803        let text = rule
804            .o0()
805            .map_or(Value::Undefined, |token| token.val.clone());
806        push_child(&mut rule.node.borrow_mut(), text);
807        rule.u_mut().insert("done".to_string(), Value::Bool(true));
808        Ok(())
809    });
810
811    parser.state_action_ref(CHILD_BC, |rule, _context| {
812        if flag(rule, "done") || rule.child_node.is_undefined() {
813            return Ok(());
814        }
815        let child = rule.child_node.clone();
816        push_child(&mut rule.node.borrow_mut(), child);
817        Ok(())
818    });
819
820    parser.alt_condition(
821        ELEMENT_IS_SELFCLOSED,
822        |rule, _context| matches!(rule.u.get("selfclose"), Some(Value::Number(n)) if *n == 1.0),
823    );
824
825    // In embed mode the top-level wrapper is jsonic's `val` rule, so the
826    // `@xml-bc` hook that resolves namespaces over the document never
827    // runs. Resolve them instead when an element closes directly under a
828    // `val`, once its whole subtree is in place.
829    if embed && namespaces {
830        parser.state_action_ref(ELEMENT_BC, move |rule, _context| {
831            let under_val = rule
832                .parent_rule
833                .as_ref()
834                .is_some_and(|parent| parent.name.as_str() == "val");
835            if !under_val || !matches!(&*rule.node.borrow(), Value::Object(_)) {
836                return Ok(());
837            }
838            let mut element = rule.node.borrow().clone();
839            // The outcome is deliberately not an error here, as in the
840            // canonical plugin: a fragment inside a jsonic document is
841            // annotated as far as it can be.
842            let _ = namespace::resolve_namespaces(&mut element, strict_namespaces);
843            *rule.node.borrow_mut() = element;
844            Ok(())
845        });
846    }
847}
848
849/// The plugin form of [`xml`], for [`Tabnas::use_plugin`]. Options are
850/// read from the plugin option bag with [`XmlOptions::from_value`];
851/// installed this way the grammar is re-applied to derived instances, as
852/// every native plugin is.
853///
854/// ```
855/// let mut parser = tabnas_jsonic::make();
856/// parser.use_plugin(tabnas_xml::plugin(), None)?;
857/// assert_eq!(
858///     parser.parse("<a>&amp;</a>")?.to_string(),
859///     r#"{"name":"a","localName":"a","attributes":{},"children":["&"]}"#
860/// );
861/// # Ok::<(), Box<dyn std::error::Error>>(())
862/// ```
863pub fn plugin() -> Plugin {
864    Plugin::new(PLUGIN_NAME, |parser, options| {
865        xml(parser, &XmlOptions::from_value(options))
866    })
867    .with_defaults(XmlOptions::default().to_value())
868}
869
870/// Build an XML parser with caller options: the jsonic grammar, then this
871/// plugin, the `new Tabnas().use(jsonic).use(Xml, options)` of the
872/// canonical plugin and the `jsonic.Make()` plus `UseDefaults` of Go.
873///
874/// Infallible by design: the grammar documents are fixed literals, so a
875/// failure here is a bug in this crate rather than anything a caller did.
876///
877/// ```
878/// let parser = tabnas_xml::make_with(&tabnas_xml::XmlOptions {
879///     strict_entities: false,
880///     ..Default::default()
881/// });
882/// assert_eq!(
883///     parser.parse("<a>&nope;</a>")?.to_string(),
884///     r#"{"name":"a","localName":"a","attributes":{},"children":["&nope;"]}"#
885/// );
886/// # Ok::<(), tabnas_xml::XmlError>(())
887/// ```
888pub fn make_with(options: &XmlOptions) -> Tabnas {
889    let mut parser = tabnas_jsonic::make();
890    parser
891        .use_plugin(plugin(), Some(options.to_value()))
892        .expect("the xml grammar documents are fixed and valid");
893    parser
894}
895
896/// Build an XML parser with the default options.
897///
898/// Reuse the result: building the grammar dominates a parse.
899///
900/// ```
901/// let parser = tabnas_xml::make();
902/// assert_eq!(
903///     parser.parse("<a><b/></a>")?.to_string(),
904///     r#"{"name":"a","localName":"a","attributes":{},"children":[{"name":"b","localName":"b","attributes":{},"children":[]}]}"#
905/// );
906/// assert_eq!(parser.parse("<a></b>").unwrap_err().code, "xml_mismatched_tag");
907/// # Ok::<(), tabnas_xml::XmlError>(())
908/// ```
909pub fn make() -> Tabnas {
910    make_with(&XmlOptions::default())
911}
912
913/// Parse an XML document with the shared default parser.
914///
915/// The engine is built once, on first use, and reused after that; reuse
916/// is safe because [`Tabnas::parse`] takes `&self` and builds a fresh
917/// parse context per call, and `Tabnas` is `Send + Sync`. Use [`make`] or
918/// [`make_with`] when the parser needs configuring.
919///
920/// ```
921/// let value = tabnas_xml::parse("<a>Tom &amp; Jerry</a>")?;
922/// assert_eq!(
923///     value.to_string(),
924///     r#"{"name":"a","localName":"a","attributes":{},"children":["Tom & Jerry"]}"#
925/// );
926/// assert_eq!(tabnas_xml::parse("<a/>junk").unwrap_err().code, "text_at_top_level");
927/// # Ok::<(), tabnas_xml::XmlError>(())
928/// ```
929pub fn parse(src: &str) -> Result<Value, XmlError> {
930    static DEFAULT: OnceLock<Tabnas> = OnceLock::new();
931    DEFAULT.get_or_init(make).parse(src)
932}
933
934/// One optional alchemy translation source and its explicit entry point.
935#[derive(Clone, Copy, Debug, Eq, PartialEq)]
936pub struct TranslationPart {
937    /// The definition a host calls after linking the source.
938    pub entry: &'static str,
939    /// The source text, or `None` for an entry supplied by alchemy.
940    pub source: Option<&'static str>,
941}
942
943/// The package-local structural translation interface.
944#[derive(Clone, Copy, Debug, Eq, PartialEq)]
945pub struct TranslationParts {
946    /// The complete `tabnas.plugin.json` text.
947    pub manifest: &'static str,
948    /// An optional lift from the grammar's events to its first read shape.
949    pub lift: Option<TranslationPart>,
950    /// An optional render from the write shape to text.
951    pub render: Option<TranslationPart>,
952}
953
954const TRANSLATION: TranslationParts = TranslationParts {
955    manifest: include_str!("../translate/manifest.json"),
956    lift: None,
957    render: Some(TranslationPart {
958        entry: "xml-render",
959        source: Some(include_str!("../translate/render.alc")),
960    }),
961};
962
963/// Return XML's immutable translation parts.
964#[must_use]
965pub const fn translate() -> Option<TranslationParts> {
966    Some(TRANSLATION)
967}
968
969/// The plugin's manifest, `tabnas.plugin.json`, as the repository carries
970/// it. Its `translate` object is what a host that translates reads: the
971/// shape XML is read as and written from (`tree`), the file that holds
972/// the render, and the sentences that say what the render does not keep
973/// and which trees it writes. The crate embeds its own copy,
974/// `translate/manifest.json`, since a packaged crate holds nothing
975/// outside `rs/`; `tests/translate_test.rs` holds the copy to the file.
976///
977/// ```
978/// assert!(tabnas_xml::manifest_text().contains("\"translate\""));
979/// ```
980pub fn manifest_text() -> &'static str {
981    TRANSLATION.manifest
982}
983
984/// XML's render, `alchemy/render.alc`, the file the manifest's
985/// `translate.render` names: a library of alchemy definitions, with no
986/// `export`, whose entry point `xml-render` writes an element tree's
987/// events, the shape this reader builds, as one XML document, and
988/// refuses any other tree. A host links it with its own program. The
989/// crate embeds its own copy, `translate/render.alc`, held to the file
990/// as the manifest's is.
991///
992/// ```
993/// assert!(tabnas_xml::render_text().contains("def xml-render [input]"));
994/// ```
995pub fn render_text() -> &'static str {
996    match TRANSLATION.render {
997        Some(part) => part.source.unwrap_or_default(),
998        None => "",
999    }
1000}
1001
1002/// The error templates, interpolated against the failing token's
1003/// details. Kept identical to `ts/src/xml.ts`. `$name` is not a
1004/// placeholder syntax the engine understands, so it is never used here.
1005const ERROR_MESSAGES: &[(&str, &str)] = &[
1006    (
1007        "xml_mismatched_tag",
1008        "closing tag </{closename}> does not match opening tag <{openname}>",
1009    ),
1010    ("xml_invalid_tag", "invalid tag: {src}"),
1011    ("unterminated_comment", "unterminated comment: {src}"),
1012    ("unterminated_cdata", "unterminated CDATA section: {src}"),
1013    (
1014        "unterminated_pi",
1015        "unterminated processing instruction: {src}",
1016    ),
1017    (
1018        "unterminated_doctype",
1019        "unterminated DOCTYPE declaration: {src}",
1020    ),
1021    ("comment_double_dash", "comment body cannot contain \"--\""),
1022    (
1023        "cdata_terminator_in_text",
1024        "character data cannot contain \"]]>\"",
1025    ),
1026    (
1027        "pi_target_invalid",
1028        "processing instruction target is missing or invalid",
1029    ),
1030    (
1031        "lt_in_attr_value",
1032        "\"<\" is not allowed in an attribute value",
1033    ),
1034    (
1035        "bad_entity_ref",
1036        "malformed entity reference (need &name; or &#NNN; or &#xHHH;)",
1037    ),
1038    ("duplicate_attribute", "duplicate attribute name in tag"),
1039    ("invalid_xml_char", "illegal control character in XML data"),
1040    (
1041        "reserved_namespace",
1042        "invalid use of a reserved namespace prefix or URI",
1043    ),
1044    (
1045        "unbound_prefix",
1046        "element or attribute uses an undeclared namespace prefix",
1047    ),
1048    (
1049        "invalid_namespace_uri",
1050        "namespace name cannot contain white space",
1051    ),
1052    ("undeclared_entity", "reference to undeclared entity"),
1053    (
1054        "unparsed_entity_ref",
1055        "reference to an unparsed (NDATA) entity",
1056    ),
1057    (
1058        "external_entity_in_attr",
1059        "attribute value cannot reference an external entity",
1060    ),
1061    (
1062        "text_at_top_level",
1063        "character data is not allowed outside the root element",
1064    ),
1065];
1066
1067/// The hint for each error code. Kept identical to `ts/src/xml.ts`.
1068const ERROR_HINTS: &[(&str, &str)] = &[
1069    (
1070        "xml_mismatched_tag",
1071        "Each opening tag must be paired with a matching closing tag.\nExpected </{openname}> but found </{closename}>.",
1072    ),
1073    ("xml_invalid_tag", "The tag syntax is not valid XML."),
1074    (
1075        "unterminated_comment",
1076        "The comment starting at this position has no closing \"-->\".",
1077    ),
1078    (
1079        "unterminated_cdata",
1080        "The CDATA section starting at this position has no closing \"]]>\".",
1081    ),
1082    (
1083        "unterminated_pi",
1084        "The processing instruction starting at this position has no closing \"?>\".",
1085    ),
1086    (
1087        "unterminated_doctype",
1088        "The DOCTYPE declaration starting at this position has no closing \">\".",
1089    ),
1090    (
1091        "comment_double_dash",
1092        "XML 1.0 disallows \"--\" inside a comment body.",
1093    ),
1094    (
1095        "cdata_terminator_in_text",
1096        "The literal \"]]>\" must only appear as the end of a CDATA section.",
1097    ),
1098    (
1099        "pi_target_invalid",
1100        "A processing instruction must start with a Name; the XML declaration <?xml...?> is the special case.",
1101    ),
1102    (
1103        "lt_in_attr_value",
1104        "Use the entity reference &lt; to include \"<\" in an attribute value.",
1105    ),
1106    (
1107        "bad_entity_ref",
1108        "Replace literal \"&\" with &amp;, or terminate the entity reference with \";\".",
1109    ),
1110    (
1111        "duplicate_attribute",
1112        "Each attribute name in an open tag must be unique.",
1113    ),
1114    (
1115        "invalid_xml_char",
1116        "Only #x9, #xA, #xD and code points >= #x20 are legal XML characters.",
1117    ),
1118    (
1119        "reserved_namespace",
1120        "The \"xml\" prefix is fixed to http://www.w3.org/XML/1998/namespace; the \"xmlns\" prefix cannot be redeclared, and neither URI may be bound to any other prefix or as the default namespace.",
1121    ),
1122    (
1123        "unbound_prefix",
1124        "Declare the prefix with xmlns:prefix=\"...\" on this element or one of its ancestors.",
1125    ),
1126    (
1127        "invalid_namespace_uri",
1128        "A namespace name is a URI reference, and a URI reference cannot contain white space; note that a line break inside the declaration becomes a space under attribute-value normalisation.",
1129    ),
1130    (
1131        "undeclared_entity",
1132        "Declare the entity in the DOCTYPE internal subset, add it to the customEntities option, or set strictEntities: false to allow unresolved references through.",
1133    ),
1134    (
1135        "unparsed_entity_ref",
1136        "XML 1.0 \u{a7}4.1 (WFC: Parsed Entity) \u{2014} an entity declared with an NDATA notation is unparsed, and its name may only appear as the value of an ENTITY-typed attribute, never in an entity reference.",
1137    ),
1138    (
1139        "external_entity_in_attr",
1140        "XML 1.0 \u{a7}4.1 (WFC: No External Entity References) \u{2014} an attribute value may not reference an entity whose replacement text lives in an external file.",
1141    ),
1142    (
1143        "text_at_top_level",
1144        "An XML document is \"prolog element Misc*\": outside the single root element only comments, processing instructions and white space may appear.",
1145    ),
1146];