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
25pub 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());
34static 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 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
88pub(crate) fn force_init() { let _ = &*MODEL; }
98
99impl Model {
100 pub fn new() -> Self {
101 let mut model = Model::default();
102 model.register_namespace("xml", Some(XML_NS));
104 model.register_document_namespace("xml", Some(XML_NS));
105 model
106 }
107 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 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 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 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 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 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 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 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 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 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 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 Warn!("expected", "<model>", "TODO");
396 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")); 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 } 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 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 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 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 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 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 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 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
631pub fn get_namespace_prefix(namespace: &str, _forattribute: bool, probe: bool) -> Option<SymStr> {
639 if probe {
640 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 docprefix.is_some() && !model.code_namespaces.contains_key_sym(docprefix.unwrap()) {
657 codeprefix = docprefix.copied();
658 }
659 }
660 } else {
661 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 }
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#[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
707pub fn get_node_qname(node: &Node) -> SymStr { get_ro_node_qname(node.as_readonly()) }
711
712pub 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 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 pin!("xmlns")
737 },
738 ElementNode | AttributeNode => node.with_name(|name| {
739 node.with_namespace_prefix(|prefix| match prefix {
742 Some("") => arena::pin_qname("ltx", name),
751 Some(prefix) => arena::pin_qname(prefix, name),
753 None => match name {
755 "song" | "verse" => arena::pin(name),
756 regular => arena::pin_qname("ltx", regular),
757 },
758 })
759 }),
760 _ => {
762 pin!("#BrokenNode")
769 },
770 }
771}
772
773pub 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 let registered = model!()
801 .code_namespace_prefixes
802 .get_sym(arena::pin(href.as_str()))
803 .copied();
804 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
815pub 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
827pub 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 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 t => {
855 panic!("Fatal:misdefined:<caller> should not ask for qualified name for node of type {t:?}")
856 },
857 }
858}
859
860pub 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
878pub 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
897pub 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
911fn 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
925pub 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
947pub fn decode_qname_sym(sym: SymStr) -> Result<(Option<String>, String)> {
950 let codetag = arena::to_string(sym);
951 decode_qname(&codetag)
952}
953
954pub fn can_contain_sym(tag: SymStr, child: SymStr) -> bool {
979 if tag == pin!("#PCDATA") || tag == pin!("#Comment") || tag == pin!("") {
981 return false;
982 } else if tag == pin!("_WildCard_") {
983 return true;
984 }
985 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; }
1006
1007 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
1024pub fn can_contain(tag: &str, child: &str) -> bool {
1027 can_contain_sym(arena::pin(tag), arena::pin(child))
1028}
1029
1030fn 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
1051fn set_allows(set: &HashSet<SymStr>, key: SymStr) -> bool {
1068 if set.contains(&key) {
1069 return true; }
1071 if set.is_empty() {
1072 return false;
1073 }
1074 if !arena::with(key, |k| k.contains(':')) {
1078 if !set.contains(&pin!("*")) || set.contains(&pin!("!*")) {
1080 return false;
1081 }
1082 let negated = arena::with(key, |k| s!("!{k}"));
1084 return !set_holds(set, &negated);
1085 }
1086 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
1108fn 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 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 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 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
1160pub 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 let tag_contents: Vec<SymStr> = get_tag_contents(tag);
1212
1213 for kid in tag_contents {
1214 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 let next_desirability = desirability * (priority as usize) / 100;
1247 compute_indirect_model_aux(kid, Some(inner), next_desirability, openability, desc);
1248 }
1249 }
1250}
1251pub fn register_document_namespace(docprefix: &str, namespace_opt: Option<&str>) {
1258 model_mut!().register_document_namespace(docprefix, namespace_opt)
1259}
1260
1261pub 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
1274pub 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 use super::*;
1296
1297 fn set_of(keys: &[&str]) -> HashSet<SymStr> { keys.iter().map(|k| arena::pin(*k)).collect() }
1298 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 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 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 let s2 = set_of(&["!svg:width", "svg:*"]);
1336 assert!(allows(&s2, "svg:height"));
1337 assert!(!allows(&s2, "svg:width"));
1338
1339 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 let namespaced_only = set_of(&["*:*"]);
1349 assert!(!allows(&namespaced_only, "class"));
1350 assert!(allows(&namespaced_only, "svg:width"));
1351
1352 let html_wildcard = set_of(&["*", "*:*"]);
1355 assert!(allows(&html_wildcard, "class"));
1356 assert!(allows(&html_wildcard, "xlink:href"));
1357
1358 let denied = set_of(&["!*", "*:*"]);
1360 assert!(!allows(&denied, "class"));
1361 assert!(allows(&denied, "svg:width"));
1362
1363 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 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 use super::*;
1402
1403 #[test]
1404 fn raw_rng_scan_populates_tagprop_end_to_end() {
1405 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 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 #[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 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 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 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 #[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 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 #[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 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 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 #[test]
1552 fn foreign_and_runtime_namespaces_serialize_under_their_code_prefix() {
1553 initialize_model();
1554 model_mut!().register_namespace("svg", Some("http://www.w3.org/2000/svg"));
1556 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}