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