Skip to main content

latexml_post/mathml/
content.rs

1//! Content MathML rendering rules.
2//!
3//! Port of `LaTeXML::Post::MathML::Content` (31 lines) + the content
4//! portion of `LaTeXML::Post::MathML` (main module, ~400 lines).
5//! Converts XMath nodes to Content MathML elements (apply, ci, cn, csymbol, etc.).
6//!
7//! Content MathML aims to capture the semantic structure of math:
8//! - Variables → `m:ci`
9//! - Numbers → `m:cn` (with type: integer, float, etc.)
10//! - Known symbols → `m:csymbol` (with cd attribute)
11//! - Standard symbols → dedicated elements (`m:plus`, `m:eq`, `m:int`, etc.)
12//! - Application → `m:apply`
13//! - XMDual → follows the content branch
14
15use libxml::tree::Node;
16use rustc_hash::FxHashMap as HashMap;
17
18use crate::document::{NodeData, PostDocument, element_children};
19
20/// Well-known meaning → Content MathML element mappings.
21///
22/// Port of the Token:?:* DefMathML content entries.
23/// Also accessible via `meaning_to_cmml_element_pub` for cross-module access.
24pub(crate) fn meaning_to_cmml_element_pub(meaning: &str) -> Option<&'static str> {
25  meaning_to_cmml_element(meaning)
26}
27
28fn meaning_to_cmml_element(meaning: &str) -> Option<&'static str> {
29  match meaning {
30    // Arithmetic
31    "plus" => Some("m:plus"),
32    "minus" | "uminus" => Some("m:minus"),
33    "times" => Some("m:times"),
34    "divide" => Some("m:divide"),
35    "power" => Some("m:power"),
36    "quotient" => Some("m:quotient"),
37    "factorial" => Some("m:factorial"),
38    "remainder" => Some("m:rem"),
39    "maximum" => Some("m:max"),
40    "minimum" => Some("m:min"),
41    "gcd" => Some("m:gcd"),
42    "lcm" => Some("m:lcm"),
43    "absolute-value" => Some("m:abs"),
44    "conjugate" => Some("m:conjugate"),
45    "argument" => Some("m:arg"),
46    "real-part" => Some("m:real"),
47    "imaginary-part" => Some("m:imaginary"),
48    "floor" => Some("m:floor"),
49    "ceiling" => Some("m:ceiling"),
50    // Logic
51    "and" => Some("m:and"),
52    "or" => Some("m:or"),
53    "xor" => Some("m:xor"),
54    "not" => Some("m:not"),
55    "implies" => Some("m:implies"),
56    "forall" => Some("m:forall"),
57    "exists" => Some("m:exists"),
58    // Relations
59    "equals" => Some("m:eq"),
60    "not-equals" => Some("m:neq"),
61    "greater-than" => Some("m:gt"),
62    "less-than" => Some("m:lt"),
63    "greater-than-or-equals" => Some("m:geq"),
64    "less-than-or-equals" => Some("m:leq"),
65    "equivalent-to" => Some("m:equivalent"),
66    "approximately-equals" => Some("m:approx"),
67    "factor-of" => Some("m:factorof"),
68    // Calculus
69    "integral" => Some("m:int"),
70    "differential" => Some("m:diff"),
71    "partial-differential" => Some("m:partialdiff"),
72    "divergence" => Some("m:divergence"),
73    "gradient" => Some("m:grad"),
74    "curl" => Some("m:curl"),
75    "laplacian" => Some("m:laplacian"),
76    // Sets
77    "union" => Some("m:union"),
78    "intersection" => Some("m:intersect"),
79    "element-of" => Some("m:in"),
80    "not-element-of" => Some("m:notin"),
81    "subset-of" | "subset-of-or-equals" => Some("m:subset"),
82    "subset-of-and-not-equals" => Some("m:prsubset"),
83    "set-minus" => Some("m:setdiff"),
84    "cardinality" => Some("m:card"),
85    "cartesian-product" => Some("m:cartesianproduct"),
86    // Sequences and Series
87    "sum" => Some("m:sum"),
88    "prod" => Some("m:prod"),
89    "limit" => Some("m:limit"),
90    "tends-to" => Some("m:tendsto"),
91    // Elementary Classical Functions (trig, exp, log)
92    "exponential" => Some("m:exp"),
93    "natural-logarithm" => Some("m:ln"),
94    "logarithm" => Some("m:log"),
95    "sine" => Some("m:sin"),
96    "cosine" => Some("m:cos"),
97    "tangent" => Some("m:tan"),
98    "secant" => Some("m:sec"),
99    "cosecant" => Some("m:csc"),
100    "cotangent" => Some("m:cot"),
101    "hyperbolic-sine" => Some("m:sinh"),
102    "hyperbolic-cosine" => Some("m:cosh"),
103    "hyperbolic-tangent" => Some("m:tanh"),
104    "hyperbolic-secant" => Some("m:sech"),
105    "hyperbolic-cosecant" => Some("m:csch"),
106    "hyperbolic-cotantent" => Some("m:coth"),
107    "inverse-sine" => Some("m:arcsin"),
108    "inverse-cosine" => Some("m:arccos"),
109    "inverse-tangent" => Some("m:arctan"),
110    "inverse-secant" => Some("m:arcsec"),
111    "inverse-cosecant" => Some("m:arccsc"),
112    "inverse-cotangent" => Some("m:arccot"),
113    "inverse-hyperbolic-sine" => Some("m:arcsinh"),
114    "inverse-hyperbolic-cosine" => Some("m:arccosh"),
115    "inverse-hyperbolic-tangent" => Some("m:arctanh"),
116    "inverse-hyperbolic-secant" => Some("m:arcsech"),
117    "inverse-hyperbolic-cosecant" => Some("m:arccsch"),
118    "inverse-hyperbolic-cotangent" => Some("m:arccoth"),
119    // Statistics
120    "mean" => Some("m:mean"),
121    "standard-deviation" => Some("m:sdev"),
122    "variance" => Some("m:var"),
123    "median" => Some("m:median"),
124    "mode" => Some("m:mode"),
125    "moment" => Some("m:moment"),
126    // Linear Algebra
127    "determinant" => Some("m:determinant"),
128    "transpose" => Some("m:transpose"),
129    "selector" => Some("m:selector"),
130    "vector-product" => Some("m:vectorproduct"),
131    "scalar-product" => Some("m:scalarproduct"),
132    "outer-product" => Some("m:outerproduct"),
133    // Constants
134    "integers" => Some("m:integers"),
135    "reals" => Some("m:reals"),
136    "rationals" => Some("m:rationals"),
137    "numbers" => Some("m:naturalnumbers"),
138    "complexes" => Some("m:complexes"),
139    "primes" => Some("m:primes"),
140    "exponential-e" => Some("m:exponentiale"),
141    "imaginary-i" => Some("m:imaginaryi"),
142    "notanumber" => Some("m:notanumber"),
143    "true" => Some("m:true"),
144    "false" => Some("m:false"),
145    "empty-set" => Some("m:emptyset"),
146    "circular-pi" => Some("m:pi"),
147    "Euler-constant" => Some("m:eulergamma"),
148    "infinity" => Some("m:infinity"),
149    // Other
150    "inverse" => Some("m:inverse"),
151    "lambda" => Some("m:lambda"),
152    "compose" => Some("m:compose"),
153    "identity" => Some("m:ident"),
154    "domain" => Some("m:domain"),
155    "codomain" => Some("m:codomain"),
156    "image" => Some("m:image"),
157    "square-root" => Some("m:root"),
158    _ => None,
159  }
160}
161
162/// Convert an XMath tree to Content MathML.
163///
164/// Port of `MathML::Content::convertNode` + `cmml_top`.
165pub fn convert_to_cmml(doc: &PostDocument, xmath: &Node) -> NodeData {
166  reset_share_counter();
167  // Perl cmml_top (L1290-1300): STYLE='text' + inherited context bindings.
168  super::presentation::bind_cmml_top_context(doc, xmath);
169  CMML_DEPTH.with(|d| d.set(0));
170  CMML_PATH.with(|p| p.borrow_mut().clear());
171  cmml_contents(doc, xmath)
172}
173
174// Recursion guard. Perl uses `no warnings 'recursion'` and relies on
175// its native stack; we cap to avoid blowing the 256 MB worker stack
176// when malformed/cyclic XMath (e.g. duplicate xml:id whose target
177// loops via XMRef) drives `cmml` into unbounded descent. Two failure
178// modes seen on the second-500K canvas (stage_53/54):
179//
180// 1. Plain stack overflow on linearly-deep XMath — witnesses arXiv:1505.06709, 1505.06978 (both
181//    emitted `Info:malformed:id Duplicated attribute xml:id` then overflowed during
182//    MathML[Content]). Cap at `CMML_MAX_DEPTH` (256, well above any legitimate XMApp nesting we've
183//    measured).
184//
185// 2. Cyclic XMRef chains: an `ltx:XMRef` whose `find_node_by_id` target's subtree contains another
186//    XMRef back into an ancestor of the current cmml frame. Linear depth cap alone is not enough —
187//    each cycle iteration doubles the generated NodeData::Element subtree, exhausting the 6 GB
188//    worker memory budget long before the depth limit fires. Witness: arXiv:1508.06324 (stage_54) —
189//    440 maths, OOMs with 5-byte alloc failure mid-CMML. Track a `CMML_PATH` set of node pointers
190//    along the current recursion path; if we visit a node already on the path, return
191//    `cmml_error("cycle")` and unwind.
192const CMML_MAX_DEPTH: u32 = 256;
193thread_local! {
194  static CMML_DEPTH: std::cell::Cell<u32> = const { std::cell::Cell::new(0) };
195  static CMML_PATH: std::cell::RefCell<rustc_hash::FxHashSet<usize>>
196    = std::cell::RefCell::new(rustc_hash::FxHashSet::default());
197}
198
199enum CmmlEnter {
200  Ok,
201  DepthExceeded,
202  Cycle,
203}
204
205fn cmml_enter(node: &Node) -> CmmlEnter {
206  let ptr = node.node_ptr() as usize;
207  let in_path = CMML_PATH.with(|p| !p.borrow_mut().insert(ptr));
208  if in_path {
209    // Diagnostic: dump the current path so the math-parser bisect can see
210    // exactly which node-ids form the cycle. Behind an env so production
211    // canvas runs stay silent. Format: `cmml_cycle: <id_or_tag>(<ptr>) <-
212    // ... <- <cycling node>` — most recent ancestor first; the cycling
213    // node is repeated at the end so the loop is visually obvious.
214    if std::env::var_os("LATEXML_CMML_TRACE_CYCLE").is_some() {
215      let id = node
216        .get_attribute("xml:id")
217        .or_else(|| node.get_attribute("id"))
218        .unwrap_or_else(|| format!("({})", node.get_name()));
219      eprintln!("cmml_cycle: re-entering {} ptr=0x{:x}", id, ptr);
220    }
221    return CmmlEnter::Cycle;
222  }
223  CMML_DEPTH.with(|d| {
224    let cur = d.get();
225    if cur >= CMML_MAX_DEPTH {
226      // Pop the path entry we just inserted before returning.
227      CMML_PATH.with(|p| {
228        p.borrow_mut().remove(&ptr);
229      });
230      CmmlEnter::DepthExceeded
231    } else {
232      d.set(cur + 1);
233      CmmlEnter::Ok
234    }
235  })
236}
237
238fn cmml_exit(node: &Node) {
239  CMML_PATH.with(|p| {
240    p.borrow_mut().remove(&(node.node_ptr() as usize));
241  });
242  CMML_DEPTH.with(|d| d.set(d.get().saturating_sub(1)));
243}
244
245/// Convert the contents of a node (which normally has a single child).
246///
247/// Port of `cmml_contents`.
248fn cmml_contents(doc: &PostDocument, node: &Node) -> NodeData {
249  // A list keeps its edge phantoms beside its item (OXIDIZED_DESIGN_DIVERGENCES #1141): the item is its content.
250  if let Some(item) = latexml_core::document::item_beside_phantoms(node) {
251    return cmml(doc, &item);
252  }
253  let children = element_children(node);
254  if children.is_empty() {
255    cmml_error("missing-subexpression")
256  } else if children.len() == 1 {
257    cmml(doc, &children[0])
258  } else {
259    cmml_unparsed(doc, &children)
260  }
261}
262
263/// Core dispatch: convert a single XMath node to Content MathML.
264///
265/// Port of `cmml` + `cmml_internal`.
266fn cmml(doc: &PostDocument, node: &Node) -> NodeData {
267  match cmml_enter(node) {
268    CmmlEnter::Cycle => return cmml_error("cycle"),
269    CmmlEnter::DepthExceeded => return cmml_error("recursion-depth-exceeded"),
270    CmmlEnter::Ok => {},
271  }
272  let result = cmml_impl(doc, node);
273  cmml_exit(node);
274  result
275}
276
277fn cmml_impl(doc: &PostDocument, node: &Node) -> NodeData {
278  let tag = doc.get_qname(node).unwrap_or_default();
279
280  // Follow XMRef
281  if tag == "ltx:XMRef" {
282    if let Some(idref) = node.get_attribute("idref") {
283      if let Some(target) = doc.find_node_by_id(&idref) {
284        return cmml(doc, target);
285      }
286    }
287    return cmml_error("unresolved-reference");
288  }
289
290  match tag.as_str() {
291    "ltx:XMDual" => {
292      let children = element_children(node);
293      if !children.is_empty() {
294        cmml(doc, &children[0]) // Content branch
295      } else {
296        cmml_error("empty-dual")
297      }
298    },
299    "ltx:XMWrap" | "ltx:XMArg" => cmml_contents(doc, node),
300    "ltx:XMApp" => {
301      // Check if XMApp has a meaning (token-like application)
302      if let Some(meaning) = node.get_attribute("meaning") {
303        return cmml_token_by_meaning(&meaning, node);
304      }
305      // Check if role=ID (decorated symbol)
306      if node.with_attribute(c"role", |v| v == "ID") == Some(true) {
307        return cmml_decorated_symbol(doc, node);
308      }
309      // Normal application
310      let children = element_children(node);
311      if children.is_empty() {
312        return cmml_error("missing-operator");
313      }
314      let op = &children[0];
315      let args = &children[1..];
316
317      // Realize operator
318      let rop = if doc.is_qname(op, "ltx:XMRef") {
319        op.get_attribute("idref")
320          .and_then(|id| doc.find_node_by_id(&id).cloned())
321          .unwrap_or_else(|| op.clone())
322      } else {
323        op.clone()
324      };
325
326      let meaning = rop.get_attribute("meaning").unwrap_or_default();
327      let _role = rop.get_attribute("role").unwrap_or_default();
328
329      // Special meanings with dedicated structure
330      match meaning.as_str() {
331        // Perl `Apply:?:multirelation` cmml (L1713-1729): chained relations
332        // a<b<c become pairwise applies sharing the middle operands, under
333        // m:and when there is more than one.
334        "multirelation" if !args.is_empty() => {
335          let lhs0 = cmml(doc, &args[0]);
336          if args.len() == 1 {
337            return lhs0;
338          }
339          let mut lhs = lhs0;
340          let mut relations = Vec::new();
341          let mut i = 1;
342          while i < args.len() {
343            let rel = &args[i];
344            let Some(rhs) = args.get(i + 1) else { break };
345            relations.push(NodeData::Element {
346              tag:        "m:apply".to_string(),
347              attributes: None,
348              children:   vec![cmml(doc, rel), lhs, cmml_shared(doc, rhs)],
349            });
350            lhs = cmml_share(rhs);
351            i += 2;
352          }
353          if relations.len() > 1 {
354            let mut children = vec![NodeData::Element {
355              tag:        "m:and".to_string(),
356              attributes: None,
357              children:   vec![],
358            }];
359            children.extend(relations);
360            NodeData::Element {
361              tag: "m:apply".to_string(),
362              attributes: None,
363              children,
364            }
365          } else {
366            relations
367              .pop()
368              .unwrap_or_else(|| cmml_error("multirelation"))
369          }
370        },
371        // Perl `Apply:?:less-than-or-approximately-equals` →
372        // cmml_or_compose(['m:lt','m:approx']) (L1436-1445): each relation
373        // applied to the (shared) operands, disjoined under m:or.
374        "less-than-or-approximately-equals" if !args.is_empty() => {
375          let first: Vec<NodeData> = args.iter().map(|a| cmml_shared(doc, a)).collect();
376          let second: Vec<NodeData> = args.iter().map(cmml_share).collect();
377          let mk = |op: &str, ops: Vec<NodeData>| {
378            let mut children = vec![NodeData::Element {
379              tag:        op.to_string(),
380              attributes: None,
381              children:   vec![],
382            }];
383            children.extend(ops);
384            NodeData::Element {
385              tag: "m:apply".to_string(),
386              attributes: None,
387              children,
388            }
389          };
390          NodeData::Element {
391            tag:        "m:or".to_string(),
392            attributes: None,
393            children:   vec![mk("m:lt", first), mk("m:approx", second)],
394          }
395        },
396        "square-root" if !args.is_empty() => NodeData::Element {
397          tag:        "m:apply".to_string(),
398          attributes: None,
399          children:   vec![
400            NodeData::Element {
401              tag:        "m:root".to_string(),
402              attributes: None,
403              children:   vec![],
404            },
405            cmml(doc, &args[0]),
406          ],
407        },
408        "nth-root" if args.len() >= 2 => NodeData::Element {
409          tag:        "m:apply".to_string(),
410          attributes: None,
411          children:   vec![
412            NodeData::Element {
413              tag:        "m:root".to_string(),
414              attributes: None,
415              children:   vec![],
416            },
417            NodeData::Element {
418              tag:        "m:degree".to_string(),
419              attributes: None,
420              // Perl L1648: degree is args[0], radicand args[1] (was swapped).
421              children:   vec![cmml(doc, &args[0])],
422            },
423            cmml(doc, &args[1]),
424          ],
425        },
426        "set" => {
427          let items: Vec<NodeData> = args.iter().map(|a| cmml(doc, a)).collect();
428          NodeData::Element {
429            tag:        "m:set".to_string(),
430            attributes: None,
431            children:   items,
432          }
433        },
434        "list" => {
435          let items: Vec<NodeData> = args.iter().map(|a| cmml(doc, a)).collect();
436          NodeData::Element {
437            tag:        "m:list".to_string(),
438            attributes: None,
439            children:   items,
440          }
441        },
442        "vector" => {
443          let items: Vec<NodeData> = args.iter().map(|a| cmml(doc, a)).collect();
444          NodeData::Element {
445            tag:        "m:vector".to_string(),
446            attributes: None,
447            children:   items,
448          }
449        },
450        // Interval types
451        "open-interval" => {
452          let items: Vec<NodeData> = args.iter().map(|a| cmml(doc, a)).collect();
453          NodeData::Element {
454            tag:        "m:interval".to_string(),
455            attributes: Some(HashMap::from_iter([(
456              "closure".to_string(),
457              "open".to_string(),
458            )])),
459            children:   items,
460          }
461        },
462        "closed-interval" => {
463          let items: Vec<NodeData> = args.iter().map(|a| cmml(doc, a)).collect();
464          NodeData::Element {
465            tag:        "m:interval".to_string(),
466            attributes: Some(HashMap::from_iter([(
467              "closure".to_string(),
468              "closed".to_string(),
469            )])),
470            children:   items,
471          }
472        },
473        "closed-open-interval" => {
474          let items: Vec<NodeData> = args.iter().map(|a| cmml(doc, a)).collect();
475          NodeData::Element {
476            tag:        "m:interval".to_string(),
477            attributes: Some(HashMap::from_iter([(
478              "closure".to_string(),
479              "closed-open".to_string(),
480            )])),
481            children:   items,
482          }
483        },
484        "open-closed-interval" => {
485          let items: Vec<NodeData> = args.iter().map(|a| cmml(doc, a)).collect();
486          NodeData::Element {
487            tag:        "m:interval".to_string(),
488            attributes: Some(HashMap::from_iter([(
489              "closure".to_string(),
490              "open-closed".to_string(),
491            )])),
492            children:   items,
493          }
494        },
495        // Complement operations: reverse argument order
496        "contains" | "superset-of" | "superset-of-or-equals" | "superset-of-and-not-equals" => {
497          let cmml_op = match meaning.as_str() {
498            "contains" => "m:in",
499            "superset-of" | "superset-of-or-equals" => "m:subset",
500            "superset-of-and-not-equals" => "m:prsubset",
501            _ => "m:subset",
502          };
503          let mut reversed_args: Vec<NodeData> = args.iter().rev().map(|a| cmml(doc, a)).collect();
504          reversed_args.insert(0, NodeData::Element {
505            tag:        cmml_op.to_string(),
506            attributes: None,
507            children:   vec![],
508          });
509          NodeData::Element {
510            tag:        "m:apply".to_string(),
511            attributes: None,
512            children:   reversed_args,
513          }
514        },
515        // Not-contains: not(in(reversed))
516        "not-contains" => {
517          let mut reversed_args: Vec<NodeData> = args.iter().rev().map(|a| cmml(doc, a)).collect();
518          reversed_args.insert(0, NodeData::Element {
519            tag:        "m:notin".to_string(),
520            attributes: None,
521            children:   vec![],
522          });
523          NodeData::Element {
524            tag:        "m:apply".to_string(),
525            attributes: None,
526            children:   reversed_args,
527          }
528        },
529        // Not-approximately-equals: not(approx(args))
530        "not-approximately-equals" => {
531          let inner_args: Vec<NodeData> = args.iter().map(|a| cmml(doc, a)).collect();
532          let mut apply_children = vec![NodeData::Element {
533            tag:        "m:approx".to_string(),
534            attributes: None,
535            children:   vec![],
536          }];
537          apply_children.extend(inner_args);
538          NodeData::Element {
539            tag:        "m:apply".to_string(),
540            attributes: None,
541            children:   vec![
542              NodeData::Element {
543                tag:        "m:not".to_string(),
544                attributes: None,
545                children:   vec![],
546              },
547              NodeData::Element {
548                tag:        "m:apply".to_string(),
549                attributes: None,
550                children:   apply_children,
551              },
552            ],
553          }
554        },
555        // Hack for definite integrals with explicit limits
556        "hack-definite-integral" if args.len() >= 4 => NodeData::Element {
557          tag:        "m:apply".to_string(),
558          attributes: None,
559          children:   vec![
560            NodeData::Element {
561              tag:        "m:int".to_string(),
562              attributes: None,
563              children:   vec![],
564            },
565            NodeData::Element {
566              tag:        "m:bvar".to_string(),
567              attributes: None,
568              children:   vec![cmml(doc, &args[3])],
569            },
570            NodeData::Element {
571              tag:        "m:lowlimit".to_string(),
572              attributes: None,
573              children:   vec![cmml(doc, &args[0])],
574            },
575            NodeData::Element {
576              tag:        "m:uplimit".to_string(),
577              attributes: None,
578              children:   vec![cmml(doc, &args[1])],
579            },
580            cmml(doc, &args[2]),
581          ],
582        },
583        // Formulae: sequence of expressions
584        "formulae" => {
585          let items: Vec<NodeData> = args.iter().map(|a| cmml(doc, a)).collect();
586          let mut children = vec![NodeData::Element {
587            tag:        "m:csymbol".to_string(),
588            attributes: Some(HashMap::from_iter([(
589              "cd".to_string(),
590              "ambiguous".to_string(),
591            )])),
592            children:   vec![NodeData::Text("formulae-sequence".to_string())],
593          }];
594          children.extend(items);
595          NodeData::Element {
596            tag: "m:apply".to_string(),
597            attributes: None,
598            children,
599          }
600        },
601        _ => {
602          // Generic application: <m:apply> op args... </m:apply>
603          let mut apply_children = vec![cmml(doc, op)];
604          apply_children.extend(args.iter().map(|a| cmml(doc, a)));
605          NodeData::Element {
606            tag:        "m:apply".to_string(),
607            attributes: None,
608            children:   apply_children,
609          }
610        },
611      }
612    },
613    "ltx:XMTok" => cmml_leaf(doc, node),
614    "ltx:XMHint" => {
615      // Hints are ignored in Content MathML
616      NodeData::Text(String::new())
617    },
618    "ltx:XMArray" => cmml_array(doc, node),
619    "ltx:XMText" => cmml_decorated_symbol(doc, node),
620    _ => cmml_decorated_symbol(doc, node),
621  }
622}
623
624/// Convert an XMTok to a Content MathML leaf element.
625///
626/// Port of `cmml_leaf`.
627fn cmml_leaf(_doc: &PostDocument, node: &Node) -> NodeData {
628  let meaning = node.get_attribute("meaning");
629  let role = node.get_attribute("role").unwrap_or_default();
630
631  if let Some(ref m) = meaning {
632    // Known meaning → check for dedicated MathML element
633    if let Some(element_name) = meaning_to_cmml_element(m) {
634      return NodeData::Element {
635        tag:        element_name.to_string(),
636        attributes: None,
637        children:   vec![],
638      };
639    }
640
641    // Has omcd → csymbol with cd
642    if let Some(cd) = node.get_attribute("omcd") {
643      return NodeData::Element {
644        tag:        "m:csymbol".to_string(),
645        attributes: Some(HashMap::from_iter([("cd".to_string(), cd)])),
646        children:   vec![NodeData::Text(m.clone())],
647      };
648    }
649
650    // Number with meaning
651    if role == "NUMBER" {
652      // Perl /^[+-]?\d+$/ — arbitrary-length integers, unlike i64::parse.
653      let cn_type = if is_perl_integer(m) {
654        "integer"
655      } else {
656        "float"
657      };
658      return NodeData::Element {
659        tag:        "m:cn".to_string(),
660        attributes: Some(HashMap::from_iter([(
661          "type".to_string(),
662          cn_type.to_string(),
663        )])),
664        children:   vec![NodeData::Text(m.clone())],
665      };
666    }
667
668    // Default: csymbol with latexml cd
669    return NodeData::Element {
670      tag:        "m:csymbol".to_string(),
671      attributes: Some(HashMap::from_iter([(
672        "cd".to_string(),
673        "latexml".to_string(),
674      )])),
675      children:   vec![NodeData::Text(m.clone())],
676    };
677  }
678
679  // No meaning: variable or number
680  let content = node.get_content();
681  match role.as_str() {
682    "NUMBER" => {
683      let cn_type = if is_perl_integer(&content) {
684        "integer"
685      } else {
686        "float"
687      };
688      NodeData::Element {
689        tag:        "m:cn".to_string(),
690        attributes: Some(HashMap::from_iter([(
691          "type".to_string(),
692          cn_type.to_string(),
693        )])),
694        children:   vec![NodeData::Text(content)],
695      }
696    },
697    "SUPERSCRIPTOP" => NodeData::Element {
698      tag:        "m:csymbol".to_string(),
699      attributes: Some(HashMap::from_iter([(
700        "cd".to_string(),
701        "ambiguous".to_string(),
702      )])),
703      children:   vec![NodeData::Text("superscript".to_string())],
704    },
705    "SUBSCRIPTOP" => NodeData::Element {
706      tag:        "m:csymbol".to_string(),
707      attributes: Some(HashMap::from_iter([(
708        "cd".to_string(),
709        "ambiguous".to_string(),
710      )])),
711      children:   vec![NodeData::Text("subscript".to_string())],
712    },
713    _ => {
714      // Variable / identifier (Perl cmml_leaf L1388-1391: stylized ci).
715      let name = if content.is_empty() {
716        node
717          .get_attribute("name")
718          .unwrap_or_else(|| "?".to_string())
719      } else {
720        content
721      };
722      NodeData::Element {
723        tag:        "m:ci".to_string(),
724        attributes: None,
725        children:   vec![NodeData::Text(stylize_ci_content(node, name))],
726      }
727    },
728  }
729}
730
731/// Convert a token by its meaning attribute (for XMApp with meaning).
732fn cmml_token_by_meaning(meaning: &str, _node: &Node) -> NodeData {
733  if let Some(element_name) = meaning_to_cmml_element(meaning) {
734    NodeData::Element {
735      tag:        element_name.to_string(),
736      attributes: None,
737      children:   vec![],
738    }
739  } else {
740    NodeData::Element {
741      tag:        "m:csymbol".to_string(),
742      attributes: Some(HashMap::from_iter([(
743        "cd".to_string(),
744        "latexml".to_string(),
745      )])),
746      children:   vec![NodeData::Text(meaning.to_string())],
747    }
748  }
749}
750
751// Per-formula counter for generated share ids (Perl uses the document
752// idcache to find the next free `sh<n>`; ancestor-id scoping makes a
753// per-formula counter equivalent). Reset by `convert_to_cmml`.
754thread_local! {
755  static SH_COUNTER: std::cell::Cell<u32> = const { std::cell::Cell::new(0) };
756  /// Uniquifies share ids minted on formulas with no ancestor xml:id, across one document: Perl's
757  /// `generateNodeID` probes the document's idcache (Post.pm:1475-1493), so the scope is the document. Reset by
758  /// [`reset_document_share_counter`] (a persistent worker's next document starts from `sh1`, as the CLI's does).
759  static SH_GLOBAL_COUNTER: std::cell::Cell<u32> = const { std::cell::Cell::new(0) };
760}
761pub(super) fn reset_share_counter() { SH_COUNTER.with(|c| c.set(0)); }
762/// Each document's ancestor-less share ids count from one again (`MathML::process`, once per document).
763pub(super) fn reset_document_share_counter() { SH_GLOBAL_COUNTER.with(|c| c.set(0)); }
764
765/// Port of Perl `generateNodeID` + `cmml_shared` (MathML.pm L1420-1424,
766/// Post.pm generateNodeID): make sure the XMath node has an xml:id (and a
767/// fragid mirroring its ancestor's) so it can be shared, then convert.
768fn cmml_shared(doc: &PostDocument, node: &Node) -> NodeData {
769  if crate::document::get_xml_id(node).is_none() {
770    // Closest ancestor with an id (Perl walks parentNode chain).
771    // NB xml:id is namespaced — always read via get_xml_id (WISDOM).
772    let mut parent = node.get_parent();
773    while let Some(ref p) = parent {
774      if crate::document::get_xml_id(p).is_some() {
775        break;
776      }
777      parent = p.get_parent();
778    }
779    let pid = parent
780      .as_ref()
781      .and_then(crate::document::get_xml_id)
782      .map(|id| format!("{id}."))
783      .unwrap_or_default();
784    // With an ancestor id the per-formula counter is unique (ancestor ids are
785    // unique per formula). WITHOUT one, a per-formula counter would mint the
786    // same bare `sh1` in every such formula — use the monotonic per-thread
787    // counter instead so ids stay document-unique. (Perl probes the document
788    // idcache to the same effect; our minted ids are href targets only and
789    // are not idcache-registered — the counter guarantees no collision.)
790    let n = if pid.is_empty() {
791      SH_GLOBAL_COUNTER.with(|c| {
792        let v = c.get() + 1;
793        c.set(v);
794        v
795      })
796    } else {
797      SH_COUNTER.with(|c| {
798        let v = c.get() + 1;
799        c.set(v);
800        v
801      })
802    };
803    let mut handle = node.clone();
804    handle.set_attribute("xml:id", &format!("{pid}sh{n}")).ok();
805    if let Some(pfragid) = parent.as_ref().and_then(|p| p.get_attribute("fragid")) {
806      handle
807        .set_attribute("fragid", &format!("{pfragid}.sh{n}"))
808        .ok();
809    }
810  }
811  cmml(doc, node)
812}
813
814/// Port of Perl `cmml_share` (L1426-1434): reference a shared operand.
815fn cmml_share(node: &Node) -> NodeData {
816  if let Some(fragid) = node.get_attribute("fragid") {
817    // NB Perl appends $MATHPROCESSOR->IDSuffix; our cmml runs with the
818    // primary suffix '' (parallel-markup suffix wiring is an audit residual).
819    NodeData::Element {
820      tag:        "m:share".to_string(),
821      attributes: Some(HashMap::from_iter([(
822        "href".to_string(),
823        format!("#{fragid}"),
824      )])),
825      children:   vec![],
826    }
827  } else {
828    crate::Warn!(
829      "expected",
830      "fragid",
831      "Shared node is missing fragid (multirelation/or-compose share)"
832    );
833    NodeData::Element {
834      tag:        "m:share".to_string(),
835      attributes: None,
836      children:   vec![],
837    }
838  }
839}
840
841/// Perl integer test `/^[+-]?\d+$/` (arbitrary length, unlike i64::parse).
842fn is_perl_integer(s: &str) -> bool {
843  let digits = s.strip_prefix(['+', '-']).unwrap_or(s);
844  !digits.is_empty() && digits.bytes().all(|b| b.is_ascii_digit())
845}
846
847/// The identifier-content half of Perl `stylizeContent($item, 'm:ci')`
848/// (cmml_leaf L1388-1391): font → mathvariant → plane1 unicode conversion;
849/// a variant that could not be baked into characters prefixes the content
850/// ("bold-x"). This is why Perl's cmml says `<ci>𝑥</ci>`, not `<ci>x</ci>`.
851fn stylize_ci_content(node: &Node, text: String) -> String {
852  // Perl L747-748: Format-only content (invisible operators) gets no
853  // styling — never "bold-⁢".
854  if text.chars().all(|c| {
855    matches!(c,
856      '\u{00AD}' | '\u{200B}'..='\u{200F}' | '\u{2060}'..='\u{2064}' | '\u{FEFF}')
857  }) {
858    return text;
859  }
860  // Perl stylizeContent L678: token font, else the inherited context font.
861  let Some(font) = node
862    .get_attribute("font")
863    .or_else(super::presentation::ctx_font)
864  else {
865    return text;
866  };
867  let variant = crate::unicode::unicode_mathvariant(&font);
868  if variant.is_empty() || variant == "normal" {
869    return text;
870  }
871  if let Some(u) = crate::unicode::unicode_convert(&text, variant)
872    && !u.is_empty()
873  {
874    return u;
875  }
876  format!("{variant}-{text}")
877}
878
879/// Convert a "decorated symbol" — an XMApp with role=ID treated as a ci.
880///
881/// Port of `cmml_decoratedSymbol` (L1396-1404): with a meaning it is a
882/// csymbol (cd from omcd, default latexml); otherwise a ci whose content is
883/// the node's PRESENTATION conversion.
884fn cmml_decorated_symbol(doc: &PostDocument, node: &Node) -> NodeData {
885  if let Some(meaning) = node.get_attribute("meaning") {
886    let cd = node
887      .get_attribute("omcd")
888      .unwrap_or_else(|| "latexml".to_string());
889    return NodeData::Element {
890      tag:        "m:csymbol".to_string(),
891      attributes: Some(HashMap::from_iter([("cd".to_string(), cd)])),
892      children:   vec![NodeData::Text(meaning)],
893    };
894  }
895  NodeData::Element {
896    tag:        "m:ci".to_string(),
897    attributes: None,
898    children:   vec![super::presentation::pmml_for_ci(doc, node)],
899  }
900}
901
902/// Convert an XMArray to Content MathML.
903///
904/// Port of `Array:?:cases` DefMathML content handler.
905fn cmml_array(doc: &PostDocument, node: &Node) -> NodeData {
906  let meaning = node.get_attribute("meaning").unwrap_or_default();
907
908  if meaning == "cases" {
909    // Piecewise construct
910    let mut pieces = Vec::new();
911    let mut otherwises = Vec::new();
912
913    for row in element_children(node) {
914      let items = element_children(&row);
915      if items.is_empty() {
916        continue;
917      }
918      if items.len() == 1 {
919        otherwises.push(cmml_contents(doc, &items[0]));
920      } else if items[1].get_content().contains("otherwise") {
921        otherwises.push(cmml_contents(doc, &items[0]));
922      } else {
923        pieces.push(NodeData::Element {
924          tag:        "m:piece".to_string(),
925          attributes: None,
926          children:   vec![cmml_contents(doc, &items[0]), cmml_contents(doc, &items[1])],
927        });
928      }
929    }
930
931    if let Some(ow) = otherwises.into_iter().next() {
932      pieces.push(NodeData::Element {
933        tag:        "m:otherwise".to_string(),
934        attributes: None,
935        children:   vec![ow],
936      });
937    }
938
939    NodeData::Element {
940      tag:        "m:piecewise".to_string(),
941      attributes: None,
942      children:   pieces,
943    }
944  } else {
945    // Generic array → matrix-like structure
946    let mut rows = Vec::new();
947    for row in element_children(node) {
948      let cells: Vec<NodeData> = element_children(&row)
949        .iter()
950        .map(|cell| cmml_contents(doc, cell))
951        .collect();
952      rows.push(NodeData::Element {
953        tag:        "m:matrixrow".to_string(),
954        attributes: None,
955        children:   cells,
956      });
957    }
958    NodeData::Element {
959      tag:        "m:matrix".to_string(),
960      attributes: None,
961      children:   rows,
962    }
963  }
964}
965
966/// Convert unparsed (multiple) nodes to Content MathML error.
967///
968/// Port of `cmml_unparsed`.
969fn cmml_unparsed(doc: &PostDocument, nodes: &[Node]) -> NodeData {
970  let mut results = vec![NodeData::Element {
971    tag:        "m:csymbol".to_string(),
972    attributes: Some(HashMap::from_iter([(
973      "cd".to_string(),
974      "ambiguous".to_string(),
975    )])),
976    children:   vec![NodeData::Text("fragments".to_string())],
977  }];
978
979  for node in nodes {
980    let tag = doc.get_qname(node).unwrap_or_default();
981    if tag == "ltx:XMTok" && node.with_attribute(c"role", |v| v == "UNKNOWN") == Some(true) {
982      results.push(NodeData::Element {
983        tag:        "m:csymbol".to_string(),
984        attributes: Some(HashMap::from_iter([(
985          "cd".to_string(),
986          "unknown".to_string(),
987        )])),
988        children:   vec![NodeData::Text(node.get_content())],
989      });
990    } else {
991      results.push(cmml(doc, node));
992    }
993  }
994
995  NodeData::Element {
996    tag:        "m:cerror".to_string(),
997    attributes: None,
998    children:   results,
999  }
1000}
1001
1002/// Create a Content MathML error element.
1003fn cmml_error(symbol: &str) -> NodeData {
1004  NodeData::Element {
1005    tag:        "m:cerror".to_string(),
1006    attributes: None,
1007    children:   vec![NodeData::Element {
1008      tag:        "m:csymbol".to_string(),
1009      attributes: Some(HashMap::from_iter([(
1010        "cd".to_string(),
1011        "ambiguous".to_string(),
1012      )])),
1013      children:   vec![NodeData::Text(symbol.to_string())],
1014    }],
1015  }
1016}