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