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.18";
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) an
572/// open or self-closing tag token carries.
573fn tag_of(token: Option<&Token>, context: &Context) -> (String, IndexMap<String, Value>) {
574    let (name, attributes) = match token.map(|token| &token.val) {
575        Some(Value::Object(tag)) => {
576            let name = match tag.get("name") {
577                Some(Value::String(name)) => name.clone(),
578                _ => String::new(),
579            };
580            let attributes = match tag.get("attributes") {
581                Some(Value::Object(attributes)) => (**attributes).clone(),
582                _ => IndexMap::new(),
583            };
584            (name, attributes)
585        }
586        _ => (String::new(), IndexMap::new()),
587    };
588    let attributes = apply_attr_defaults(attributes, &name, context);
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(), context);
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/// Fill in DOCTYPE-supplied default attribute values (`<!ATTLIST element
666/// attr ... "default">`) for any attribute the element does not carry.
667fn apply_attr_defaults(
668    mut attributes: IndexMap<String, Value>,
669    element: &str,
670    context: &Context,
671) -> IndexMap<String, Value> {
672    if let Some(defaults) = lex::dtd_attr_defaults(context, element) {
673        for (name, value) in defaults {
674            if !attributes.contains_key(&name) {
675                attributes.insert(name, value);
676            }
677        }
678    }
679    attributes
680}
681
682/// XML 1.0 2.1 [1] `document ::= prolog element Misc*`: at document level
683/// only Misc (comments, PIs, white space) may appear, so character data
684/// before or after the root element is not well-formed. Comments, PIs and
685/// the DOCTYPE arrive as `#XIG` and are ignored by the token set, so the
686/// only document-level token to police is `#TX`.
687///
688/// The token policed here is one of the few this plugin does not mint:
689/// outside the root element the matcher claims nothing, so the engine's
690/// own text matcher cuts it, and its column has not been through
691/// [`lex::discount_bom`] yet.
692fn check_doc_text(token: Option<&Token>, context: &Context) -> Option<Token> {
693    let token = token?;
694    let Value::String(text) = &token.val else {
695        return None;
696    };
697    if text
698        .bytes()
699        .all(|byte| matches!(byte, b' ' | b'\t' | b'\n' | b'\r'))
700    {
701        return None;
702    }
703    let mut bad = token.clone();
704    lex::discount_bom(context, &mut bad.site);
705    bad.bad("text_at_top_level");
706    Some(bad)
707}
708
709// ---------------------------------------------------------------------------
710// The plugin
711// ---------------------------------------------------------------------------
712
713/// Install the XML grammar on `parser`: the port of the `Xml` plugin
714/// function.
715///
716/// In pure mode the parser is reconfigured for XML alone: `xml` becomes
717/// the start rule, the JSON structural tokens and every non-XML lexer are
718/// switched off, and any jsonic value rules are removed, so the parser
719/// carries the six XML rules whether it started as the bare engine (as
720/// [`make`] arranges) or as a jsonic parser. In embed mode, on a jsonic
721/// parser, the jsonic grammar stays and XML elements become values.
722/// Installation is idempotent: an instance that already carries the
723/// `xml` rule is left alone.
724///
725/// # Errors
726///
727/// Embed mode on a parser whose `val` rule is not jsonic's, the bare
728/// engine and the strict-JSON parsers among them, is refused with a
729/// [`PluginError`] that starts `xml: embed mode needs a jsonic host`, and
730/// nothing is installed.
731///
732/// ```
733/// let mut parser = tabnas::Tabnas::new();
734/// tabnas_xml::xml(&mut parser, &tabnas_xml::XmlOptions::default())?;
735/// assert_eq!(
736///     parser.parse("<a x='1'/>")?.to_string(),
737///     r#"{"name":"a","localName":"a","attributes":{"x":"1"},"children":[]}"#
738/// );
739/// # Ok::<(), Box<dyn std::error::Error>>(())
740/// ```
741pub fn xml(parser: &mut Tabnas, options: &XmlOptions) -> Result<(), PluginError> {
742    if parser.rules.contains_key("xml") {
743        return Ok(());
744    }
745    if options.embed && !jsonic_host(parser) {
746        return Err(PluginError(EMBED_NEEDS_JSONIC.to_string()));
747    }
748    let embed = options.embed;
749    let namespaces = options.namespaces;
750    let strict_namespaces = options.strict_namespaces;
751
752    // Reserve the XML tokens so they have stable identities before the
753    // grammar references them; the matcher closes over them.
754    let tokens = lex::Tokens {
755        xig: parser.token("#XIG"),
756        xop: parser.token("#XOP"),
757        xcl: parser.token("#XCL"),
758        xsc: parser.token("#XSC"),
759    };
760    let state = Arc::new(lex::MatcherState {
761        decoder: entity::EntityDecoder::new(&options.custom_entities),
762        entities: options.entities,
763        strict: options.strict_entities,
764        tokens,
765    });
766    let matcher = lex::matcher(state);
767
768    parser.set_options(|o: &mut Options| {
769        // The custom matcher runs first, ahead of every engine matcher.
770        o.lex.matchers.insert(
771            "xmltag".to_string(),
772            LexMatcher {
773                name: "xmltag".to_string(),
774                order: 100_000.0,
775                matcher: None,
776                imperative: Some(matcher),
777                factory: None,
778            },
779        );
780        o.lex.empty_result = Value::Undefined;
781        // Terminate jsonic text at `<` so a tag start is never absorbed
782        // into a text run.
783        o.ender = vec!["<".to_string()];
784
785        if !embed {
786            // Pure XML mode: the jsonic value grammar is unreachable and
787            // every lexer other than the tag matcher is quiescent. No
788            // `text.modify` hook: while the root element is open the tag
789            // matcher emits the text tokens itself, and the engine's text
790            // matcher only sees white space before and after the root.
791            o.rule.start = "xml".to_string();
792            o.rule.exclude = "jsonic,imp".to_string();
793            for name in ["#OB", "#CB", "#OS", "#CS", "#CL", "#CA"] {
794                o.fixed.tokens.shift_remove(name);
795            }
796            o.number.lex = false;
797            o.value.lex = false;
798            o.string.lex = false;
799            o.comment.lex = false;
800            o.space.lex = false;
801            o.line.lex = false;
802            // XML 1.0 2.1: a well-formed document has exactly ONE document
803            // element. Input that parses to no value at all (a prolog on
804            // its own, a lone comment, white space) satisfies every other
805            // rule and then yields nothing, which a caller cannot tell
806            // from a successful parse of nothing. It is the
807            // well-formedness error it is. Both spellings of "no value"
808            // are listed: which one a no-value parse lands on depends on
809            // whether the start rule ran at all.
810            o.result.fail = vec![Value::Undefined, Value::Null];
811            // ...and the same rule makes empty input ill-formed. The
812            // engine short-circuits `""` before the rule loop, so
813            // `result.fail` never sees it; `lex.empty` governs that path.
814            o.lex.empty = false;
815        }
816
817        // Drop `#XIG` (comments, PIs, DOCTYPE) with the default ignored
818        // tokens. In pure mode the space, line and comment tokens are
819        // never produced, but listing them is harmless.
820        o.token_set.insert(
821            "IGNORE".to_string(),
822            vec![TIN_SP, TIN_LN, TIN_CM, tokens.xig],
823        );
824
825        // Error templates and hints, in both modes. A template
826        // interpolates `{key}` against the failing token's details.
827        for (code, message) in ERROR_MESSAGES {
828            o.error.insert((*code).to_string(), (*message).to_string());
829        }
830        for (code, hint) in ERROR_HINTS {
831            o.hint.insert((*code).to_string(), (*hint).to_string());
832        }
833    })?;
834
835    register_refs(parser, namespaces, strict_namespaces);
836
837    parser
838        .grammar_json(GRAMMAR_TEXT)
839        .map_err(|error| PluginError(format!("xml: apply grammar: {error}")))?;
840
841    if embed {
842        // Splice XML literals into the jsonic `val` rule: on `#XOP` or
843        // `#XSC`, push `element`, backtracking by one so `element.open`
844        // reads the same token and dispatches. A bare alternate list is
845        // prepended, as the canonical `rs.open([...])` prepends.
846        let splice = serde_json::json!({
847            "rule": {
848                "val": {
849                    "open": [
850                        { "s": "#XOP", "b": 1, "p": "element", "g": "xml" },
851                        { "s": "#XSC", "b": 1, "p": "element", "g": "xml" },
852                    ],
853                },
854            },
855        });
856        let splice = tabnas::GrammarSpec::from_value(splice)
857            .map_err(|error| PluginError(format!("xml: embed grammar: {error}")))?;
858        parser
859            .grammar(&splice)
860            .map_err(|error| PluginError(format!("xml: embed grammar: {error}")))?;
861    } else {
862        // Pure XML mode: the `xml` start rule reaches only the XML rules,
863        // so jsonic's value rules are dead. Remove them, so the parser
864        // (and a railroad diagram of it) carries only the rules XML uses.
865        for name in ["val", "map", "list", "pair", "elem"] {
866            parser.remove_rule(name);
867        }
868    }
869
870    // The nesting limit is the lexer's (see `lex::DEPTH_LIMIT`), not a
871    // budget: a caller's `parse_budget` replaces the budget in place, and
872    // would take a limit kept there with it.
873    Ok(())
874}
875
876/// Register every function reference the grammar names.
877fn register_refs(parser: &mut Tabnas, namespaces: bool, strict_namespaces: bool) {
878    // The root element is done, on the `xml` rule's child: it is the
879    // document's value from here, on the start rule's cell, where a plugin
880    // layered on this one (feed) reads it and replaces it with what it
881    // makes of the tree. Mark the root as seen so `@no-root-yet` refuses a
882    // second one, and fail the document with the first namespace violation
883    // its elements met.
884    parser.state_action_with_next_ref(XML_BC, move |rule, context, _next, _out| {
885        if rule.child_node.is_undefined() {
886            return Ok(None);
887        }
888        // The start rule's cell IS the document node, so it is written in
889        // place; `root.node = r.child.node` in the canonical grammar, which
890        // writes it before it reports a namespace violation, as this does.
891        *rule.node.borrow_mut() = rule.child_node.clone();
892        context.u.insert("rootSeen".to_string(), Value::Bool(true));
893        if namespaces {
894            if let Some(Value::String(code)) = context.u.get(NS_ERROR) {
895                if !code.is_empty() {
896                    // The canonical writes `ctx.t0.bad(nsErr)` here. The
897                    // root is done at DOCUMENT CLOSE, where no token is
898                    // current, so the canonical's `t0` is the no-token
899                    // sentinel, and its report lands at the start of the
900                    // source (row 1, column 1). Marking the same sentinel
901                    // keeps the failure inside the engine's error
902                    // machinery, which is what renders the template
903                    // registered for `code`. An `ActionError` here would
904                    // bypass that and hand the caller a literal stand-in
905                    // message instead.
906                    let code = code.clone();
907                    let mut token = context.t0().cloned().unwrap_or_else(Token::no_token);
908                    token.bad(&code);
909                    return Ok(Some(token));
910                }
911            }
912        }
913        Ok(None)
914    });
915
916    // The document's last rule closes: a value set aside while the white
917    // space after the root was read is the result again. The start rule's
918    // cell IS the document node, shared by the rules that replace the start
919    // rule, so it is written in place.
920    parser.action_with_context(XML_END, |rule, context| {
921        if let Some(value) = context.u.shift_remove(ROOT) {
922            *rule.node.borrow_mut() = value;
923        }
924        Ok(())
925    });
926
927    // Only let `xml` push an `element` while the document has produced
928    // no root (XML 1.0 2.1).
929    parser.alt_condition(NO_ROOT_YET, |_rule, context| {
930        !matches!(context.u.get("rootSeen"), Some(Value::Bool(true)))
931    });
932
933    parser.action_with_match_ref(DOC_TEXT_OPEN, |rule, context, _matched| {
934        Ok(check_doc_text(rule.o0(), context))
935    });
936    // White space after the root element. This rule is replaced to read
937    // what follows (`r: xml`), and the rule replacing it shares this
938    // rule's cell, so the document's value is set aside until the last
939    // rule closes (`@xml-end`): no rule that starts after the root element
940    // is done is handed the finished document as its node.
941    parser.action_with_match_ref(DOC_TEXT_CLOSE, |rule, context, _matched| {
942        if let Some(bad) = check_doc_text(rule.c0(), context) {
943            return Ok(Some(bad));
944        }
945        let value = std::mem::replace(&mut *rule.node.borrow_mut(), Value::Undefined);
946        if !value.is_undefined() {
947            context.u.insert(ROOT.to_string(), value);
948        }
949        Ok(None)
950    });
951
952    parser.action_with_context(ELEMENT_OPEN, move |rule, context| {
953        start_element(rule, context, false, namespaces, strict_namespaces);
954        Ok(())
955    });
956    parser.action_with_context(ELEMENT_SELFCLOSE, move |rule, context| {
957        start_element(rule, context, true, namespaces, strict_namespaces);
958        Ok(())
959    });
960
961    // The close tag must name the open tag. The offending close tag
962    // itself is marked (not the lookahead token) so the caret lands on
963    // `</b>`, and the two names ride on the token as details, which is
964    // where the `{openname}` / `{closename}` placeholders resolve from.
965    // Then the members that follow `children` are appended, in order.
966    parser.action_with_match_ref(ELEMENT_CLOSE, |rule, _context, _matched| {
967        let open_name = match &*rule.node.borrow() {
968            Value::Object(element) => match element.get("name") {
969                Some(Value::String(name)) => name.clone(),
970                _ => String::new(),
971            },
972            _ => String::new(),
973        };
974        let close_name = token_string(rule.c0()).unwrap_or_default();
975        if open_name == close_name {
976            if let Some(Value::Object(fields)) = rule.u.get(FIELDS).cloned() {
977                if let Some(element) = rule.node.borrow_mut().as_object_mut() {
978                    for (key, value) in fields.iter() {
979                        element.insert(key.clone(), value.clone());
980                    }
981                }
982            }
983            return Ok(None);
984        }
985        let Some(mut token) = rule.c0().cloned() else {
986            return Ok(None);
987        };
988        token.bad_with_details(
989            "xml_mismatched_tag",
990            [
991                ("openname".to_string(), Value::String(open_name)),
992                ("closename".to_string(), Value::String(close_name)),
993            ],
994        );
995        Ok(Some(token))
996    });
997
998    // The list is done: it is the element's `children`.
999    parser.action_with_context(CONTENT_CLOSE, |rule, _context| {
1000        let children = rule.child_node.clone();
1001        if let Some(element) = rule.node.borrow_mut().as_object_mut() {
1002            element.insert("children".to_string(), children);
1003        }
1004        Ok(())
1005    });
1006
1007    // The list of an element's children, in a cell of its own. The first
1008    // child is pushed with it and shares it, and so do the children that
1009    // replace the first, so the last of them hands the list back to this
1010    // rule, whose cell it is, and the rule above it, `content`, takes a
1011    // handle on the list only when this rule closes. Until then the list
1012    // has one owner, so a reader of the rule events that empties it in
1013    // place as it streams (tabnas-transduce's pruning) empties the list
1014    // the element stores, not a copy.
1015    parser.state_action_ref(CHILDREN_BO, |rule, _context| {
1016        set_node(rule, Value::array(Vec::new()));
1017        Ok(())
1018    });
1019
1020    parser.action_with_context(CHILD_TEXT, |rule, _context| {
1021        let text = rule
1022            .o0()
1023            .map_or(Value::Undefined, |token| token.val.clone());
1024        if let Some(list) = rule.node.borrow_mut().as_array_mut() {
1025            list.push(text);
1026        }
1027        rule.u_mut().insert("done".to_string(), Value::Bool(true));
1028        Ok(())
1029    });
1030
1031    parser.state_action_ref(CHILD_BC, |rule, _context| {
1032        if flag(rule, "done") || rule.child_node.is_undefined() {
1033            return Ok(());
1034        }
1035        let child = rule.child_node.clone();
1036        if let Some(list) = rule.node.borrow_mut().as_array_mut() {
1037            list.push(child);
1038        }
1039        Ok(())
1040    });
1041
1042    parser.alt_condition(
1043        ELEMENT_IS_SELFCLOSED,
1044        |rule, _context| matches!(rule.u.get("selfclose"), Some(Value::Number(n)) if *n == 1.0),
1045    );
1046}
1047
1048/// The plugin form of [`xml`], for [`Tabnas::use_plugin`]. Options are
1049/// read from the plugin option bag with [`XmlOptions::from_value`];
1050/// installed this way the grammar is re-applied to derived instances, as
1051/// every native plugin is.
1052///
1053/// ```
1054/// let mut parser = tabnas::Tabnas::new();
1055/// parser.use_plugin(tabnas_xml::plugin(), None)?;
1056/// assert_eq!(
1057///     parser.parse("<a>&amp;</a>")?.to_string(),
1058///     r#"{"name":"a","localName":"a","attributes":{},"children":["&"]}"#
1059/// );
1060/// # Ok::<(), Box<dyn std::error::Error>>(())
1061/// ```
1062pub fn plugin() -> Plugin {
1063    Plugin::new(PLUGIN_NAME, |parser, options| {
1064        xml(parser, &XmlOptions::from_value(options))
1065    })
1066    .with_defaults(XmlOptions::default().to_value())
1067}
1068
1069/// Build an XML parser with caller options: the engine, then this
1070/// plugin, the `new Tabnas().use(Xml, options)` of the canonical plugin
1071/// and the `tabnas.Make()` plus `UseDefaults` of Go's C library.
1072///
1073/// Infallible for every option but one: the grammar documents are fixed
1074/// literals, so any other failure here is a bug in this crate rather than
1075/// anything a caller did.
1076///
1077/// # Panics
1078///
1079/// When `options.embed` is true. The engine carries no grammar of its
1080/// own, so embed mode has no jsonic document to embed XML in, and a
1081/// parser built anyway would parse every document to nothing. For embed
1082/// mode, install [`plugin`] on a jsonic parser (`tabnas_jsonic::make()`)
1083/// instead.
1084///
1085/// ```
1086/// let parser = tabnas_xml::make_with(&tabnas_xml::XmlOptions {
1087///     strict_entities: false,
1088///     ..Default::default()
1089/// });
1090/// assert_eq!(
1091///     parser.parse("<a>&nope;</a>")?.to_string(),
1092///     r#"{"name":"a","localName":"a","attributes":{},"children":["&nope;"]}"#
1093/// );
1094/// # Ok::<(), tabnas_xml::XmlError>(())
1095/// ```
1096pub fn make_with(options: &XmlOptions) -> Tabnas {
1097    let mut parser = Tabnas::new();
1098    if let Err(error) = parser.use_plugin(plugin(), Some(options.to_value())) {
1099        // Embed mode, refused by `xml` on the bare engine; or a bug here.
1100        panic!("tabnas_xml::make_with: {error}");
1101    }
1102    parser
1103}
1104
1105/// Build an XML parser with the default options.
1106///
1107/// Reuse the result: building the grammar dominates a parse.
1108///
1109/// ```
1110/// let parser = tabnas_xml::make();
1111/// assert_eq!(
1112///     parser.parse("<a><b/></a>")?.to_string(),
1113///     r#"{"name":"a","localName":"a","attributes":{},"children":[{"name":"b","localName":"b","attributes":{},"children":[]}]}"#
1114/// );
1115/// assert_eq!(parser.parse("<a></b>").unwrap_err().code, "xml_mismatched_tag");
1116/// # Ok::<(), tabnas_xml::XmlError>(())
1117/// ```
1118pub fn make() -> Tabnas {
1119    make_with(&XmlOptions::default())
1120}
1121
1122/// Parse an XML document with the shared default parser.
1123///
1124/// The engine is built once, on first use, and reused after that; reuse
1125/// is safe because [`Tabnas::parse`] takes `&self` and builds a fresh
1126/// parse context per call, and `Tabnas` is `Send + Sync`. Use [`make`] or
1127/// [`make_with`] when the parser needs configuring.
1128///
1129/// ```
1130/// let value = tabnas_xml::parse("<a>Tom &amp; Jerry</a>")?;
1131/// assert_eq!(
1132///     value.to_string(),
1133///     r#"{"name":"a","localName":"a","attributes":{},"children":["Tom & Jerry"]}"#
1134/// );
1135/// assert_eq!(tabnas_xml::parse("<a/>junk").unwrap_err().code, "text_at_top_level");
1136/// # Ok::<(), tabnas_xml::XmlError>(())
1137/// ```
1138pub fn parse(src: &str) -> Result<Value, XmlError> {
1139    static DEFAULT: OnceLock<Tabnas> = OnceLock::new();
1140    DEFAULT.get_or_init(make).parse(src)
1141}
1142
1143/// One optional alchemy translation source and its explicit entry point.
1144#[derive(Clone, Copy, Debug, Eq, PartialEq)]
1145pub struct TranslationPart {
1146    /// The definition a host calls after linking the source.
1147    pub entry: &'static str,
1148    /// The source text, or `None` for an entry supplied by alchemy.
1149    pub source: Option<&'static str>,
1150}
1151
1152/// The package-local structural translation interface.
1153#[derive(Clone, Copy, Debug, Eq, PartialEq)]
1154pub struct TranslationParts {
1155    /// The complete `tabnas.plugin.json` text.
1156    pub manifest: &'static str,
1157    /// An optional lift from the grammar's events to its first read shape.
1158    pub lift: Option<TranslationPart>,
1159    /// An optional embedding of a plain tree in the format's schema, with its reverse.
1160    pub embed: Option<TranslationPart>,
1161    /// An optional render from the write shape to text.
1162    pub render: Option<TranslationPart>,
1163}
1164
1165const TRANSLATION: TranslationParts = TranslationParts {
1166    manifest: include_str!("../translate/manifest.json"),
1167    lift: None,
1168    embed: Some(TranslationPart {
1169        entry: "xml-embed",
1170        source: Some(include_str!("../translate/embed.alc")),
1171    }),
1172    render: Some(TranslationPart {
1173        entry: "xml-render",
1174        source: Some(include_str!("../translate/render.alc")),
1175    }),
1176};
1177
1178/// Return XML's immutable translation parts.
1179#[must_use]
1180pub const fn translate() -> Option<TranslationParts> {
1181    Some(TRANSLATION)
1182}
1183
1184/// The plugin's manifest, `tabnas.plugin.json`, as the repository carries
1185/// it. Its `translate` object is what a host that translates reads: the
1186/// shape XML is read as and written from (`tree`), the root it takes
1187/// (`any`), the schema of the tree its events carry (`xml-element`), the
1188/// files that hold the embedding of a plain tree in that schema and the
1189/// render, and the sentences that say what the render does not keep and
1190/// how a plain tree is written. The crate embeds its own copy,
1191/// `translate/manifest.json`, since a packaged crate holds nothing
1192/// outside `rs/`; `tests/translate_test.rs` holds the copy to the file.
1193///
1194/// ```
1195/// assert!(tabnas_xml::manifest_text().contains("\"translate\""));
1196/// ```
1197pub fn manifest_text() -> &'static str {
1198    TRANSLATION.manifest
1199}
1200
1201/// XML's render, `alchemy/render.alc`, the file the manifest's
1202/// `translate.render` names: a library of alchemy definitions, with no
1203/// `export`, whose entry point `xml-render` writes an element tree's
1204/// events, the shape this reader builds, as one XML document, and
1205/// refuses any other tree, and one holding a text, an attribute value
1206/// or a name no XML document can hold. A host links it with its own
1207/// program. The crate embeds its own copy, `translate/render.alc`, held
1208/// to the file as the manifest's is.
1209///
1210/// ```
1211/// assert!(tabnas_xml::render_text().contains("def xml-render [input]"));
1212/// ```
1213pub fn render_text() -> &'static str {
1214    match TRANSLATION.render {
1215        Some(part) => part.source.unwrap_or_default(),
1216        None => "",
1217    }
1218}
1219
1220/// The error templates, interpolated against the failing token's
1221/// details. Kept identical to `ts/src/xml.ts`. `$name` is not a
1222/// placeholder syntax the engine understands, so it is never used here.
1223const ERROR_MESSAGES: &[(&str, &str)] = &[
1224    (
1225        "xml_mismatched_tag",
1226        "closing tag </{closename}> does not match opening tag <{openname}>",
1227    ),
1228    ("xml_invalid_tag", "invalid tag: {src}"),
1229    ("unterminated_comment", "unterminated comment: {src}"),
1230    ("unterminated_cdata", "unterminated CDATA section: {src}"),
1231    (
1232        "unterminated_pi",
1233        "unterminated processing instruction: {src}",
1234    ),
1235    (
1236        "unterminated_doctype",
1237        "unterminated DOCTYPE declaration: {src}",
1238    ),
1239    ("comment_double_dash", "comment body cannot contain \"--\""),
1240    (
1241        "cdata_terminator_in_text",
1242        "character data cannot contain \"]]>\"",
1243    ),
1244    (
1245        "pi_target_invalid",
1246        "processing instruction target is missing or invalid",
1247    ),
1248    (
1249        "lt_in_attr_value",
1250        "\"<\" is not allowed in an attribute value",
1251    ),
1252    (
1253        "bad_entity_ref",
1254        "malformed entity reference (need &name; or &#NNN; or &#xHHH;)",
1255    ),
1256    ("duplicate_attribute", "duplicate attribute name in tag"),
1257    ("invalid_xml_char", "illegal control character in XML data"),
1258    (
1259        "reserved_namespace",
1260        "invalid use of a reserved namespace prefix or URI",
1261    ),
1262    (
1263        "unbound_prefix",
1264        "element or attribute uses an undeclared namespace prefix",
1265    ),
1266    (
1267        "invalid_namespace_uri",
1268        "namespace name cannot contain white space",
1269    ),
1270    ("undeclared_entity", "reference to undeclared entity"),
1271    (
1272        "unparsed_entity_ref",
1273        "reference to an unparsed (NDATA) entity",
1274    ),
1275    (
1276        "external_entity_in_attr",
1277        "attribute value cannot reference an external entity",
1278    ),
1279    (
1280        "text_at_top_level",
1281        "character data is not allowed outside the root element",
1282    ),
1283];
1284
1285/// The hint for each error code. Kept identical to `ts/src/xml.ts`.
1286const ERROR_HINTS: &[(&str, &str)] = &[
1287    (
1288        "xml_mismatched_tag",
1289        "Each opening tag must be paired with a matching closing tag.\nExpected </{openname}> but found </{closename}>.",
1290    ),
1291    ("xml_invalid_tag", "The tag syntax is not valid XML."),
1292    (
1293        "unterminated_comment",
1294        "The comment starting at this position has no closing \"-->\".",
1295    ),
1296    (
1297        "unterminated_cdata",
1298        "The CDATA section starting at this position has no closing \"]]>\".",
1299    ),
1300    (
1301        "unterminated_pi",
1302        "The processing instruction starting at this position has no closing \"?>\".",
1303    ),
1304    (
1305        "unterminated_doctype",
1306        "The DOCTYPE declaration starting at this position has no closing \">\".",
1307    ),
1308    (
1309        "comment_double_dash",
1310        "XML 1.0 disallows \"--\" inside a comment body.",
1311    ),
1312    (
1313        "cdata_terminator_in_text",
1314        "The literal \"]]>\" must only appear as the end of a CDATA section.",
1315    ),
1316    (
1317        "pi_target_invalid",
1318        "A processing instruction must start with a Name; the XML declaration <?xml...?> is the special case.",
1319    ),
1320    (
1321        "lt_in_attr_value",
1322        "Use the entity reference &lt; to include \"<\" in an attribute value.",
1323    ),
1324    (
1325        "bad_entity_ref",
1326        "Replace literal \"&\" with &amp;, or terminate the entity reference with \";\".",
1327    ),
1328    (
1329        "duplicate_attribute",
1330        "Each attribute name in an open tag must be unique.",
1331    ),
1332    (
1333        "invalid_xml_char",
1334        "Only #x9, #xA, #xD and code points >= #x20 are legal XML characters.",
1335    ),
1336    (
1337        "reserved_namespace",
1338        "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.",
1339    ),
1340    (
1341        "unbound_prefix",
1342        "Declare the prefix with xmlns:prefix=\"...\" on this element or one of its ancestors.",
1343    ),
1344    (
1345        "invalid_namespace_uri",
1346        "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.",
1347    ),
1348    (
1349        "undeclared_entity",
1350        "Declare the entity in the DOCTYPE internal subset, add it to the customEntities option, or set strictEntities: false to allow unresolved references through.",
1351    ),
1352    (
1353        "unparsed_entity_ref",
1354        "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.",
1355    ),
1356    (
1357        "external_entity_in_attr",
1358        "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.",
1359    ),
1360    (
1361        "text_at_top_level",
1362        "An XML document is \"prolog element Misc*\": outside the single root element only comments, processing instructions and white space may appear.",
1363    ),
1364];