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