Skip to main content

latexml_core/common/
model.rs

1use std::{
2  cell::RefCell,
3  fs::File,
4  io::{BufRead, BufReader},
5  sync::LazyLock,
6};
7
8use libxml::{readonly::RoNode, tree::Node};
9use regex::Regex;
10use rustc_hash::FxHashSet as HashSet;
11
12use super::arena::SymHashMap;
13use crate::{
14  common::{
15    arena::{self, SymStr},
16    error::*,
17    relaxng::Relaxng,
18    xml::XML_NS,
19  },
20  document::Document,
21  pin,
22  util::pathname,
23};
24
25// use common::font::*;
26
27pub const LTX_NAMESPACE: &str = "http://dlmf.nist.gov/LaTeXML";
28pub type IndirectModel = SymHashMap<SymHashMap<SymStr>>;
29
30static PREFIXED_LOCALNAME_RE: LazyLock<Regex> =
31  LazyLock::new(|| Regex::new(r"^([^:]+):(.+)$").unwrap());
32static TAG_MODEL_LINE_RE: LazyLock<Regex> =
33  LazyLock::new(|| Regex::new(r"^([^\{]+)\{(.*?)\}\((.*?)\)$").unwrap());
34// Mirrors Perl Model.pm L149: `m/^([^:=]+):=\(?([^)]*?)\)?$/` — the
35// `\(?…\)?` pair strips the surrounding parens from
36// `classname:=(elt1,elt2,...)` so the elements split cleanly.
37static CLASS_MODEL_LINE_RE: LazyLock<Regex> =
38  LazyLock::new(|| Regex::new(r"^([^:=]+):=\(?([^)]*?)\)?$").unwrap());
39static NAMESPACE_MODEL_LINE_RE: LazyLock<Regex> =
40  LazyLock::new(|| Regex::new(r"^([^=]+)=(.*?)$").unwrap());
41
42#[derive(Default, Debug)]
43pub struct TagFrame {
44  model:      HashSet<SymStr>,
45  attributes: HashSet<SymStr>,
46}
47
48static DEFAULT_TAG_FRAME: LazyLock<TagFrame> = LazyLock::new(TagFrame::default);
49
50#[derive(Default, Debug)]
51pub struct Model {
52  pub schema:                      Option<Relaxng>,
53  pub schema_data:                 Option<Vec<SymStr>>,
54  pub schema_class:                SymHashMap<HashSet<SymStr>>,
55  pub code_namespace_prefixes:     SymHashMap<SymStr>,
56  pub code_namespaces:             SymHashMap<SymStr>,
57  pub document_namespace_prefixes: SymHashMap<SymStr>,
58  pub document_namespaces:         SymHashMap<SymStr>,
59  // doctype_namespaces: SymHashMap<SymStr>,
60  // namespace_errors: usize,
61  pub permissive:                  bool,
62  pub no_compiled:                 bool,
63  pub debug_mode:                  bool,
64  pub namespace_errors:            u8,
65  pub tagprop:                     SymHashMap<TagFrame>,
66}
67
68thread_static! {
69  pub static MODEL: RefCell<Model> = RefCell::new(Model::new());
70}
71
72macro_rules! model {
73  () => {
74    (*MODEL).borrow()
75  };
76}
77macro_rules! model_mut {
78  () => {
79    (*MODEL).borrow_mut()
80  };
81}
82
83pub fn initialize_model() {
84  let mut global_model = MODEL.borrow_mut();
85  *global_model = Model::new();
86}
87
88/// Eagerly initialize this thread's per-thread `MODEL` root.
89///
90/// `Model::new()` interns the `xml` namespace prefix/URI via `arena::pin`,
91/// so its initializer reaches into the `ARENA` thread-local. Forcing
92/// it at conversion entry — *after* [`arena::force_init`](crate::common::arena::force_init)
93/// and before `STATE`/`STOMACH` are built — keeps that init from running
94/// re-entrantly from within another root's initialization, the macOS
95/// thread-local hazard behind issue #217. No behavioral change on
96/// Linux (a later `set_model` for a schema-driven model still replaces it).
97pub(crate) fn force_init() { let _ = &*MODEL; }
98
99impl Model {
100  pub fn new() -> Self {
101    let mut model = Model::default();
102    // model.xpath.register_function("match-font", |x, y| {font::match_font(x,y)})
103    model.register_namespace("xml", Some(XML_NS));
104    model.register_document_namespace("xml", Some(XML_NS));
105    model
106  }
107  ///**********************************************************************
108  /// Namespaces
109  ///**********************************************************************
110  /// There are TWO namespace mappings!!!
111  /// One for coding, one for the document output.
112  ///
113  /// Coding: this namespace mapping associates prefixes to namespace URIs for
114  ///   use in the latexml code, constructors and such.
115  ///   This must be a one to one mapping and there are no default namespaces.
116  /// Document: this namespace mapping associates prefixes to namespace URIs
117  ///   as used in the generated document, and will be the
118  ///   set of prefixes used in the generated output.
119  ///   This mapping may also use a prefix of "#default" which is for
120  ///   the unprefixed form of elements (not used for attributes!)
121  pub fn register_namespace(&mut self, codeprefix: &str, namespace_opt: Option<&str>) {
122    self.register_namespace_sym(arena::pin(codeprefix), namespace_opt.map(arena::pin))
123  }
124  pub fn register_namespace_sym(&mut self, codeprefix: SymStr, namespace_opt: Option<SymStr>) {
125    // double-check empty strings are None
126    let namespace_opt_checked = namespace_opt.filter(|val| *val != pin!(""));
127    match namespace_opt_checked {
128      Some(namespace) => {
129        self
130          .code_namespace_prefixes
131          .insert_sym(namespace, codeprefix);
132        self.code_namespaces.insert_sym(codeprefix, namespace);
133      },
134      None => {
135        if let Some(prev) = self.code_namespaces.get_sym(codeprefix) {
136          self.code_namespace_prefixes.remove_sym(*prev);
137        };
138        self.code_namespaces.remove_sym(codeprefix);
139      },
140    };
141  }
142
143  /// Register a prefix in the DOCUMENT mapping — the second of the two
144  /// mappings described on [`Model::register_namespace`] above.
145  ///
146  /// An empty `docprefix` is the `#default` entry, i.e. the unprefixed form of
147  /// elements (never attributes). `None` for the namespace unbinds the prefix.
148  pub fn register_document_namespace(&mut self, docprefix: &str, namespace_opt: Option<&str>) {
149    let default_sym = pin!("#default");
150    let docprefix_sym = if docprefix.is_empty() {
151      default_sym
152    } else {
153      arena::pin(docprefix)
154    };
155
156    match namespace_opt {
157      Some(namespace) => {
158        // Since the default namespace url can still ALSO have a prefix associated,
159        // we prepend "DEFAULT#url" when using as a hash key in the prefixes table.
160        let ns_sym = arena::pin(namespace);
161        let regnamespace = if docprefix_sym == default_sym {
162          arena::pin(s!("DEFAULT#{namespace}"))
163        } else {
164          ns_sym
165        };
166        self
167          .document_namespace_prefixes
168          .insert_sym(regnamespace, docprefix_sym);
169        self.document_namespaces.insert_sym(docprefix_sym, ns_sym);
170      },
171      None => {
172        if let Some(prev) = self.document_namespaces.get_sym(docprefix_sym) {
173          self.document_namespace_prefixes.remove_sym(*prev);
174        };
175        self.document_namespaces.remove_sym(docprefix_sym);
176      },
177    };
178  }
179
180  pub fn set_relaxng_schema(&mut self, schema: &str) {
181    self.schema_data = Some(vec![pin!("RelaxNG"), arena::pin(schema)]);
182  }
183  /// TODO: This is another component that would fit perfectly as a compiler plugin.
184  /// For now, simply reimplementing the runtime loading of
185  /// LaTeXML.model as-is from Model.pm
186  pub fn load_compiled_schema(&mut self, path: &str) {
187    let compiled_fh = File::open(path).unwrap();
188    let compiled_reader = BufReader::new(&compiled_fh);
189    let content: String = compiled_reader
190      .lines()
191      .map_while(std::result::Result::ok)
192      .collect::<Vec<_>>()
193      .join("\n");
194    self.load_compiled_schema_str(&content, path);
195  }
196
197  /// Same as [`Self::load_compiled_schema`] but consumes an already-
198  /// loaded `.model` body. `source` is used purely for diagnostic
199  /// messages (the `note_begin`/`note_end` envelope and the
200  /// malformed-line panic). Avoids the disk read when the model is
201  /// served from the binary's own embedded RelaxNG table.
202  pub fn load_compiled_schema_str(&mut self, content: &str, source: &str) {
203    note_begin(&s!("Loading compiled schema {}\n", source));
204    for line in content.lines() {
205      if let Some(caps) = TAG_MODEL_LINE_RE.captures(line) {
206        let tag = caps.get(1).map_or("", |m| m.as_str());
207        let attr = caps.get(2).map_or("", |m| m.as_str());
208        let children = caps.get(3).map_or("", |m| m.as_str());
209        self.add_tag_attribute(tag, attr.split(',').collect());
210        self.add_tag_content(tag, children.split(',').collect());
211      } else if let Some(caps) = CLASS_MODEL_LINE_RE.captures(line) {
212        let classname = caps.get(1).map_or("", |m| m.as_str());
213        let elements = caps.get(2).map_or("", |m| m.as_str());
214        let mut class_set = HashSet::default();
215        for set_element in elements.split(',') {
216          class_set.insert(arena::pin(set_element));
217        }
218        self.set_schema_class(classname, class_set);
219      } else if let Some(caps) = NAMESPACE_MODEL_LINE_RE.captures(line) {
220        let prefix = caps.get(1).map_or("", |m| m.as_str());
221        let namespace = caps.get(2).map_or("", |m| m.as_str());
222        self.register_document_namespace(prefix, Some(namespace));
223      } else {
224        panic!("Fatal:internal:{source} Compiled model '{source}' is malformatted at \"{line}\"");
225      }
226    }
227    note_end(&s!("Loading compiled schema {source}\n"));
228  }
229  pub fn add_tag_content(&mut self, tag: &str, elements: Vec<&str>) {
230    let frame = self.tagprop.entry(tag).or_default();
231
232    for element in elements {
233      frame.model.insert(arena::pin(element));
234    }
235  }
236
237  // pub fn get_tag_attributes(&self, tag: &str) -> Vec<&str> {
238  //   match self.tagprop.get(&arena::pin(tag)) {
239  //     Some(h) => {
240  //       let mut keys: Vec<&str> = h.attributes.iter().map(|s| arena::resolve(*s)).collect();
241  //       keys.sort_unstable();
242  //       keys
243  //     },
244  //     None => Vec::new(),
245  //   }
246  // }
247
248  pub fn add_tag_attribute(&mut self, tag: &str, attributes: Vec<&str>) {
249    let frame = self.tagprop.entry(tag).or_default();
250
251    for attribute in attributes {
252      frame.attributes.insert(arena::pin(attribute));
253    }
254  }
255
256  pub fn set_schema_class(&mut self, classname: &str, content: HashSet<SymStr>) {
257    self.schema_class.insert(classname, content);
258  }
259
260  /// Serialise the loaded schema into the `.model` plain-text format
261  /// emitted by Perl `LaTeXML::Common::Model::compileSchema`
262  /// (Model.pm L121-136). Three kinds of lines, all newline-separated:
263  ///
264  /// * `prefix=namespace` for every entry in `document_namespaces` (sorted by prefix).
265  /// * `classname:=(elt1,elt2,...)` for every entry in `schema_class` (sorted by classname; each
266  ///   element list sorted).
267  /// * `tag{attr1,attr2}(child1,child2)` for every entry in `tagprop` (sorted by tag; attrs and
268  ///   children sorted; tags whose name starts with `!` are skipped — they are content-model-only
269  ///   negations).
270  ///
271  /// Output is identical to the Perl tool so a downstream
272  /// `tools/compileschema.sh` can diff Rust vs. Perl-generated
273  /// `LaTeXML.model` files byte-for-byte (modulo schema content).
274  pub fn dump_compiled_schema(&self) -> String {
275    fn sym_to_string(sym: SymStr) -> String { arena::with(sym, |s| s.to_string()) }
276    fn syms_sorted(set: impl IntoIterator<Item = SymStr>) -> Vec<String> {
277      let mut v: Vec<String> = set.into_iter().map(sym_to_string).collect();
278      v.sort();
279      v
280    }
281    let mut out = String::new();
282    let prefixes = syms_sorted(self.document_namespaces.keys().copied());
283    for prefix in &prefixes {
284      let ns_opt = self
285        .document_namespaces
286        .get_sym(arena::pin(prefix.as_str()));
287      let ns = match ns_opt {
288        Some(v) => sym_to_string(*v),
289        None => continue,
290      };
291      out.push_str(prefix);
292      out.push('=');
293      out.push_str(&ns);
294      out.push('\n');
295    }
296    let classnames = syms_sorted(self.schema_class.keys().copied());
297    for classname in &classnames {
298      let elements = match self.schema_class.get_sym(arena::pin(classname.as_str())) {
299        Some(set) => set,
300        None => continue,
301      };
302      let elt_names = syms_sorted(elements.iter().copied());
303      out.push_str(classname);
304      out.push_str(":=(");
305      out.push_str(&elt_names.join(","));
306      out.push_str(")\n");
307    }
308    let tags = syms_sorted(self.tagprop.keys().copied());
309    for tag in &tags {
310      if tag.starts_with('!') {
311        continue;
312      }
313      let frame = match self.tagprop.get_sym(arena::pin(tag.as_str())) {
314        Some(f) => f,
315        None => continue,
316      };
317      let attrs = syms_sorted(frame.attributes.iter().copied());
318      let children = syms_sorted(frame.model.iter().copied());
319      out.push_str(tag);
320      out.push('{');
321      out.push_str(&attrs.join(","));
322      out.push_str("}(");
323      out.push_str(&children.join(","));
324      out.push_str(")\n");
325    }
326    out
327  }
328  pub fn describe_model(&self) {}
329  fn load_internal_extensions(&mut self) {
330    if !self.tagprop.contains_key("ltx:_CaptureBlock_") {
331      // Synthesize ltx:_CaptureBlock_ to act like the union of ltx:block,
332      // ltx:logical-block, ltx:sectional-block, Caption, FrontMatter,
333      // BackMatter (Perl Common/Model.pm loadInternalExtensions L96-97).
334      // FrontMatter/BackMatter were missing here, so a captured box that
335      // legitimately holds frontmatter/backmatter content was modelled
336      // more narrowly than Perl.
337      self.synthesize_element("ltx:_CaptureBlock_", &[
338        "ltx:block",
339        "ltx:logical-block",
340        "ltx:sectional-block",
341        "Caption",
342        "FrontMatter",
343        "BackMatter",
344      ]);
345      let cb_entry = self.tagprop.entry("ltx:_CaptureBlock_").or_default();
346      cb_entry.model.insert(pin!("svg:g"));
347      cb_entry.model.insert(pin!("svg:foreignObject"));
348    }
349  }
350
351  /// Clone the tagprop's (allowed content & attributes) of @other to $tag
352  fn synthesize_element(&mut self, tag: &str, others: &[&str]) {
353    let mut to_add_in_model = Vec::new();
354    let mut to_add_in_attrs = Vec::new();
355    for other in others {
356      if let Some(content) = self.schema_class.get(other) {
357        for child in content {
358          to_add_in_model.push(*child);
359        }
360      } else if let Some(entry) = self.tagprop.get(other) {
361        for child in &entry.model {
362          to_add_in_model.push(*child);
363        }
364        for attr in &entry.attributes {
365          to_add_in_attrs.push(*attr);
366        }
367      }
368    }
369    let capture = self.tagprop.entry(tag).or_default();
370    for child in to_add_in_model {
371      capture.model.insert(child);
372    }
373    for attr in to_add_in_attrs {
374      capture.attributes.insert(attr);
375    }
376  }
377}
378
379pub fn set_relaxng_schema(schema: &str) { model_mut!().set_relaxng_schema(schema) }
380pub fn add_schema_declaration(document: &mut Document) {
381  if let Some(ref schema) = model!().schema {
382    schema.add_schema_declaration(document);
383  }
384}
385
386pub fn load_schema(search_paths: &[&str]) -> Result<()> {
387  // Only load once
388  let mut model = model_mut!();
389  if model.schema.is_some() {
390    return Ok(());
391  }
392  let mut name = String::new();
393  if model.schema_data.is_none() {
394    // TODO: Return this code path to normal once we properly load schemas
395    Warn!("expected", "<model>", "TODO");
396    // Warn('expected', '<model>', undef, "No Schema Model has been declared; assuming LaTeXML");
397    // // article ??? or what ? undef gives problems!
398
399    model.register_document_namespace("ltx", Some(LTX_NAMESPACE));
400    model.set_relaxng_schema("LaTeXML");
401    model.register_namespace("ltx", Some(LTX_NAMESPACE));
402    model.register_namespace("svg", Some("http://www.w3.org/2000/svg"));
403    model.register_namespace("xlink", Some("http://www.w3.org/1999/xlink")); // Needed for SVG
404    model.register_namespace("m", Some("http://www.w3.org/1998/Math/MathML"));
405    model.register_namespace("xhtml", Some("http://www.w3.org/1999/xhtml"));
406    model.permissive = true;
407  } // Actually, they could have declared all sorts of Tags....
408  // Only RelaxNG schemas are supported (DTD support removed from Rust port)
409  if let Some(ref data) = model.schema_data {
410    if data[0] == pin!("RelaxNG") {
411      name = arena::to_string(data[1]);
412      model.schema = Some(Relaxng {
413        name: name.clone(),
414        ..Relaxng::default()
415      });
416    } else {
417      let message = arena::with(data[0], |schema_type_str| {
418        s!("Can't load a schema of type {schema_type_str:?}")
419      });
420      Error!("unknown", "schematype", message)
421    }
422  }
423
424  if !model.no_compiled && model.schema.is_some() {
425    let paths: Option<Vec<String>> = if search_paths.is_empty() {
426      None
427    } else {
428      Some(search_paths.iter().map(ToString::to_string).collect())
429    };
430    // The engine's own schema, read on its own behalf (never a document's name).
431    let pathname_opt = pathname::own_behalf(|| {
432      pathname::find(&name, pathname::PathnameFindOptions {
433        paths,
434        extensions: Some(vec![s!("model")]),
435        installation_subdir: Some(s!("resources/RelaxNG")),
436      })
437    });
438
439    match pathname_opt {
440      Some(compiled_path) => model.load_compiled_schema(&compiled_path),
441      None => {
442        // No `.model` on the searchpath. Try the embedded RelaxNG
443        // table for a same-named compiled schema first (the
444        // distribution path — binary running outside the source
445        // tree); fall through to raw `.rng` parsing if that misses
446        // too.
447        let embed_key = format!("{}.model", name);
448        if let Some(content) = crate::common::relaxng::embedded::lookup(&embed_key) {
449          model.load_compiled_schema_str(content, &format!("<embedded>/{embed_key}"));
450        } else {
451          let paths: Vec<&std::path::Path> =
452            search_paths.iter().map(std::path::Path::new).collect();
453          // Seed the scanner with the model's registered code-namespace prefixes
454          // (e.g. `ltx` → dlmf from `base_schema`), so a schema whose target
455          // namespace appears only as a default `ns=` — with no `xmlns:` prefix,
456          // exactly how `LaTeXML.rng` is written — resolves to that conventional
457          // prefix instead of a synthetic `namespaceN` the runtime never matches
458          // (Perl: the scanner delegates `encodeQName` to the model; #652).
459          // Collect first: the immutable borrow ends before `schema.as_mut()`.
460          let code_prefix_seed: Vec<(String, String)> = model
461            .code_namespace_prefixes
462            .iter()
463            .map(|(uri, prefix)| {
464              (
465                arena::with(*uri, |s| s.to_string()),
466                arena::with(*prefix, |s| s.to_string()),
467              )
468            })
469            .collect();
470          let schema = model.schema.as_mut().unwrap();
471          schema.code_namespace_prefixes = code_prefix_seed.into_iter().collect();
472          let schema_name = schema.name.clone();
473          match schema.load_schema(&schema_name, &paths) {
474            Err(err) => {
475              let msg = format!("load_schema failed for {}: {}", schema_name, err);
476              Warn!("expected", "RelaxNG", msg);
477            },
478            // A raw `.rng` was scanned but the tag/attribute/namespace/class
479            // tables the runtime consults are NOT baked into it (unlike a
480            // compiled `.model`). Distil them now — else `tagprop` stays empty
481            // and every element is rejected (#652). `compute_model_data` owns its
482            // result, so the immutable `model.schema` borrow ends before the
483            // `add_*`/`register_*`/`set_*` mutations below.
484            Ok(()) => {
485              let data = model.schema.as_ref().unwrap().compute_model_data();
486              for (tag, children) in &data.tag_contents {
487                model.add_tag_content(tag, children.iter().map(String::as_str).collect());
488              }
489              for (tag, attrs) in &data.tag_attributes {
490                model.add_tag_attribute(tag, attrs.iter().map(String::as_str).collect());
491              }
492              for (name, members) in &data.schema_classes {
493                model.set_schema_class(name, members.iter().map(arena::pin).collect());
494              }
495              for (prefix, uri) in &data.namespaces {
496                model.register_document_namespace(prefix, Some(uri));
497              }
498              // Perl RelaxNG.pm L78: register the schema's primary namespace as
499              // the DEFAULT document namespace, so the output serializes it with
500              // no prefix (the schema's unprefixed default-`ns=` elements).
501              // Generalized from Perl's hardcoded dlmf to the schema's ACTUAL
502              // primary namespace, so a schema with a different default namespace
503              // gets ITS namespace as the output default — full namespace
504              // expressivity, user-directed (#652). For a LaTeXML-namespace
505              // schema this is identical to Perl. (`""` prefix → `#default`.)
506              let primary = model.schema.as_ref().unwrap().primary_namespace.clone();
507              if let Some(primary) = primary {
508                model.register_document_namespace("", Some(&primary));
509              }
510            },
511          }
512        }
513      },
514    };
515  }
516  model.load_internal_extensions();
517  if model.debug_mode {
518    model.describe_model()
519  }
520
521  Ok(())
522}
523
524pub fn get_document_namespace_prefix(
525  namespace: &str,
526  forattribute: bool,
527  probe: bool,
528) -> Option<SymStr> {
529  // Get the prefix associated with the namespace url, noting that for elements, it might by
530  // "#default", but for attributes would never be.
531  // log!("Searching for {:?} in {:?}", namespace, self.document_namespace_prefixes);
532  let mut docprefix = if !forattribute {
533    model!()
534      .document_namespace_prefixes
535      .get(&s!("DEFAULT#{namespace}"))
536      .copied()
537  } else {
538    None
539  };
540  let ns_sym = arena::pin(namespace);
541  if docprefix.is_none() {
542    docprefix = model!()
543      .document_namespace_prefixes
544      .get_sym(ns_sym)
545      .copied();
546  }
547
548  // Perl Model.pm `getDocumentNamespacePrefix` L242: for a non-LaTeXML
549  // namespace with no explicit document prefix, fall back to the registered
550  // CODE prefix. This is what lets FOREIGN namespaces — built-in (`svg`, `m`,
551  // `xlink`, `xhtml`) or supplied by a third-party / runtime `.rhai` binding via
552  // `RegisterNamespace` — serialize under their conventional prefix instead of a
553  // synthetic `namespaceN` + "no prefix registered" warning (#652). The LaTeXML
554  // namespace is excluded: it is the default document namespace (registered from
555  // the schema's primary `ns=`) and serializes with no prefix.
556  if docprefix.is_none() && namespace != LTX_NAMESPACE {
557    docprefix = model!().code_namespace_prefixes.get_sym(ns_sym).copied();
558  }
559
560  if docprefix.is_none() && !probe {
561    {
562      model_mut!().namespace_errors += 1;
563    }
564    let ns_err = s!("namespace{}", &model!().namespace_errors.to_string());
565    docprefix = Some(arena::pin(&ns_err));
566    {
567      model_mut!().register_document_namespace(&ns_err, Some(namespace));
568    }
569    let message2 = if let Some(dp) = docprefix {
570      arena::with(dp, |dp_str| s!("Using '{dp_str}' instead"))
571    } else {
572      String::from("No prefix to fall back on.")
573    };
574    Warn!(
575      "malformed",
576      namespace,
577      "No prefix has been registered for namespace (in document)",
578      message2
579    );
580  }
581  let default_sym = pin!("#default");
582  docprefix.filter(|p| p != &default_sym)
583}
584
585pub fn get_document_namespace(docprefix: &str, probe: bool) -> Option<String> {
586  let h_default_sym = pin!("#default");
587  let docprefix_sym = if docprefix.is_empty() {
588    h_default_sym
589  } else {
590    arena::pin(docprefix)
591  };
592  let ns_str = match model!().document_namespaces.get_sym(docprefix_sym) {
593    None => String::new(),
594    Some(sym) => arena::with(*sym, |s| {
595      if s.starts_with("DEFAULT#") {
596        s.replacen("DEFAULT#", "", 1)
597      } else {
598        s.to_string()
599      }
600    }),
601  };
602
603  if docprefix_sym != h_default_sym && ns_str.is_empty() && !probe {
604    {
605      model_mut!().namespace_errors += 1;
606    }
607    let ns_error = s!(
608      "http://example.com/namespace{}",
609      &model!().namespace_errors.to_string()
610    );
611    {
612      model_mut!().register_document_namespace(docprefix, Some(&ns_error));
613    }
614    let msg1 = arena::with(docprefix_sym, |dp_str| {
615      s!("No namespace has been registered for prefix '{dp_str}' (in document)")
616    });
617    let msg2 = s!("Using '{ns_str}' instead");
618    let err = || {
619      Error!("malformed", docprefix, msg1, msg2);
620      Ok(())
621    };
622    err().ok();
623  }
624  if ns_str.is_empty() {
625    None
626  } else {
627    Some(ns_str)
628  }
629}
630
631/// Get the (code) prefix associated with $namespace,
632/// creating a dummy prefix and signalling an error if none has been registered.
633///
634/// In the following:
635/// $forattribute is 1 if the namespace is for an attribute (in which case, there must be a
636/// non-empty prefix) $probe, if non 0, just test for namespace, without creating an entry
637/// if missing.
638pub fn get_namespace_prefix(namespace: &str, _forattribute: bool, probe: bool) -> Option<SymStr> {
639  if probe {
640    // Model.pm:196-197: a probe reads the registered code prefix and synthesizes none.
641    return model!()
642      .code_namespace_prefixes
643      .get_sym(arena::pin(namespace))
644      .copied();
645  }
646  let mut codeprefix: Option<SymStr> = None;
647  let ns_sym = arena::pin(namespace);
648  let mut model = model_mut!();
649  if !namespace.is_empty() {
650    codeprefix = model.code_namespace_prefixes.get_sym(ns_sym).copied();
651
652    if codeprefix.is_some() && !probe {
653      {
654        let docprefix = model.document_namespace_prefixes.get_sym(ns_sym);
655        // if there's a doc prefix and it's NOT already used in code namespace mapping
656        if docprefix.is_some() && !model.code_namespaces.contains_key_sym(docprefix.unwrap()) {
657          codeprefix = docprefix.copied();
658        }
659      }
660    } else {
661      // Else synthesize one
662      model.namespace_errors += 1;
663      let auto_prefix = arena::pin(s!("namespace{}", &model.namespace_errors.to_string()));
664      codeprefix = Some(auto_prefix);
665    }
666    model.register_namespace_sym(codeprefix.unwrap(), Some(arena::pin(namespace)));
667    // Warn!('malformed', $namespace, undef,
668    //   "No prefix has been registered for namespace '$namespace' (in code)",
669    //   "Using '$codeprefix' instead"); }
670  }
671
672  codeprefix
673}
674
675pub fn get_namespace(codeprefix: &str, probe: bool) -> Result<Option<SymStr>> {
676  let mut model = model_mut!();
677  let mut ns: Option<SymStr> = model.code_namespaces.get(codeprefix).copied();
678  if ns.is_none() && !probe {
679    model.namespace_errors += 1;
680    let example_namespace = s!(
681      "http://example.com/namespace{}",
682      &model.namespace_errors.to_string()
683    );
684    ns = Some(arena::pin(&example_namespace));
685    model.register_namespace(codeprefix, Some(&example_namespace));
686    Error!(
687      "malformed",
688      codeprefix,
689      s!("No namespace has been registered for prefix '{codeprefix}' (in code)"),
690      s!("Using '{example_namespace}' instead")
691    );
692  }
693  Ok(ns)
694}
695
696/// Build a `prefix:local` qname with one exact-capacity allocation, avoiding the
697/// `format!` machinery (`s!`) ([`get_foreign_node_qname`]).
698#[inline]
699fn prefixed_qname(prefix: &str, local: &str) -> String {
700  let mut q = String::with_capacity(prefix.len() + 1 + local.len());
701  q.push_str(prefix);
702  q.push(':');
703  q.push_str(local);
704  q
705}
706
707/// Get the node's qualified name in standard form
708/// Ie. using the registered (code) prefix for that namespace.
709/// NOTE: Reconsider how _Capture_ & _WildCard_ should be integrated!?!
710pub fn get_node_qname(node: &Node) -> SymStr { get_ro_node_qname(node.as_readonly()) }
711
712/// [`get_node_qname`] of a node met in a read-only walk. The name and prefix are read borrowed: this runs on every model
713/// check and serialization step, where copying them out was ≈0.75 % of a conversion (PERF2 R7).
714pub fn get_ro_node_qname(node: RoNode) -> SymStr {
715  use libxml::tree::NodeType::*;
716  let node_type = node.get_type();
717  if node_type.is_none() {
718    return pin!("#BrokenNode");
719  }
720  // per-node hot path: the literal branches use the call-site-cached `pin!`
721  // (branch+load) rather than a per-call `pin_static` arena probe.
722  match node_type.unwrap() {
723    TextNode => pin!("#PCDATA"),
724    DocumentNode => pin!("#Document"),
725    CommentNode => pin!("#Comment"),
726    PiNode => pin!("#ProcessingInstruction"),
727    DTDNode => pin!("#DTD"),
728    NamespaceDecl => {
729      // match node.declared_uri() {
730      //   Some(ns) => match self.get_namespace_prefix(ns, false, true) {
731      //     Some(prefix) => s!("xmlns:")+prefix,
732      //     None => s!("xmlns")
733      //   },
734      //   None => s!("xmlns")
735      // }
736      pin!("xmlns")
737    },
738    ElementNode | AttributeNode => node.with_name(|name| {
739      // Use the actual namespace prefix from the node when available.
740      // For SVG/MathML/etc with explicit prefix, use that prefix directly.
741      node.with_namespace_prefix(|prefix| match prefix {
742        // Default namespace — use ltx: prefix. The document we build declares
743        // ltx as ITS default namespace, so an empty prefix means ltx here, and
744        // this deliberately does NOT read the namespace URI to confirm it:
745        // `Namespace::get_href` allocates a String per call, and on this path
746        // (~140 call sites, once per node and per attribute) that measured a
747        // 3.4% whole-conversion regression. A node whose DEFAULT namespace is
748        // something else can only come from a foreign document — see
749        // [`get_foreign_node_qname`], which is what reads such a tree.
750        Some("") => arena::pin_qname("ltx", name),
751        // Explicit prefix (e.g., "svg", "m") — use it
752        Some(prefix) => arena::pin_qname(prefix, name),
753        // No namespace — special cases for non-namespaced elements
754        None => match name {
755          "song" | "verse" => arena::pin(name),
756          regular => arena::pin_qname("ltx", regular),
757        },
758      })
759    }),
760    // Need others?
761    _ => {
762      // Defense-in-depth (issue #217): a node with an unexpected libxml2 type
763      // reached qname resolution. Degrade to the same `#BrokenNode` sentinel
764      // the `node_type.is_none()` arm above already returns, rather than the
765      // original hard `panic!`. LaTeXML never builds such nodes, so on a
766      // healthy tree this arm is unreachable; it exists only so a stray
767      // corrupt/foreign node can never crash qname resolution.
768      pin!("#BrokenNode")
769    },
770  }
771}
772
773/// [`get_node_qname`] for a node read out of a FOREIGN document — a tree parsed
774/// by [`crate::common::xml::parse_fragment`] rather than built by us. Used by
775/// `Document::append_tree`, the one place such a tree is ever walked.
776///
777/// The difference is confined to the DEFAULT-namespace case. Perl's single
778/// `Model::getNodeQName` always maps a namespace URI to its registered code
779/// prefix (`Common/Model.pm` → `getNamespacePrefix`), which is what gives
780/// `RegisterNamespace` (`Package.pm:2049`) its effect on absorbed content: an
781/// xhtml snippet arrives as `<p xmlns="…/1999/xhtml">`, i.e. an EMPTY libxml
782/// prefix over a non-ltx URI, and must be re-created as `xhtml:p`. Mislabelling
783/// it `ltx:p` would strip exactly the namespace the XHTML post-processor keys on
784/// (`copy-foreign` matches `xhtml:*`), silently dropping the raw HTML.
785///
786/// Splitting that off from `get_node_qname` is a pure PERFORMANCE factoring with
787/// no behavioural difference, because inside our own document an element either
788/// sits in the ltx default namespace or carries an explicit code prefix — the
789/// re-created `xhtml:p` above included. So only a foreign tree can present the
790/// ambiguous shape, and reading the URI on the shared path would cost every
791/// other caller a `String` allocation per node (measured: 3.4%).
792pub fn get_foreign_node_qname(node: &Node) -> SymStr {
793  if let Some(ns) = node.get_namespace()
794    && ns.get_prefix().is_empty()
795  {
796    let href = ns.get_href();
797    if !href.is_empty() && href != LTX_NAMESPACE {
798      // `.copied()` yields an owned SymStr, so the model guard does not outlive
799      // this expression (no borrow held across the arena pins below).
800      let registered = model!()
801        .code_namespace_prefixes
802        .get_sym(arena::pin(href.as_str()))
803        .copied();
804      // An UNREGISTERED URI keeps the historical ltx fallback, i.e. whatever
805      // `get_node_qname` would have said.
806      if let Some(code_prefix) = registered {
807        let name_str = node.get_name();
808        return arena::pin(arena::with(code_prefix, |p| prefixed_qname(p, &name_str)));
809      }
810    }
811  }
812  get_node_qname(node)
813}
814
815/// Borrow a node's qualified name (`ltx:section`, `#PCDATA`, …) as a `&str`
816/// for the duration of `caller`.
817///
818/// The closure form is the point: qnames are interned, and lending the arena's
819/// copy lets a caller compare or match on the name without the `String` that
820/// [`get_node_qname`] + `to_string` would allocate on every node of a walk.
821pub fn with_node_qname<R, FnR>(node: &Node, caller: FnR) -> R
822where FnR: FnOnce(&str) -> R {
823  let qsym = get_node_qname(node);
824  arena::with(qsym, |qname_str| caller(qname_str))
825}
826
827/// Same as get_node_qname, but using the Document namespace prefixes
828pub fn get_node_document_qname(node: &Node) -> SymStr {
829  use libxml::tree::NodeType::*;
830  let node_type = node.get_type();
831  if node_type.is_none() {
832    return pin!("#BrokenNode");
833  }
834
835  match node_type.unwrap() {
836    TextNode => pin!("#PCDATA"),
837    DocumentNode => pin!("#Document"),
838    CommentNode => pin!("#Comment"),
839    PiNode => pin!("#ProcessingInstruction"),
840    DTDNode => pin!("#DTD"),
841
842    // TODO
843    // elsif ($type == XML_NAMESPACE_DECL) {
844    //   my $ns = $node->declaredURI;
845    //   my $prefix = $ns && $self->getDocumentNamespacePrefix($ns, 0, 1);
846    //   return ($prefix ? 'xmlns:' . $prefix : 'xmlns'); }
847    NamespaceDecl => pin!("xmlns"),
848
849    ElementNode | AttributeNode => {
850      let node = node.as_readonly();
851      node.with_name(|name| node.with_namespace_href(|href| document_qname(href, name)))
852    },
853    // Need others?
854    t => {
855      panic!("Fatal:misdefined:<caller> should not ask for qualified name for node of type {t:?}")
856    },
857  }
858}
859
860/// [`get_node_document_qname`] of an element or attribute named `name` in the namespace `href`.
861pub fn document_qname(href: Option<&str>, name: &str) -> SymStr {
862  let empty_sym = pin!("");
863  let prefix = match href {
864    Some(href) if !href.is_empty() => {
865      get_document_namespace_prefix(href, false, true).unwrap_or(empty_sym)
866    },
867    _ => empty_sym,
868  };
869  if prefix == empty_sym {
870    arena::pin(name)
871  } else {
872    arena::pin(arena::with(prefix, |prefix_str| {
873      s!("{}:{}", prefix_str, name)
874    }))
875  }
876}
877
878/// Read a possibly-PREFIXED attribute off a node, resolving the prefix the same
879/// way `Document::set_attribute` does on the write side (via [`decode_qname`]).
880///
881/// libxml stores `xml:id` as local name `id` in the built-in xml namespace, and
882/// `xmlGetProp` matches on the plain name — so `get_attribute("xml:id")` finds
883/// NOTHING. That asymmetry is invisible in Rust bindings (which read ids through
884/// `get_attribute_ns`) but bites any caller that writes an attribute by qualified
885/// name and then tries to read it back by the same name, which is exactly what a
886/// script does after `generateID`.
887pub fn get_node_attribute(node: &Node, key: &str) -> Option<String> {
888  if let Some(ns_uri) = attribute_namespace(key) {
889    let local = key.split_once(':').map_or(key, |(_, l)| l);
890    if let Some(value) = node.get_attribute_ns(local, &ns_uri) {
891      return Some(value);
892    }
893  }
894  node.get_attribute(key)
895}
896
897/// Remove a possibly-PREFIXED attribute — the counterpart of
898/// [`get_node_attribute`], with the same namespace resolution.
899pub fn remove_node_attribute(node: &mut Node, key: &str) -> std::result::Result<(), String> {
900  if let Some(ns_uri) = attribute_namespace(key) {
901    let local = key.split_once(':').map_or(key, |(_, l)| l).to_string();
902    if node.get_attribute_ns(&local, &ns_uri).is_some() {
903      return node
904        .remove_attribute_ns(&local, &ns_uri)
905        .map_err(|e| e.to_string());
906    }
907  }
908  node.remove_attribute(key).map_err(|e| e.to_string())
909}
910
911/// The namespace URI an attribute name resolves to, or `None` when it is
912/// unprefixed (or its prefix is not registered). `xml:` is built in — the one
913/// prefix [`decode_qname`] deliberately hands back whole for libxml to special-case.
914fn attribute_namespace(key: &str) -> Option<String> {
915  let (prefix, _) = key.split_once(':')?;
916  if prefix == "xml" {
917    return Some(XML_NS.to_string());
918  }
919  match decode_qname(key) {
920    Ok((ns_uri, _local)) => ns_uri,
921    Err(_) => None,
922  }
923}
924
925/// Given a Qualified name, possibly prefixed with a namespace prefix,
926/// as defined by the code namespace mapping,
927/// return the NamespaceURI and localname.
928pub fn decode_qname(codetag: &str) -> Result<(Option<String>, String)> {
929  match PREFIXED_LOCALNAME_RE.captures(codetag) {
930    Some(captures) => {
931      let prefix = captures.get(1).map_or("", |m| m.as_str());
932      let localname = captures.get(2).map_or("", |m| m.as_str());
933
934      if prefix == "xml" {
935        Ok((None, codetag.to_string()))
936      } else {
937        Ok((
938          get_namespace(prefix, false)?.map(arena::to_string),
939          localname.to_string(),
940        ))
941      }
942    },
943    None => Ok((None, codetag.to_string())),
944  }
945}
946
947/// TODO: We need a proper data model to deal with the Symbol - String distinction.
948/// For now let's allocate strings and release the arena, but this is a CODE SMELL!
949pub fn decode_qname_sym(sym: SymStr) -> Result<(Option<String>, String)> {
950  let codetag = arena::to_string(sym);
951  decode_qname(&codetag)
952}
953
954//**********************************************************************
955// Document Structure Queries
956//**********************************************************************
957// NOTE: These are public, but perhaps should be passed
958// to submodel, in case it can evolve to more precision?
959// However, it would need more context to do that.
960
961/// The single faithful containment check (Perl `Common/Model.pm::canContain`),
962/// keyed on interned `SymStr` names — the arena's native currency. This is the
963/// canonical implementation; [`can_contain`] is a thin `&str` wrapper over it.
964///
965/// It is the entry point the serializer's `#PCDATA` indentation test
966/// (`Document::serialize_into`) and the digestion auto-open/close logic use, so
967/// it stays allocation-lean: the common exact-match branch interns nothing, and
968/// the negation/namespace-wildcard probes fire only when the exact child is
969/// absent from the content model.
970///
971/// The `ns:*` namespace-wildcard fallback (below) is why a FOREIGN element whose
972/// content model is a wildcard — `ltx:rawhtml`'s `xhtml:*`, `svg:*` — is handled
973/// correctly: it has no exact `tagprop` entry, so an exact-match-only check
974/// wrongly answered `can_contain(xhtml:b, #PCDATA) == false`, and the serializer
975/// then treated mixed HTML content as block and injected indentation whitespace
976/// that HTML treats as significant (`<xhtml:b>\n  bold  </xhtml:b>`).
977/// arXiv/html_feedback#680 (xworld21).
978pub fn can_contain_sym(tag: SymStr, child: SymStr) -> bool {
979  // Handle obvious cases explicitly (Perl Common/Model.pm::canContain).
980  if tag == pin!("#PCDATA") || tag == pin!("#Comment") || tag == pin!("") {
981    return false;
982  } else if tag == pin!("_WildCard_") {
983    return true;
984  }
985  // A `_Capture_` tag contains anything; a `_Capture_`/`_CaptureBlock_` child is
986  // contained by anything (with or without a namespace prefix).
987  if arena::with(tag, |t| t.ends_with("_Capture_"))
988    || arena::with(child, |c| {
989      c.ends_with("_Capture_") || c.ends_with("_CaptureBlock_")
990    })
991  {
992    return true;
993  }
994  if child == pin!("_WildCard_")
995    || child == pin!("#Comment")
996    || child == pin!("#ProcessingInstruction")
997    || child == pin!("#DTD")
998  {
999    return true;
1000  }
1001
1002  let model = model!();
1003  if model.permissive && tag == pin!("#Document") && child != pin!("#PCDATA") {
1004    return true; // No schema? Punt!
1005  }
1006
1007  // Query tag properties, falling back to the `ns:*` wildcard entry when this
1008  // exact tag has none of its own, then the most-specific-first chain — Perl
1009  // `Common/Model.pm`. The fallback is what lets a wildcard content model such
1010  // as `ltx:rawhtml{}(xhtml:*)` accept every concrete `xhtml:p`/`xhtml:b`.
1011  let frame = model.tagprop.get_sym(tag);
1012  let wildcard_frame = if frame.is_none() {
1013    namespace_wildcard_sym(tag).and_then(|w| model.tagprop.get_sym(w))
1014  } else {
1015    None
1016  };
1017  let content = &frame
1018    .or(wildcard_frame)
1019    .unwrap_or(&*DEFAULT_TAG_FRAME)
1020    .model;
1021  content.contains(&pin!("ANY")) || set_allows(content, child)
1022}
1023
1024/// `&str` wrapper over the canonical [`can_contain_sym`]; interns both names and
1025/// delegates. Kept for call sites that hold string names rather than `SymStr`.
1026pub fn can_contain(tag: &str, child: &str) -> bool {
1027  can_contain_sym(arena::pin(tag), arena::pin(child))
1028}
1029
1030/// Perl `Model::canContain`/`canHaveAttribute` fall back to the NAMESPACE
1031/// WILDCARD entry when a prefixed tag has no `tagprop` entry of its own
1032/// (`Common/Model.pm`: `if (!$model && ($tag =~ /^(\w*):/)) { $xtag = $1 . ':*' }`).
1033/// This is how a wildcard schema element such as `xhtml:*` — the content model of
1034/// `ltx:rawhtml` — governs every concrete `xhtml:p`/`xhtml:b` absorbed into it.
1035///
1036/// Two knowingly narrower details than the Perl regex, neither reachable with the
1037/// schema we compile (checked against `resources/RelaxNG/LaTeXML.model`, whose
1038/// only `ns:*` entries are `*:*` and `xhtml:*`):
1039/// * Perl falls back when the tag has no entry OR its entry has no `model` /
1040///   `attributes` key; a Rust `TagFrame` always has both, possibly empty, so the
1041///   callers fall back only when the whole frame is missing. Reaching that
1042///   difference needs a schema with BOTH an empty-set entry and a matching `ns:*`
1043///   entry — e.g. an `ltx:*`, which no LaTeXML schema declares.
1044/// * Perl's `\w*` does not match `*`, so it never derives a wildcard from a tag
1045///   that is already one; `split_once` would, but only for the `*:*` entry, which
1046///   maps to itself and is looked up only when it has no frame — and it has one.
1047fn namespace_wildcard_sym(tag: SymStr) -> Option<SymStr> {
1048  arena::with(tag, |t| t.split_once(':').map(|(ns, _)| s!("{ns}:*"))).map(|w| arena::pin(&w))
1049}
1050
1051/// Perl's most-specific-first membership chain over a `tagprop` set — shared by
1052/// `canContain`'s child test and `canHaveAttribute`'s attribute test
1053/// (`Common/Model.pm`). Order: exact, `!exact`, then for a PREFIXED key the
1054/// namespace wildcard `ns:*` / `!ns:*` and finally `*:*` / `!*:*`; for an
1055/// unprefixed key, `*` / `!*`. A `!`-prefixed entry is an explicit exclusion and
1056/// always beats the broader wildcard that follows it. The compiled model really
1057/// does carry these (e.g. `ltx:XMText{!aria:*,!xml:*,*:*,…}`), so an exact-match-only
1058/// test both over-rejects (ignoring `*:*`) and under-rejects (ignoring `!ns:*`).
1059///
1060/// Allocation profile: the exact-match branch interns nothing (the caller's
1061/// `key` is already a `SymStr`). On an exact miss we probe the broadest ALLOWING
1062/// wildcard first — a cached `pin!` for `*` / `*:*`, no allocation — and build a
1063/// `!key` / `ns:*` probe string only when it can still change the answer. So the
1064/// serializer's hot `can_contain(<block element>, #PCDATA)` query, whose model
1065/// carries no `*`, returns here having interned nothing. A probe string is looked
1066/// up, never interned ([`set_holds`]).
1067fn set_allows(set: &HashSet<SymStr>, key: SymStr) -> bool {
1068  if set.contains(&key) {
1069    return true; // exact hit — the common case, interns nothing
1070  }
1071  if set.is_empty() {
1072    return false;
1073  }
1074  // Exact miss. The unprefixed hot path (the serializer's `#PCDATA` query) can
1075  // only be turned `true` by `*`, a cached `pin!` — so a block element's model,
1076  // which has no `*`, returns here without interning any probe string.
1077  if !arena::with(key, |k| k.contains(':')) {
1078    // Unprefixed key — Perl only consults `!*` / `*`, both cached pins.
1079    if !set.contains(&pin!("*")) || set.contains(&pin!("!*")) {
1080      return false;
1081    }
1082    // `*` allows it unless an explicit `!key` excludes it — build that one probe.
1083    let negated = arena::with(key, |k| s!("!{k}"));
1084    return !set_holds(set, &negated);
1085  }
1086  // Prefixed key (cold path — the serializer never queries one). Perl order:
1087  // !key, ns:*, !ns:*, !*:*, *:*.
1088  let negated = arena::with(key, |k| s!("!{k}"));
1089  if set_holds(set, &negated) {
1090    return false;
1091  }
1092  let (ns_star, neg_ns_star) = arena::with(key, |k| {
1093    let ns = k.split_once(':').map_or("", |(ns, _)| ns);
1094    (s!("{ns}:*"), s!("!{ns}:*"))
1095  });
1096  if set_holds(set, &ns_star) {
1097    return true;
1098  }
1099  if set_holds(set, &neg_ns_star) {
1100    return false;
1101  }
1102  if set.contains(&pin!("!*:*")) {
1103    return false;
1104  }
1105  set.contains(&pin!("*:*"))
1106}
1107
1108/// Whether `set` holds the string `probe`. A string never interned cannot be in the set, so it is looked up
1109/// (`arena::get`), not pinned: a pin would keep every new probe string in the arena for good.
1110fn set_holds(set: &HashSet<SymStr>, probe: &str) -> bool {
1111  arena::get(probe).is_some_and(|sym| set.contains(&sym))
1112}
1113
1114pub fn can_have_attribute(tag: SymStr, attrib: SymStr) -> bool {
1115  // Handle obvious cases explicitly.
1116  if let Some(early_choice) = arena::with(tag, |tag_str| match tag_str {
1117    "#PCDATA" | "#Comment" | "#Document" | "#ProcessingInstruction" | "#DTD" => Some(false),
1118    "_WildCard_" => Some(true),
1119    other if other.ends_with("_Capture_") => Some(true),
1120    _ => None,
1121  }) {
1122    return early_choice;
1123  };
1124  // Perl: `return 1 if $attrib =~ /^_/;` — internal bookkeeping attributes are
1125  // always permitted, whatever the schema says about the element.
1126  if arena::with(attrib, |a| a.starts_with('_')) {
1127    return true;
1128  }
1129  let model = model!();
1130  if model.permissive {
1131    return true;
1132  }
1133
1134  // Else query tag properties, falling back to the `ns:*` wildcard entry when
1135  // this exact tag has none of its own (Perl canHaveAttribute).
1136  let frame = model.tagprop.get_sym(tag);
1137  let wildcard_frame = if frame.is_none() {
1138    namespace_wildcard_sym(tag).and_then(|w| model.tagprop.get_sym(w))
1139  } else {
1140    None
1141  };
1142  let attributes = &frame
1143    .or(wildcard_frame)
1144    .unwrap_or(&*DEFAULT_TAG_FRAME)
1145    .attributes;
1146  set_allows(attributes, attrib)
1147}
1148
1149pub fn is_node_in_schema_class(class_name: &str, tag: &Node) -> bool {
1150  let tag = get_node_qname(tag);
1151  is_in_schema_class(arena::pin(class_name), tag)
1152}
1153pub fn is_in_schema_class(class_name: SymStr, tag: SymStr) -> bool {
1154  match model!().schema_class.get_sym(class_name) {
1155    Some(class) => class.contains(&tag),
1156    _ => false,
1157  }
1158}
1159
1160//**********************************************************************
1161// Accessors
1162//**********************************************************************
1163
1164pub fn get_tags() -> Vec<SymStr> { model!().tagprop.keys().copied().collect() }
1165
1166pub fn get_tag_contents(tag: SymStr) -> Vec<SymStr> {
1167  match model!().tagprop.get_sym(tag) {
1168    Some(h) => h.model.iter().copied().collect(),
1169    None => Vec::new(),
1170  }
1171}
1172pub fn set_model(new_model: Model) {
1173  let mut model = model_mut!();
1174  *model = new_model;
1175}
1176pub fn is_permissive() -> bool { model!().permissive }
1177
1178pub fn with_schema_data<FnR, R>(caller: FnR) -> R
1179where FnR: FnOnce(Option<&Vec<SymStr>>) -> R {
1180  caller(model!().schema_data.as_ref())
1181}
1182pub fn set_schema(schema: Relaxng) {
1183  let mut model = model_mut!();
1184  model.schema = Some(schema);
1185}
1186pub fn set_schema_class(classname: &str, content: HashSet<SymStr>) {
1187  model_mut!().set_schema_class(classname, content)
1188}
1189pub fn add_tag_content(tag: &str, elements: Vec<&str>) {
1190  model_mut!().add_tag_content(tag, elements)
1191}
1192pub fn add_tag_attribute(tag: &str, attributes: Vec<&str>) {
1193  model_mut!().add_tag_attribute(tag, attributes)
1194}
1195
1196pub(crate) fn compute_indirect_model_aux(
1197  tag: SymStr,
1198  start_opt: Option<SymStr>,
1199  desirability: usize,
1200  openability: &mut SymHashMap<u32>,
1201  desc: &mut SymHashMap<SymHashMap<usize>>,
1202) {
1203  let start = match start_opt {
1204    Some(s) => s,
1205    None => pin!(""),
1206  };
1207
1208  // A bit tricky here, we need to release the model_mut!() borrow immediately, which is why we
1209  // move ownership of the tag strings into the tag_contents vector.
1210  // That leads to a bunch of .clone()s later one, but stays close to the original algorithm
1211  let tag_contents: Vec<SymStr> = get_tag_contents(tag);
1212
1213  for kid in tag_contents {
1214    // Memoise on (kid, start) to bound recursion in cyclic schemas, but
1215    // retain the *maximum* desirability observed across paths — the
1216    // outer loop in compute_indirect_model picks the highest-scoring
1217    // starting tag, so the score stored here must reflect the best path,
1218    // not the first one the hashmap iteration happened to surface.
1219    //
1220    // The prior "first visit wins" behavior (WISDOM #49) caused paralists
1221    // test-harness runs to assign `desc[#PCDATA][ltx:text] = 50` when
1222    // `contents(text)` iterated `ltx:picture` before `#PCDATA`: the
1223    // sub-recursion `text → picture → #PCDATA` inserted 50 first and the
1224    // direct `text → #PCDATA` path was skipped, forcing the auto-open
1225    // path to pick `<ltx:picture>` instead of `<ltx:text>`.
1226    let prior = desc.entry_sym(kid).or_default().get_sym(start).copied();
1227    if let Some(prior_d) = prior
1228      && prior_d >= desirability
1229    {
1230      continue;
1231    }
1232
1233    if start != pin!("") {
1234      desc
1235        .entry_sym(kid)
1236        .or_default()
1237        .insert_sym(start, desirability);
1238    }
1239
1240    if kid != pin!("#PCDATA")
1241      && let Some(priority) = openability.get_sym(kid).copied()
1242    {
1243      let inner = if start != pin!("") { start } else { kid };
1244      // Perl Document.pm L220: `$desirability * $x`. We keep integer
1245      // arithmetic (priorities scaled by 100), so this is a scaled multiply.
1246      let next_desirability = desirability * (priority as usize) / 100;
1247      compute_indirect_model_aux(kid, Some(inner), next_desirability, openability, desc);
1248    }
1249  }
1250}
1251/// Bind an OUTPUT-document prefix to a namespace URI, on the current model.
1252///
1253/// The document half of the two mappings described on
1254/// [`Model::register_namespace`] — these are the prefixes that appear in the
1255/// generated XML, and the one place `#default` is meaningful (for unprefixed
1256/// elements; never for attributes). Passing `None` unbinds the prefix.
1257pub fn register_document_namespace(docprefix: &str, namespace_opt: Option<&str>) {
1258  model_mut!().register_document_namespace(docprefix, namespace_opt)
1259}
1260
1261/// Returns all registered document namespace prefixes and their URIs.
1262pub fn get_document_namespace_prefixes() -> Vec<(String, String)> {
1263  model!()
1264    .document_namespace_prefixes
1265    .iter()
1266    .map(|(ns_sym, prefix_sym)| {
1267      let prefix = arena::with(*prefix_sym, |s| s.to_string());
1268      let ns = arena::with(*ns_sym, |s| s.to_string());
1269      (prefix, ns)
1270    })
1271    .collect()
1272}
1273
1274/// Bind a CODE prefix to a namespace URI, on the current model.
1275///
1276/// The coding half of the two mappings described on
1277/// [`Model::register_namespace`] — the prefixes constructors and bindings write,
1278/// which must be one-to-one and admit no default namespace. Passing `None`
1279/// unbinds the prefix.
1280pub fn register_namespace(codeprefix: &str, namespace_opt: Option<&str>) {
1281  model_mut!().register_namespace(codeprefix, namespace_opt)
1282}
1283
1284pub fn with_code_namespaces<FnR, R>(caller: FnR) -> R
1285where FnR: FnOnce(&SymHashMap<SymStr>) -> R {
1286  caller(&model!().code_namespaces)
1287}
1288
1289#[cfg(test)]
1290mod wildcard_resolution_tests {
1291  //! Direct coverage for the Perl `Common/Model.pm` resolution helpers shared by
1292  //! `canContain` (child test) and `canHaveAttribute` (attribute test). The
1293  //! end-to-end script-bindings guard only exercises the plain `*` branch via
1294  //! `xhtml:*`, so the negation and namespace-wildcard branches are pinned here.
1295  use super::*;
1296
1297  fn set_of(keys: &[&str]) -> HashSet<SymStr> { keys.iter().map(|k| arena::pin(*k)).collect() }
1298  // `&str` shims over the sym-native helpers under test, so the cases read the
1299  // same as the schema keys they mirror.
1300  fn allows(set: &HashSet<SymStr>, key: &str) -> bool { set_allows(set, arena::pin(key)) }
1301  fn wildcard(tag: &str) -> Option<String> {
1302    namespace_wildcard_sym(arena::pin(tag)).map(|w| arena::with(w, str::to_string))
1303  }
1304
1305  #[test]
1306  fn namespace_wildcard_tag_only_applies_to_prefixed_tags() {
1307    assert_eq!(wildcard("xhtml:p").as_deref(), Some("xhtml:*"));
1308    assert_eq!(wildcard("ltx:para").as_deref(), Some("ltx:*"));
1309    // Unprefixed names have no namespace wildcard to fall back on.
1310    assert_eq!(wildcard("para"), None);
1311    assert_eq!(wildcard("#PCDATA"), None);
1312  }
1313
1314  #[test]
1315  fn exact_membership_wins_and_empty_sets_reject() {
1316    let s = set_of(&["class", "href"]);
1317    assert!(allows(&s, "class"));
1318    assert!(!allows(&s, "style"));
1319    assert!(!allows(&HashSet::default(), "class"));
1320  }
1321
1322  #[test]
1323  fn a_negation_beats_the_wildcard_that_would_otherwise_allow_it() {
1324    // Perl order: exact, !exact, ns:*, !ns:*, !*:*, *:*  — the `!` entries are
1325    // explicit exclusions and must beat the broader wildcard that follows them.
1326    // This is the real shape of a compiled entry, e.g.
1327    // `ltx:XMText{!aria:*,!xml:*,*:*,about,…}`.
1328    let s = set_of(&["!aria:*", "!xml:*", "*:*", "about"]);
1329    assert!(allows(&s, "about"), "exact entry allows");
1330    assert!(allows(&s, "data:foo"), "*:* allows an unexcluded namespace");
1331    assert!(!allows(&s, "aria:label"), "!aria:* excludes its namespace");
1332    assert!(!allows(&s, "xml:lang"), "!xml:* excludes its namespace");
1333
1334    // An exact exclusion beats a namespace wildcard that would allow it.
1335    let s2 = set_of(&["!svg:width", "svg:*"]);
1336    assert!(allows(&s2, "svg:height"));
1337    assert!(!allows(&s2, "svg:width"));
1338
1339    // `!*:*` denies every namespaced key that is not exactly listed.
1340    let s3 = set_of(&["!*:*", "svg:width"]);
1341    assert!(allows(&s3, "svg:width"));
1342    assert!(!allows(&s3, "svg:height"));
1343  }
1344
1345  #[test]
1346  fn unprefixed_keys_use_the_bare_star_not_the_namespaced_one() {
1347    // `*:*` governs PREFIXED keys only; an unprefixed `class` needs `*`.
1348    let namespaced_only = set_of(&["*:*"]);
1349    assert!(!allows(&namespaced_only, "class"));
1350    assert!(allows(&namespaced_only, "svg:width"));
1351
1352    // This is the entry that lets attributes survive on absorbed xhtml markup:
1353    // the compiled model carries `xhtml:*{*,*:*}`.
1354    let html_wildcard = set_of(&["*", "*:*"]);
1355    assert!(allows(&html_wildcard, "class"));
1356    assert!(allows(&html_wildcard, "xlink:href"));
1357
1358    // …and `!*` denies the unprefixed ones.
1359    let denied = set_of(&["!*", "*:*"]);
1360    assert!(!allows(&denied, "class"));
1361    assert!(allows(&denied, "svg:width"));
1362
1363    // An explicit `!key` exclusion denies the key even when a bare `*` would
1364    // otherwise allow it (the `*`-present branch of the unprefixed fast path).
1365    let star_but_excluded = set_of(&["*", "!class"]);
1366    assert!(
1367      !allows(&star_but_excluded, "class"),
1368      "!class excludes despite *"
1369    );
1370    assert!(
1371      allows(&star_but_excluded, "id"),
1372      "* still allows an unexcluded name"
1373    );
1374  }
1375
1376  #[test]
1377  fn the_probes_intern_nothing() {
1378    let s = set_of(&["*", "*:*", "!svg:width"]);
1379    // (the first calls pin the call sites' cached literals, `!*` and `!*:*`)
1380    assert!(allows(&s, "warm") && allows(&s, "warm:up"));
1381    let (plain, prefixed) = (arena::pin("probe"), arena::pin("probe:prefixed"));
1382    let before = arena::len();
1383    assert!(
1384      set_allows(&s, plain),
1385      "`*` allows it, as no `!probe` exists"
1386    );
1387    assert!(set_allows(&s, prefixed), "`*:*` allows it");
1388    assert_eq!(
1389      arena::len(),
1390      before,
1391      "`!probe`, `!probe:prefixed`, `probe:*` and `!probe:*` were looked up, not pinned"
1392    );
1393  }
1394}
1395
1396#[cfg(test)]
1397mod schema_load_tests {
1398  //! #652: a raw `.rng` selected via `RelaxNGSchema()` (no compiled `.model`)
1399  //! must populate the runtime tag/attribute tables through `load_schema`, so
1400  //! the document validates instead of every element being rejected.
1401  use super::*;
1402
1403  #[test]
1404  fn raw_rng_scan_populates_tagprop_end_to_end() {
1405    // A minimal self-contained grammar, no `.model` alongside it → forces the
1406    // runtime raw-`.rng` scan path.
1407    let dir = std::env::temp_dir().join(format!("lxo652_{}", std::process::id()));
1408    std::fs::create_dir_all(&dir).expect("mkdir");
1409    let rng = "<grammar xmlns=\"http://relaxng.org/ns/structure/1.0\">\
1410       <start><ref name=\"document\"/></start>\
1411       <define name=\"document\"><element name=\"document\">\
1412         <zeroOrMore><ref name=\"para\"/></zeroOrMore></element></define>\
1413       <define name=\"para\"><element name=\"para\">\
1414         <attribute name=\"class\"/><text/></element></define>\
1415       </grammar>";
1416    std::fs::write(dir.join("lxo652schema.rng"), rng).expect("write rng");
1417
1418    initialize_model();
1419    model_mut!().set_relaxng_schema("lxo652schema");
1420    let dir_str = dir.to_str().unwrap();
1421    load_schema(&[dir_str]).expect("load_schema");
1422
1423    // Before the fix these were all false (empty tagprop) → the document was
1424    // rejected and the output emptied.
1425    assert!(
1426      can_contain("#Document", "document"),
1427      "document root must be allowed after a raw .rng scan"
1428    );
1429    assert!(can_contain("document", "para"), "document may contain para");
1430    assert!(
1431      can_have_attribute(pin!("para"), pin!("class")),
1432      "para must allow its @class"
1433    );
1434    assert!(
1435      !can_have_attribute(pin!("para"), pin!("bogus")),
1436      "para must NOT allow an undeclared attribute"
1437    );
1438
1439    let _ = std::fs::remove_dir_all(&dir);
1440  }
1441
1442  /// #652 (reopened): a schema whose target namespace is a **default `ns=`** (no
1443  /// `xmlns:` prefix — how real `LaTeXML.rng` is written) must resolve to the
1444  /// conventional code prefix (`ltx`) that `base_schema` registered, NOT a
1445  /// synthetic `namespace1`. Perl: the scanner delegates `encodeQName` to the
1446  /// model, which consults `code_namespace_prefixes`.
1447  #[test]
1448  fn default_ns_schema_uses_registered_code_prefix() {
1449    let dir = std::env::temp_dir().join(format!("lxo652def_{}", std::process::id()));
1450    std::fs::create_dir_all(&dir).expect("mkdir");
1451    // dlmf as the DEFAULT namespace; NO xmlns:ltx declaration in the schema.
1452    let default_ns = "<grammar xmlns=\"http://relaxng.org/ns/structure/1.0\" \
1453         ns=\"http://dlmf.nist.gov/LaTeXML\">\
1454       <start><ref name=\"document\"/></start>\
1455       <define name=\"document\"><element name=\"document\">\
1456         <zeroOrMore><ref name=\"para\"/></zeroOrMore></element></define>\
1457       <define name=\"para\"><element name=\"para\">\
1458         <attribute name=\"class\"/><text/></element></define>\
1459       </grammar>";
1460    std::fs::write(dir.join("lxo652def.rng"), default_ns).expect("write rng");
1461
1462    initialize_model();
1463    // Mimic base_schema.rs:11 — the engine registers `ltx` for the dlmf namespace
1464    // on every conversion, before any RelaxNGSchema() runs.
1465    model_mut!().register_namespace("ltx", Some(LTX_NAMESPACE));
1466    model_mut!().set_relaxng_schema("lxo652def");
1467    let dir_str = dir.to_str().unwrap();
1468    load_schema(&[dir_str]).expect("load_schema");
1469
1470    // The document root is in the default (dlmf) namespace → it must be reachable
1471    // under the registered `ltx` prefix, not a synthesized `namespaceN`.
1472    assert!(
1473      can_contain("#Document", "ltx:document"),
1474      "default-ns root must resolve to the registered ltx: prefix (#652)"
1475    );
1476    assert!(
1477      can_contain("ltx:document", "ltx:para"),
1478      "ltx:document may contain ltx:para"
1479    );
1480    assert!(
1481      !can_contain("#Document", "namespace1:document"),
1482      "must NOT invent a synthetic namespace1 prefix for a registered namespace (#652)"
1483    );
1484
1485    let _ = std::fs::remove_dir_all(&dir);
1486  }
1487
1488  /// #652 fallback guard: a namespace the engine did NOT register, but the
1489  /// schema declares an explicit `xmlns:` prefix for, keeps that declared prefix
1490  /// (Perl `getNamespacePrefix`: code prefix → document prefix → synthesize).
1491  #[test]
1492  fn schema_declared_prefix_survives_when_unregistered_in_code() {
1493    let dir = std::env::temp_dir().join(format!("lxo652decl_{}", std::process::id()));
1494    std::fs::create_dir_all(&dir).expect("mkdir");
1495    // `ex` is declared in the schema (xmlns:ex) but never registered in code.
1496    let rng = "<grammar xmlns=\"http://relaxng.org/ns/structure/1.0\" \
1497         ns=\"http://example.com/ex\" xmlns:ex=\"http://example.com/ex\">\
1498       <start><ref name=\"root\"/></start>\
1499       <define name=\"root\"><element name=\"root\"><empty/></element></define>\
1500       </grammar>";
1501    std::fs::write(dir.join("lxo652decl.rng"), rng).expect("write rng");
1502
1503    initialize_model();
1504    model_mut!().set_relaxng_schema("lxo652decl");
1505    load_schema(&[dir.to_str().unwrap()]).expect("load_schema");
1506
1507    assert!(
1508      can_contain("#Document", "ex:root"),
1509      "schema-declared xmlns:ex prefix must be used when code has none (#652)"
1510    );
1511    let _ = std::fs::remove_dir_all(&dir);
1512  }
1513
1514  /// #652 output-serialization: the schema's primary (default `ns=`) namespace
1515  /// becomes the DEFAULT document namespace — serialized with NO prefix — rather
1516  /// than being forgotten (Perl RelaxNG.pm L78).
1517  #[test]
1518  fn schema_primary_ns_becomes_default_document_namespace() {
1519    let dir = std::env::temp_dir().join(format!("lxo652out_{}", std::process::id()));
1520    std::fs::create_dir_all(&dir).expect("mkdir");
1521    let rng = "<grammar xmlns=\"http://relaxng.org/ns/structure/1.0\" \
1522         ns=\"http://dlmf.nist.gov/LaTeXML\">\
1523       <start><ref name=\"document\"/></start>\
1524       <define name=\"document\"><element name=\"document\"><empty/></element></define>\
1525       </grammar>";
1526    std::fs::write(dir.join("lxo652out.rng"), rng).expect("write rng");
1527
1528    initialize_model();
1529    model_mut!().register_namespace("ltx", Some(LTX_NAMESPACE));
1530    model_mut!().set_relaxng_schema("lxo652out");
1531    load_schema(&[dir.to_str().unwrap()]).expect("load_schema");
1532
1533    // The primary namespace is the output default (`#default` → dlmf) …
1534    assert_eq!(
1535      get_document_namespace("", true).as_deref(),
1536      Some(LTX_NAMESPACE),
1537      "schema primary ns must be the default document namespace (#652)"
1538    );
1539    // … so it serializes with NO prefix (probe → no synthetic namespaceN + warning).
1540    assert_eq!(
1541      get_document_namespace_prefix(LTX_NAMESPACE, false, true),
1542      None,
1543      "the default document namespace serializes without a prefix (#652)"
1544    );
1545  }
1546
1547  /// #652 foreign prefixes: a namespace registered only in CODE — a built-in
1548  /// (`svg`) or a third-party / runtime `.rhai` `RegisterNamespace` — serializes
1549  /// under that code prefix, never a synthetic `namespaceN` + warning (Perl
1550  /// Model.pm `getDocumentNamespacePrefix` L242 code-prefix fallback).
1551  #[test]
1552  fn foreign_and_runtime_namespaces_serialize_under_their_code_prefix() {
1553    initialize_model();
1554    // Built-in foreign namespace, as base_schema registers it.
1555    model_mut!().register_namespace("svg", Some("http://www.w3.org/2000/svg"));
1556    // A third-party / runtime binding's RegisterNamespace (e.g. a BookML .rhai).
1557    model_mut!().register_namespace("bk", Some("http://bookml.example/ns"));
1558
1559    assert_eq!(
1560      get_document_namespace_prefix("http://www.w3.org/2000/svg", false, true),
1561      Some(pin!("svg")),
1562      "built-in foreign svg namespace serializes under its code prefix (#652)"
1563    );
1564    assert_eq!(
1565      get_document_namespace_prefix("http://bookml.example/ns", false, true),
1566      Some(pin!("bk")),
1567      "a runtime/third-party registered namespace serializes under its prefix (#652)"
1568    );
1569  }
1570}