lib/LaTeXML/MathParser.pm untested

filter: Statementstmt 0.0% 0 / 986 Branchbran 0.0% 0 / 482 Conditioncond 0.0% 0 / 332 MC/DCmcdc n/a Subroutinesub 0.0% 0 / 76 Podpod 0.0% 0 / 64 totaltotal 0.0% 0 / 1940 CC 242 SCAR 46.0
CC
242
Cov
0%
filter_hints
380.0
NewScript
306.0
parse_rec
272.0
CRAP 99.8
1 # /=====================================================================\ #
2 # | LaTeXML::MathParser | #
3 # | Parse Math | #
4 # |=====================================================================| #
5 # | Part of LaTeXML: | #
6 # | Public domain software, produced as part of work done by the | #
7 # | United States Government & not subject to copyright in the US. | #
8 # |---------------------------------------------------------------------| #
9 # | Bruce Miller <bruce.miller@nist.gov> #_# | #
10 # | http://dlmf.nist.gov/LaTeXML/ (o o) | #
11 # \=========================================================ooo==U==ooo=/ #
12 # ================================================================================
13 # LaTeXML::MathParser Math Parser for LaTeXML using Parse::RecDescent.
14 # Parse the intermediate representation generated by the TeX processor.
15 # ================================================================================
16 package LaTeXML::MathParser;
17 use strict;
18 use warnings;
19 use Parse::RecDescent;
20 use LaTeXML::Global;
21 use LaTeXML::Common::Object;
22 use LaTeXML::Common::Error;
23 use LaTeXML::Core::Token;
24 use LaTeXML::Common::Font;
25 use LaTeXML::Common::XML;
26 use List::Util qw(min max);
27 use base (qw(Exporter));
28  
29 our @EXPORT_OK = (qw(&Lookup &New &Absent &Apply &ApplyNary &recApply &CatSymbols
30 &Annotate &InvisibleTimes &InvisibleComma
31 &TwoPartRelop &NewFormulae &NewFormula &NewList
32 &ApplyDelimited &NewScript &DecorateOperator &InterpretDelimited &NewEvalAt
33 &LeftRec
34 &Arg &MaybeFunction
35 &SawNotation &IsNotationAllowed
36 &isMatchingClose &Fence));
37 our %EXPORT_TAGS = (constructors
38 => [qw(&Lookup &New &Absent &Apply &ApplyNary &recApply &CatSymbols
39 &Annotate &InvisibleTimes &InvisibleComma
40 &TwoPartRelop &NewFormulae &NewFormula &NewList
41 &ApplyDelimited &NewScript &DecorateOperator &InterpretDelimited &NewEvalAt
42 &LeftRec
43 &Arg &MaybeFunction
44 &SawNotation &IsNotationAllowed
45 &isMatchingClose &Fence)]);
46  
47 DebuggableFeature('recdescent', "Trace Parse::RecDescent");
48 our $MATHPARSE_PROGRESS_QUANTUM = 100;
49  
50 # ================================================================================
51 sub new {
52 my ($class, %options) = @_;
53 require LaTeXML::MathGrammar;
54  
55 my $internalparser = LaTeXML::MathGrammar->new();
56 Fatal("expected", "MathGrammar", undef,
57 "Compilation of Math Parser grammar failed") unless $internalparser;
58 my $self = bless { internalparser => $internalparser, lexematize => $options{lexematize} }, $class;
59 return $self; }
60  
61 sub parseMath {
62 my ($self, $document, %options) = @_;
63 local $LaTeXML::MathParser::DOCUMENT = $document;
64 $self->clear; # Not reentrant!
65 $self->cleanupScripts($document);
66 if (my @math = $document->findnodes('descendant-or-self::ltx:XMath[not(ancestor::ltx:XMath)]')) {
67 my $proc = "Math Parsing " . scalar(@math) . " formulae ...";
68 ProgressSpinup($proc);
69 #### SEGFAULT TEST
70 #### $document->doctest("before parse",1);
71 foreach my $math (@math) {
72 $self->parse($math, $document); }
73 ProgressSpindown($proc);
74  
75 NoteLog("Math parsing succeeded:"
76 . join('', map { "\n $_: "
77 . colorizeString($$self{passed}{$_} . "/" . ($$self{passed}{$_} + $$self{failed}{$_}), ($$self{failed}{$_} == 0 ? 'success' : 'warning')) }
78 grep { $$self{passed}{$_} + $$self{failed}{$_} }
79 keys %{ $$self{passed} }));
80 if (my @unk = keys %{ $$self{unknowns} }) {
81 NoteLog("Symbols assumed as simple identifiers (with # of occurences):\n "
82 . join(', ', map { "'" . colorizeString("$_", 'warning') . "' ($$self{unknowns}{$_})" } sort @unk));
83 if (!$STATE->lookupValue('MATHPARSER_SPECULATE')) {
84 NoteLog("Set MATHPARSER_SPECULATE to speculate on possible notations."); } }
85 if (my @funcs = keys %{ $$self{maybe_functions} }) {
86 NoteLog("Possibly used as functions?\n "
87 . join(', ', map { "'$_' ($$self{maybe_functions}{$_}/$$self{unknowns}{$_} usages)" }
88 sort @funcs)); }
89 }
90 #### SEGFAULT TEST
91 #### $document->doctest("IN scope",1);
92 #### SEGFAULT TEST
93 #### $document->doctest("OUT of scope",1);
94 return $document; }
95  
96 # This is a rather peculiar cleanup that needs to be done to manage ids & idrefs
97 # Before parsing, sub/superscripts are represented by an operator-less XMApp with the script
98 # itself as the only child. Ideally, upon parsing these get merged, combined and disappear into
99 # proper XMApp of an appropriate operator on the base and scripts. Unless there is a parse
100 # failure, in which case they remain.
101 # The problem comes from various XMDual constructs where an XMRef refers to the script XMApp.
102 # It can occur that one branch parses and the other fails: This can leave a reference to
103 # the script XMApp which no longer exists!
104 # To solve this, we find & replace all references to such script XMApps by an explicit XMApp
105 # with the XMRef refering to the script itself, not the XMApp. (make sense?)
106 sub cleanupScripts {
107 my ($self, $document) = @_;
108 foreach my $app ($document->findnodes(
109 'descendant-or-self::ltx:XMApp[@xml:id and contains(@role,"SCRIPT")]')) {
110 my $role = $app->getAttribute('role');
111 my $appid = $app->getAttribute('xml:id');
112 if ($role =~ /^(?:PRE|POST|FLOAT)(:?SUB|SUPER)SCRIPT$/) {
113 my @refs = $document->findnodes("descendant-or-self::ltx:XMRef[\@idref = '$appid']");
114 if (scalar(@refs)) {
115 my $script = $app->firstChild;
116 my ($scriptref) = LaTeXML::Package::createXMRefs($document, $script);
117 $document->unRecordID($appid); # no longer refers to the app
118 $app->removeAttribute('xml:id');
119 # Copy all attributes, EXCEPT xml:id
120 my %attr = map { (getQName($_) => $_->getValue) }
121 grep { $_->nodeType == XML_ATTRIBUTE_NODE } $app->attributes;
122 # Now, replace each ref to the script application by an application to a ref to the script.
123 foreach my $ref (@refs) {
124 $document->replaceTree(['ltx:XMApp', {%attr}, $scriptref], $ref); }
125 } } }
126 return; }
127  
128 sub getQName {
129 my ($node) = @_;
130 if (ref $node eq 'ARRAY') {
131 return $$node[0]; }
132 else {
133 return $LaTeXML::MathParser::DOCUMENT->getModel->getNodeQName($node); } }
134  
135 sub realizeXMNode {
136 my ($node) = @_;
137 my $doc = $LaTeXML::MathParser::DOCUMENT;
138 my $idref;
139 if (!defined $node) {
140 return; }
141 elsif (ref $node eq 'ARRAY') {
142 $idref = $$node[1]{idref} if $$node[0] eq 'ltx:XMRef'; }
143 elsif (ref $node eq 'XML::LibXML::Element') {
144 $idref = $node->getAttribute('idref')
145 if $doc->getModel->getNodeQName($node) eq 'ltx:XMRef'; }
146 if ($idref) {
147 # Can it happen that $realnode is, itself, an XMRef? Then we should recurse!
148 if (my $realnode = $doc->lookupID($idref)) {
149 return $realnode; }
150 else {
151 Error("expected", 'id', undef, "Cannot find a node with xml:id='$idref'",
152 ($LaTeXML::MathParser::IDREFS{$idref}
153 ? "Previously bound to " . ToString($LaTeXML::MathParser::IDREFS{$idref})
154 : ()));
155 return ['ltx:ERROR', {}, "Missing XMRef idref=$idref"]; } }
156 else {
157 return $node; } }
158  
159 # ================================================================================
160 sub clear {
161 my ($self) = @_;
162 $$self{passed} = { 'ltx:XMath' => 0, 'ltx:XMArg' => 0, 'ltx:XMWrap' => 0 };
163 $$self{failed} = { 'ltx:XMath' => 0, 'ltx:XMArg' => 0, 'ltx:XMWrap' => 0 };
164 $$self{unknowns} = {};
165 $$self{maybe_functions} = {};
166 $$self{n_parsed} = 0;
167 $$self{progress} = 0;
168 return; }
169  
170 our %EXCLUDED_PRETTYNAME_ATTRIBUTES = (
171 fontsize => 1, opacity => 1,
172 color => 1, backgroundcolor => 1);
173  
174 sub token_prettyname {
175 my ($node) = @_;
176 my $name = $node->getAttribute('name');
177 if (defined $name) { }
178 elsif ($name = $node->textContent) {
179 my $font = $LaTeXML::MathParser::DOCUMENT->getNodeFont($node);
180 my %attr = $font->relativeTo(LaTeXML::Common::Font->textDefault);
181 my $desc = join(' ', map { ToString($attr{$_}{value}) }
182 (grep { !$EXCLUDED_PRETTYNAME_ATTRIBUTES{$_} } (sort keys %attr)));
183 $name .= "{$desc}" if $desc; }
184 else {
185 $name = Stringify($node); } # what else ????
186 return $name; }
187  
188 sub note_unknown {
189 my ($self, $node) = @_;
190 my $name = token_prettyname($node);
191 $$self{unknowns}{$name}++;
192 return; }
193  
194 # debugging utility, should be somewhere handy.
195 sub printNode {
196 my ($node) = @_;
197 if (ref $node eq 'ARRAY') {
198 my ($tag, $attr, @children) = @$node;
199 my @keys = sort keys %$attr;
200 return "<$tag"
201 . (@keys ? ' ' . join(' ', map { "$_='" . ($$attr{$_} || '') . "'" } @keys) : '')
202 . (@children
203 ? ">\n" . join('', map { printNode($_) } @children) . "</$tag>"
204 : '/>')
205 . "\n"; }
206 else {
207 return ToString($node); } }
208  
209 # ================================================================================
210 # Some more XML utilities, but math specific (?)
211  
212 # Get the Token's meaning, else name, else content, else role
213 sub getTokenMeaning {
214 my ($node) = @_;
215 my $x;
216 $node = realizeXMNode($node);
217 return (defined($x = p_getAttribute($node, 'meaning')) ? $x
218 : (defined($x = p_getAttribute($node, 'name')) ? $x
219 : (($x = (ref $node eq 'ARRAY' ? '' : $node->textContent)) ne '' ? $x
220 : (defined($x = p_getAttribute($node, 'role')) ? $x
221 : undef)))); }
222  
223 sub node_location {
224 my ($node) = @_;
225 my $n = $node;
226 while ($n && (ref $n !~ /^XML::LibXML::Document/) # Sometimes DocuementFragment ???
227 && !$n->getAttribute('refnum') && !$n->getAttribute('labels')) {
228 $n = $n->parentNode; }
229 if ($n && (ref $n !~ /^XML::LibXML::Document/)) {
230 my ($r, $l) = ($n->getAttribute('refnum'), $n->getAttribute('labels'));
231 return ($r && $l ? "$r ($l)" : $r || $l); }
232 else {
233 return 'Unknown'; } }
234  
235 #%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
236 # Parser
237 #%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
238 # Top-level per-formula parse.
239 # We do a depth-first traversal of the content of the XMath element,
240 # since various sub-elements (XMArg & XMWrap) act as containers of
241 # nominally complete subexpressions.
242 # We do these first for two reasons.
243 # Firstly, since after parsing, the parent will be rebuilt from the result,
244 # we lose the node "identity"; ie. we can't find the child to replace it!
245 # Secondly, in principle (although this isn't used yet), parsing the
246 # child could reveal something interesting about it; say, it's effective role.
247 # Then, this information could be used when parsing the parent.
248 # In fact, this could work the other way too; parsing the parent could tell
249 # us something about what the child must be....
250 sub parse {
251 my ($self, $xnode, $document) = @_;
252 local $LaTeXML::MathParser::STRICT = 1;
253 local $LaTeXML::MathParser::WARNED = 0;
254 local $LaTeXML::MathParser::XNODE = $xnode;
255 local $LaTeXML::MathParser::PUNCTUATION = {};
256 local $LaTeXML::MathParser::LOSTNODES = {};
257 local %LaTeXML::MathParser::IDREFS = ();
258 # This bit for debugging....
259 foreach my $n ($document->findnodes("descendant-or-self::*[\@xml:id]", $xnode)) {
260 my $id = $n->getAttribute('xml:id');
261 $LaTeXML::MathParser::IDREFS{$id} = $n; }
262 if ($$self{lexematize}) {
263 my $lexeme_form = $self->node_to_lexeme_full($xnode);
264 $lexeme_form =~ s/^\s+//;
265 $lexeme_form =~ s/\s+$//;
266 $lexeme_form =~ s/\s+/ /g; # normalize internal whitespaces
267 $xnode->parentNode->setAttribute('lexemes', $lexeme_form);
268 }
269 if (my $result = $self->parse_rec($xnode, 'Anything,', $document)) {
270 # Add text representation to the containing Math element.
271 my $p = $xnode->parentNode;
272 # This is a VERY screwy situation? How can the parent be a document fragment??
273 # This has got to be a LibXML bug???
274 if ($p->nodeType == XML_DOCUMENT_FRAG_NODE) {
275 my @n = $p->childNodes;
276 if (scalar(@n) == 1) {
277 $p = $n[0]; }
278 else {
279 Fatal('malformed', '<XMath>', $xnode, "XMath node has DOCUMENT_FRAGMENT for parent!"); } }
280 # HACK: replace XMRef's to stray trailing punctution
281 foreach my $id (keys %$LaTeXML::MathParser::PUNCTUATION) {
282 my $r = $$LaTeXML::MathParser::PUNCTUATION{$id}->cloneNode;
283 $r->removeAttribute('xml:id');
284 foreach my $n ($document->findnodes("descendant-or-self::ltx:XMRef[\@idref='$id']", $p)) {
285 $document->replaceTree($r, $n); } }
286 foreach my $id (keys %$LaTeXML::MathParser::LOSTNODES) {
287 my $repid = $$LaTeXML::MathParser::LOSTNODES{$id};
288 # but the replacement my have been replaced as well!
289 while (my $reprepid = $$LaTeXML::MathParser::LOSTNODES{$repid}) {
290 $repid = $reprepid; }
291 if ($document->findnodes("descendant-or-self::*[\@xml:id='$id']")
292 && !$document->findnodes("descendant-or-self::*[\@xml:id='$repid']")) {
293 # Do nothing if the node never actually got replaced (parse ultimately failed?)
294 }
295 else {
296 foreach my $n ($document->findnodes("descendant-or-self::ltx:XMRef[\@idref='$id']", $p)) {
297 $document->setAttribute($n, idref => $repid); } } }
298 $p->setAttribute('text', text_form($result));
299 }
300 return; }
301  
302 my %TAG_FEEDBACK = ('ltx:XMArg' => 'a', 'ltx:XMWrap' => 'w'); # [CONSTANT]
303 # Recursively parse a node with some internal structure
304 # by first parsing any structured children, then it's content.
305 sub parse_rec {
306 my ($self, $node, $rule, $document) = @_;
307 $self->parse_children($node, $document);
308  
309 # This will only handle 1 layer nesting (successfully?)
310 # Note that this would have been found by the top level xpath,
311 # but we've got to worry about node identity: the parent is being rebuilt
312 foreach my $nested ($document->findnodes('descendant::ltx:XMath', $node)) {
313 $self->parse($nested, $document); }
314 my $tag = getQName($node);
315 if (my $requested_rule = $node->getAttribute('rule')) {
316 $rule = $requested_rule; }
317 if ($rule eq 'kludge') {
318 $self->parse_kludge($node, $document);
319 return; }
320 elsif (my $result = $self->parse_single($node, $document, $rule)) {
321 $$self{passed}{$tag}++;
322 if ($tag eq 'ltx:XMath') { # Replace the content of XMath with parsed result
323 ProgressStep() if ($$self{progress}++ % $MATHPARSE_PROGRESS_QUANTUM) == 0;
324 map { $document->unRecordNodeIDs($_) } element_nodes($node);
325 # unbindNode followed by (append|replace)Tree (which removes ID's) should be safe
326 map { $_->unbindNode() } $node->childNodes;
327 $document->appendTree($node, $result);
328 $result = [element_nodes($node)]->[0]; }
329 else { # Replace the whole node for XMArg, XMWrap; preserve some attributes
330 ProgressStep() if ($$self{progress}++ % $MATHPARSE_PROGRESS_QUANTUM) == 0;
331 # Copy all attributes
332 my $resultid = p_getAttribute($result, 'xml:id');
333 my %attr = map { (getQName($_) => $_->getValue) }
334 grep { $_->nodeType == XML_ATTRIBUTE_NODE } $node->attributes;
335 # add to result, even allowing modification of xml node, since we're committed.
336 # [Annotate converts node to array which messes up clearing the id!]
337 my $isarr = ref $result eq 'ARRAY';
338 my $rtag = ($isarr ? $$result[0] : $document->getNodeQName($result));
339 # Make sure font is "Appropriate", if we're creating a new token (yuck)
340 if ($isarr && $attr{_font} && ($rtag eq 'ltx:XMTok')) {
341 my $content = join('', @$result[2 .. $#$result]);
342 if ((!defined $content) || ($content eq '')) {
343 delete $attr{_font}; } # No font needed
344 elsif (my $font = $document->decodeFont($attr{_font})) {
345 delete $attr{_font};
346 $attr{font} = $font->specialize($content); } }
347 else {
348 delete $attr{_font}; }
349 foreach my $key (keys %attr) {
350 next unless ($key =~ /^_/) || $document->canHaveAttribute($rtag, $key);
351 my $value = $attr{$key};
352 if ($key eq 'xml:id') { # Since we're moving the id...bookkeeping
353 $document->unRecordID($value);
354 $node->removeAttribute('xml:id'); }
355 if ($isarr) { $$result[1]{$key} = $value; }
356 else { $document->setAttribute($result, $key => $value); } }
357 $result = $document->replaceTree($result, $node);
358 my $newid = $attr{'xml:id'};
359 # Danger: the above code replaced the id on the parsed result with the one from XMArg,..
360 # If there are any references to $resultid, we need to point them to $newid!
361 if ($resultid && $newid && ($resultid ne $newid)) {
362 foreach my $ref ($document->findnodes("//*[\@idref='$resultid']")) {
363 $ref->setAttribute(idref => $newid); } }
364 }
365 return $result; }
366 else {
367 $self->parse_kludge($node, $document);
368 ProgressStep() if ($$self{progress}++ % $MATHPARSE_PROGRESS_QUANTUM) == 0;
369 $$self{failed}{$tag}++;
370 return; } }
371  
372 # Depth first parsing of XMArg nodes.
373 sub parse_children {
374 my ($self, $node, $document) = @_;
375 foreach my $child (element_nodes($node)) {
376 my $tag = getQName($child);
377 if ($tag eq 'ltx:XMArg') {
378 $self->parse_rec($child, 'Anything', $document); }
379 elsif ($tag eq 'ltx:XMWrap') {
380 local $LaTeXML::MathParser::STRICT = 0;
381 $self->parse_rec($child, 'Anything', $document); }
382 ### A nice evolution would be to use the Kludge parser for
383 ### the presentation form in XMDual
384 ### This would avoid silly "parses" of non-semantic stuff; eg assuming times between tokens!
385 ### However, it needs some experimentation to match DLMF's enhancements
386 #### $self->parse_children($child,$document);
387 #### $self->parse_kludge($child,$document); }
388 elsif ($tag =~ /^ltx:(XMApp|XMArray|XMRow|XMCell)$/) {
389 $self->parse_children($child, $document); }
390 elsif ($tag eq 'ltx:XMDual') {
391 $self->parse_children($child, $document); }
392 ### Some day this may be needed? but not yet...
393 # elsif ($tag eq 'ltx:XMRef') {
394 # # We might be referencing something outside the current tree.
395 # # but we'd like it's contents to be parsed before we start using it at this level.
396 # # NOTE: Do we have to worry about things being parsed twice? (ie. when the other tree's done)
397 # # if so, we probably want to mark things as having already been parsed.
398 # my $refnode = realizeXMNode($child);
399 # if(getQName($refnode) ne 'ltx:XMTok'){ # Anything referenced with structure...
400 # Debug("PRE-PARSING Ref'd node: ".ToString($child)." == ".ToString($refnode));
401 # ## $self->parse_rec($refnode,'Anything',$document);
402 # $self->parse_children($refnode,$document);
403 # Debug("NOW REFERENCES: ".ToString(realizeXMNode($child)));
404 # } }
405 }
406 return; }
407  
408 my $HINT_PUNCT_THRESHOLD = 10.0; # \quad or bigger becomes punctuation ? [CONSTANT]
409  
410 sub filter_hints {
411 my ($self, $document, @nodes) = @_;
412 my @prefiltered = ();
413 my $prev = undef;
414 my $pending_comments = '';
415 my $pending_space = 0.0;
416 my $pending_phantom = undef;
417 # Filter the nodes, watching for XMHint's and Comments.
418 foreach my $node (@nodes) {
419 my $type = $node->nodeType;
420 if ($type == XML_TEXT_NODE) { # text? better be (ignorable) whitespace!
421 my $string = $node->textContent;
422 if ($string =~ /\S/) {
423 Warn('unexpected', 'text', $node, "Unexpected text in Math tree"); } }
424 elsif ($type == XML_COMMENT_NODE) { # Comment!
425 my $comment = $node->getData;
426 if ($prev) { # Append to previous element's comments
427 my $c = $prev->getAttribute('_comment');
428 $prev->setAttribute(_comment => ($c ? $c . "\n" . $comment : $comment)); }
429 else { # Or save for first
430 $pending_comments = ($pending_comments ? $pending_comments . "\n" . $comment : $comment); } }
431 elsif ($type != XML_ELEMENT_NODE) {
432 Warn('unexpected', 'node', $node, "Unexpected item in Math tree"); }
433 elsif (getQName($node) eq 'ltx:XMHint') { # If a Hint node?
434 if (my $width = $node->getAttribute('width')) {
435 if (my $pts = getXMHintSpacing($width)) {
436 my $ph = ($node->getAttribute('name') || '') =~ /phantom$/;
437 # If previous token (and not open paren), add the space to the right of it
438 if ($prev && (($prev->getAttribute('role') || '') ne 'OPEN')) {
439 my $s = $prev->getAttribute('_space') || 0.0;
440 my $p = $prev->getAttribute('_phantom');
441 $prev->setAttribute(_space => $s + $pts);
442 $prev->setAttribute(_phantom => $p || $ph); }
443 else { # Else save it for the next token.
444 $pending_space += $pts;
445 $pending_phantom = $ph; } } }
446 # If XMHint is referenced??
447 # Really shouldn't happen, but if XMHint is in XMWrap, it may end up with id....?
448 if (my $id = $node->getAttribute('xml:id')) {
449 if ($document->findnodes("descendant-or-self::ltx:XMRef[\@idref='$id']")) {
450 push(@prefiltered, $node); $prev = $node; } } }
451 # Don't store stuff on APPLYOP, since they tend to disappear.
452 elsif ((getQName($node) eq 'ltx:XMTok') && (($node->getAttribute('role') || '') eq 'APPLYOP')) {
453 ### push(@prefiltered, $node); $prev = $node; } # Keep it.
454 push(@prefiltered, $node); } # Keep it, but don't step $prev
455 else { # Some other element.
456 if ($pending_comments) {
457 $node->setAttribute(_pre_comment => $pending_comments);
458 $pending_comments = ''; }
459 if ($pending_space) {
460 $node->setAttribute(lpadding =>
461 LaTeXML::Common::Dimension::attributeformat($pending_space * 65536));
462 $node->setAttribute(_phantom => $pending_phantom);
463 $pending_space = 0.0;
464 $pending_phantom = undef; }
465 push(@prefiltered, $node); $prev = $node; } # Keep it.
466 }
467 # if $pending_space > 0, should store as rpadding on last element?
468 my @filtered = ();
469 # Filter through the pre-filtered nodes looking for large rpadding to convert to virtual PUNCT.
470 # But we'll assume that phantoms do NOT get converted to PUNCT ?
471 foreach my $node (@prefiltered) {
472 push(@filtered, $node);
473 if (my $s = $node->getAttribute('_space')) {
474 $node->removeAttribute('_space');
475 if ((!$node->getAttribute('_phantom'))
476 && ($s >= $HINT_PUNCT_THRESHOLD) && (($node->getAttribute('role') || '') ne 'PUNCT')) {
477 # Create a new Punctuation node (XMTok) from the wide space
478 # I'm leary that this is a safe way to create an XML node that's NOT in the tree, but...
479 my $p = $node->parentNode;
480 # my $punct = $document->openElementAt($p,'ltx:XMTok',role=>'PUNCT',rpadding=>$s.'pt');
481 my $punct = $document->openElementAt($p, 'ltx:XMTok', role => 'PUNCT',
482 name => ('q' x int($s / 10)) . 'uad');
483 $punct->appendText(spacingToString($s));
484 $p->removeChild($punct); # But don't actually leave it in the tree!!!!
485 push(@filtered, $punct); }
486 else {
487 $node->setAttribute(rpadding =>
488 LaTeXML::Common::Dimension::attributeformat($s * 65536)); } } }
489 return @filtered; }
490  
491 # Given a width attribute on an XMHint, return the pts, if any
492 sub getXMHintSpacing {
493 my ($width) = @_;
494 if ($width && ($width =~ /^$LaTeXML::Common::Glue::GLUE_re$/)) {
495 return ($2 eq 'mu' ? $1 / 1.8 : $1); }
496 else {
497 return 0; } }
498  
499 # We've pretty much builtin the assumption that the target XML is "As If" 10 pts,
500 # so we'll assume that 1em is 10 pts.
501 my $POINTS_PER_EM = 10.0; # [CONSTANT]
502 # Convert spacing, given as a number of points, to a string of appropriate spacing chars
503 sub spacingToString {
504 my ($points) = @_;
505 my $spacing = '';
506 my $ems = $points / $POINTS_PER_EM;
507 my $n = int($ems);
508 if ($n > 0) { $spacing .= ("\x{2003}" x $n); $ems -= $n; }
509 if ($ems > 0.500) { $spacing .= "\x{2002}"; $ems -= 0.500; }
510 if ($ems > 0.333) { $spacing .= "\x{2003}"; $ems -= 0.333; }
511 if ($ems > 0.250) { $spacing .= "\x{2005}"; $ems -= 0.250; }
512 if ($ems > 0.166) { $spacing .= "\x{2006}"; $ems -= 0.166; }
513 return $spacing; }
514  
515 #%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
516 # Low-Level hack parsing when "real" parsing fails;
517 # Two issues cause generated Presentation MathML to be really bad:
518 # (1) not having mrow/mfenced structures wrapping OPEN...CLOSE sequences
519 # throws off MathML's stretchiness treatment of the fences
520 # (they're all the same size; big)
521 # (2) un-attached sub/superscripts won't position correctly,
522 # unless they're attached to something plausible.
523 # NOTE: we should be able to optionally switch this off.
524 # Especially, when we want to try alternative parse strategies.
525 sub parse_kludge {
526 my ($self, $mathnode, $document) = @_;
527 my @nodes = $self->filter_hints($document, $mathnode->childNodes);
528 # the 1st array in stack accumlates the nodes within the current fenced row.
529 # When there's only a single array, it's single entry will be the complete row.
530 my @stack = ([], []);
531 my @pairs = map { [$_, $self->getGrammaticalRole($_)] } @nodes;
532 while (scalar(@pairs) || (scalar(@stack) > 1)) {
533 my $pair = shift(@pairs);
534 my $role = ($pair ? $$pair[1] : 'CLOSE');
535 if ($role eq 'OPEN') {
536 unshift(@stack, [$pair]); } # Start new fenced row;
537 elsif ($role eq 'CLOSE') { # Close the current row
538 my $row = shift(@stack); # get the current list of items
539 push(@$row, $pair) if $pair; # Put the close (if any) into it
540  
541 my @kludged = $self->parse_kludgeScripts_rec(@$row); # handle scripts
542 # wrap, if needed.
543 $row = [(scalar(@kludged) > 1 ? ['ltx:XMWrap', {}, @kludged] : $kludged[0]), 'FENCED'];
544 push(@{ $stack[0] }, $row); } # and put this constructed row at end of containing row.
545 else {
546 push(@{ $stack[0] }, $pair); } } # Otherwise, just put this item into current row.
547  
548 # If we got to here, remove the nodes and replace them by the kludged structure.
549 map { $document->unRecordNodeIDs($_) } element_nodes($mathnode);
550 # unbindNode followed by (append|replace)Tree (which removes ID's) should be safe
551 map { $_->unbindNode() } $mathnode->childNodes;
552 # We're hoping for a single list on the stack,
553 # But extra CLOSEs will leave extra junk behind, so process all the stacked lists.
554 my @replacements = ();
555 foreach my $pair (@{ $stack[0] }) {
556 my $kludge = $$pair[0];
557 push(@replacements, (ref $kludge eq 'ARRAY') && ($$kludge[0] eq 'ltx:XMWrap')
558 ? @$kludge[2 .. $#$kludge] : ($kludge)); }
559 $document->appendTree($mathnode, @replacements);
560 return; }
561  
562 sub parse_kludgeScripts_rec {
563 my ($self, $x, $y, @more) = @_;
564 my @acc = ();
565 while (defined $y) {
566 if ($$x[1] =~ /^FLOAT(SUB|SUPER)SCRIPT$/) { # a Floating script? maybe pre-script
567 if ($$y[1] =~ /^POST(SUB|SUPER)SCRIPT$/) { # followed by another script?
568 if (@more) { # followed by a something? => Combined pre sub & super
569 my ($base, @rest) = $self->parse_kludgeScripts_rec(@more);
570 return (@acc, NewScript(NewScript($base, $$y[0], 'pre'), $$x[0], 'pre'), @rest); }
571 else { # else floating sub & super
572 return (@acc, NewScript(NewScript(Absent(), $$y[0], 'post'), $$x[0], 'post')); } }
573 else { # else just prescript on whatever follows
574 my ($base, @rest) = $self->parse_kludgeScripts_rec($y, @more);
575 return (@acc, NewScript($base, $$x[0], 'pre'), @rest); } }
576 elsif ($$y[1] =~ /^POST(SUB|SUPER)SCRIPT$/) {
577 # or a postscript is applied to the preceding thing.
578 return (@acc, $self->parse_kludgeScripts_rec([NewScript($$x[0], $$y[0]), ''], @more)); }
579 else { # else skip over a and continue
580 push(@acc, $$x[0]);
581 ($x, $y, @more) = ($y, @more); } }
582 return (@acc, $$x[0]); }
583  
584 # OBSOLETE EXPLORATORY CODE; but there are some interesting ideas....
585 # sub parse_kludge {
586 # my($self,$mathnode,$document)=@_;
587 # my @nodes = $self->filter_hints($document,$mathnode->childNodes);
588 # map { $mathnode->removeChild($_) } @nodes;
589 # my @result=();
590 # while(@nodes){
591 # @nodes = $self->parse_kludge_rec(@nodes);
592 # push(@result,shift(@nodes)); }
593 # $document->appendTree($mathnode,@result); }
594  
595 # # Kludge Parse the next thing, and then add any following scripts to it.
596 # sub parse_kludge_rec {
597 # my($self,@more)=@_;
598 # my($item,$open,$close,$seps,$arg);
599 # ($item,@more) = $self->parse_kludge_reca(@more);
600 # while(@more && (($self->getGrammaticalRole($more[0])||'') =~ /^POST(SUB|SUPER)SCRIPT$/)){
601 # $item = NewScript($item,shift(@more)); }
602 # if(@more && (($self->getGrammaticalRole($more[0])||'') eq 'APPLYOP')){
603 # shift(@more);
604 # if(@more && (($self->getGrammaticalRole($more[0])||'') eq 'OPEN')){
605 # ($open,$close,$seps,$arg,@more)=$self->parse_kludge_fence(@more);
606 # $item = Apply(Annotate($item,argopen=>$open, argclose=>$close, separators=>$seps),@$arg); }
607 # else {
608 # ($arg,@more)=$self->parse_kludge_rec(@more);
609 # $item = Apply($item,$arg); }}
610 # ($item,@more); }
611  
612 # sub parse_kludge_reca {
613 # my($self,$next,@more)=@_;
614 # my $role = $self->getGrammaticalRole($next);
615 # if($role =~ /^FLOAT(SUB|SUPER)SCRIPT$/){
616 # my($base,@rest) = $self->parse_kludge_rec(@more);
617 # (NewScript($base,$next),@rest); }
618 # elsif($role eq 'OPEN'){
619 # my($open,$close,$seps,$list,@more)=$self->parse_kludge_fence($next,@more);
620 # (Apply(Annotate(New(undef,undef,role=>'FENCED'),
621 # argopen=>$open, argclose=>$close, separators=>$seps),@$list), @more); }
622 # else {
623 # ($next,@more); }}
624  
625 # sub parse_kludge_fence {
626 # my($self,$next,@more)=@_;
627 # my($open,$close,$punct,$r,$item,@list)=($next,undef,'',undef);
628 # while(@more){
629 # my @i=();
630 # while(@more && (($r=($self->getGrammaticalRole($more[0])||'')) !~ /^(CLOSE|PUNCT)$/)){
631 # ($item,@more)=$self->parse_kludge_rec(@more);
632 # push(@i,$item); }
633 # push(@list,(scalar(@i > 1) ? ['ltx:XMWrap',{},@i] : $i[0]));
634 # if($r eq 'CLOSE'){
635 # $close=shift(@more); last; }
636 # else {
637 # $punct .= ($punct ? ' ':''). p_getValue(shift(@more)); }} # Delimited by SINGLE SPACE!
638 # ($open,$close,$punct,[@list],@more); }
639  
640 #%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
641 # Low-level Parser: parse a single expression
642 #%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
643 # Convert to textual form for processing by MathGrammar
644 sub parse_single {
645 my ($self, $mathnode, $document, $rule) = @_;
646 my @nodes = $self->filter_hints($document, $mathnode->childNodes);
647  
648 my ($punct, $result, $unparsed);
649 my @punct = ();
650 # Extract trailing punctuation, if rule allows it.
651 if ($rule =~ s/,$//) {
652 # Collect ALL trailing PUNCT|PERIOD's...
653 my ($x, $r);
654 while (($x = $nodes[-1]) && ($x = realizeXMNode($x)) && (getQName($x) eq 'ltx:XMTok')
655 && ($r = $x->getAttribute('role')) && (($r eq 'PUNCT') || ($r eq 'PERIOD'))) {
656 my $p = pop(@nodes);
657 # Special case hackery, in case this thing is XMRef'd!!!
658 # We could just stick it on the end of the presentation,
659 # but it doesn't belong in the content at all!?!?
660 if (my $id = $p->getAttribute('xml:id')) {
661 $$LaTeXML::MathParser::PUNCTUATION{$id} = $p; }
662 unshift(@punct, $p); }
663 }
664  
665 if ($LaTeXML::DEBUG{recdescent}) {
666 $::RD_TRACE = 1; # Turn on MathGrammar tracing
667 # my $box = $document->getNodeBox($LaTeXML::MathParser::XNODE);
668 my $box = $document->getNodeBox($mathnode);
669 Debug(('=' x 60) .
670 "\nParsing formula \"" . ToString($box) . "\""
671 . "\n from " . ToString($box->getLocator)
672 . "\n == \"" . join(' ', map { node_string($_, $document) } @nodes) . "\""
673 . "\n == " . ToString($mathnode)); }
674  
675 if (scalar(@nodes) < 2) { # Too few nodes? What's to parse?
676 $result = $nodes[0] || Absent(); }
677 else {
678 # Now do the actual parse.
679 ($result, $unparsed) = $self->parse_internal($rule, @nodes);
680 }
681 # Failure? No result or uparsed lexemes remain.
682 # NOTE: Should do script hack??
683 if ((!defined $result) || $unparsed) {
684 $self->failureReport($document, $mathnode, $rule, $unparsed, @nodes);
685 return; }
686 # Success!
687 else {
688 if (@punct) { # create a trivial XMDual to treat the punctuation as presentation
689 $result = ['ltx:XMDual', {},
690 LaTeXML::Package::createXMRefs($document, $result),
691 ['ltx:XMWrap', {}, $result, @punct]]; } # or perhaps: Apply, punctuated???
692 if ($LaTeXML::DEBUG{recdescent}) {
693 Debug("=>" . printNode($result) . "\n" . ('=' x 60)); }
694 return $result; } }
695  
696 sub node_to_lexeme {
697 my ($self, $node) = @_;
698 my $qname = getQName($node);
699 my $is_inked = 1;
700 my $lexeme = ($qname eq 'ltx:XMTok' or $qname eq 'ltx:text') && $node->textContent;
701 if (!defined($lexeme) || length($lexeme) == 0) {
702 $is_inked = 0;
703 $lexeme = getTokenMeaning($node); }
704 my $document = $LaTeXML::MathParser::DOCUMENT;
705 return unless defined $lexeme;
706 if ($is_inked) {
707 if (my $font = $node->getAttribute('_font')) {
708 my $font_spec = $document->decodeFont($font);
709 if (my %declarations = $font_spec && $font_spec->relativeTo(LaTeXML::Common::Font->textDefault)) {
710 my @to_add = ();
711 my $font_pending = $declarations{font} || {};
712 my $properties_pending = $$font_pending{properties} || {};
713 foreach my $attr (qw(family series shape)) {
714 if (my $value = $$properties_pending{$attr}) {
715 push @to_add, $value; } }
716 if (@to_add) {
717 my $prefix = join("_", sort(@to_add)) . "_";
718 $lexeme = join(" ", map { $prefix . $_ } split(' ', $lexeme)); }
719 } }
720 if ($lexeme =~ /^\p{L}+$/) {
721 $lexeme = join(" ", map { 'roman_' . $_ } split(' ', $lexeme)); } }
722 $lexeme =~ s/\s+$//;
723 return $lexeme; }
724  
725 sub node_to_lexeme_full {
726 my ($self, $unrealized_node) = @_;
727 my $node = realizeXMNode($unrealized_node);
728 my $tag = getQName($node);
729 if ($tag eq 'ltx:XMHint') { return ""; } # just skip XMHints, they don't contain lexemes
730 my $role = p_getAttribute($node, 'role');
731 if ($tag eq 'ltx:XMTok' || ($role && ($tag !~ 'ltx:XM(Dual|App|Arg|Array|Wrap|ath)'))) {
732 # Elements that directly represent a lexeme, or intended operation with a syntactic role (such as a postscript),
733 # can proceed to building the lexeme from the leaf node.
734 return $self->node_to_lexeme($node);
735 }
736 # Elements that do not have a role and are intermediate "may" need an argument wrapper, so that arguments
737 # remain unambiguous. For instance a `\frac{a}{b}` has clear argument structure to be preserved.
738 my ($mark_start, $mark_end) = ('', '');
739 if ($tag ne 'ltx:XMath') {
740 if ($role) {
741 $mark_start = "start_$role ";
742 $mark_end = " end_$role";
743 } elsif ($tag =~ '^ltx:XM(Arg|Row|Cell)') {
744 my $tag_role = uc($1);
745 $mark_start = "start_$tag_role ";
746 $mark_end = " end_$tag_role";
747 }
748 }
749 my $lexemes = $mark_start;
750 if ($tag eq 'ltx:XMDual') {
751 $lexemes .= $self->node_to_lexeme_full($LaTeXML::MathParser::DOCUMENT->getSecondChildElement($node)); }
752 elsif ($tag eq 'ltx:XMText') {
753 # can be either a single node XMText, we're looking at a leaf text node
754 # or \text{}-like construct, with multiple math formulas and interleaved text
755 foreach my $child ($node->childNodes) {
756 if (ref($child) eq 'XML::LibXML::Text') {
757 $lexemes .= $child->textContent() . ' '; }
758 else {
759 my $child_lexeme = $self->node_to_lexeme_full($child);
760 if (defined $child_lexeme && length($child_lexeme) > 0) {
761 $lexemes .= $child_lexeme . ' '; } } } }
762 elsif ($tag eq 'ltx:text') { # could recurse in from ltx:XMText
763 return $self->node_to_lexeme($node); }
764 else {
765 my @child_elements = element_nodes($node);
766 # skip through single child wrappers (don't serialize)
767 while (scalar(@child_elements) == 1 && getQName($child_elements[0]) =~ /^ltx:XM(Arg|Wrap)$/) {
768 @child_elements = element_nodes($child_elements[0]);
769 }
770 foreach my $child (@child_elements) {
771 my $child_lexeme = $self->node_to_lexeme_full($child);
772 if (defined $child_lexeme && length($child_lexeme) > 0) {
773 $lexemes .= $child_lexeme . ' ';
774 } } }
775 $lexemes .= $mark_end;
776 return $lexemes; }
777  
778 sub parse_internal {
779 my ($self, $rule, @nodes) = @_;
780 #------------
781 # Generate a textual token for each node; The parser operates on this encoded string.
782 local $LaTeXML::MathParser::LEXEMES = {};
783 my $i = 0;
784 my $lexemes = '';
785  
786 foreach my $node (@nodes) {
787 # This is a parser-specific lexeme, but it is not (yet) identical to the serialized lexeme by
788 # ->node_to_lexeme, which is currently experimental
789 my $role = $self->getGrammaticalRole($node);
790 my $text = getTokenMeaning($node);
791 $text = 'Unknown' unless defined $text;
792 my $lexeme = $role . ":" . $text . ":" . ++$i;
793 $lexeme =~ s/\s//g;
794  
795 $$LaTeXML::MathParser::LEXEMES{$lexeme} = $node;
796 $lexemes .= ' ' . $lexeme; }
797  
798 #------------
799 # apply the parser to the textified sequence.
800 local $LaTeXML::MathParser::PARSER = $self;
801 local %LaTeXML::MathParser::SEEN_NOTATIONS = ();
802 local %LaTeXML::MathParser::DISALLOWED_NOTATIONS = ();
803 local $LaTeXML::MathParser::MAX_ABS_DEPTH = 1;
804 # "Speculative" mode is disabled by default (set MATHPARSER_SPECULATE).
805 # It causes the parser to explore possible undeclared notatations,
806 # like possible functions (the only one, so far)
807 # These extra grammar rules can be costly in corner cases.
808 # This should be disabled when speed (but feedback) is essential
809 if ($STATE->lookupValue('MATHPARSER_SPECULATE')) {
810 $LaTeXML::MathParser::DISALLOWED_NOTATIONS{MaybeFunctions} = 0; }
811 else {
812 $LaTeXML::MathParser::DISALLOWED_NOTATIONS{MaybeFunctions} = 1; }
813 my $unparsed = $lexemes;
814 my $result = $$self{internalparser}->$rule(\$unparsed);
815 if (((!defined $result) || $unparsed) # If parsing Failed
816 && $LaTeXML::MathParser::SEEN_NOTATIONS{QM}) { # & Saw some QM stuff.
817 $LaTeXML::MathParser::DISALLOWED_NOTATIONS{QM} = 1; # Retry w/o QM notations
818 $unparsed = $lexemes;
819 $result = $$self{internalparser}->$rule(\$unparsed); }
820 while (((!defined $result) || $unparsed) # If parsing Failed
821 && ($LaTeXML::MathParser::SEEN_NOTATIONS{AbsFail}) # & Attempted deeper abs nesting?
822 && ($LaTeXML::MathParser::MAX_ABS_DEPTH < 3)) { # & Not ridiculously deep
823 delete $LaTeXML::MathParser::SEEN_NOTATIONS{AbsFail};
824 ++$LaTeXML::MathParser::MAX_ABS_DEPTH; # Try deeper.
825 $unparsed = $lexemes;
826 $result = $$self{internalparser}->$rule(\$unparsed); }
827  
828 # If still failed, try other strategies?
829  
830 return ($result, $unparsed); }
831  
832 sub getGrammaticalRole {
833 my ($self, $node) = @_;
834 $node = realizeXMNode($node);
835 my $role = p_getAttribute($node, 'role');
836 if (!defined $role) {
837 my $tag = getQName($node);
838 if ($tag eq 'ltx:XMTok') {
839 $role = 'UNKNOWN'; }
840 elsif ($tag eq 'ltx:XMDual') {
841 my ($content, $presentation) = element_nodes($node);
842 $role = p_getAttribute($content, 'role') || p_getAttribute($presentation, 'role'); }
843 $role = 'ATOM' unless defined $role; }
844 $self->note_unknown($node) if ($role eq 'UNKNOWN') && $LaTeXML::MathParser::STRICT;
845 return $role; }
846  
847 # How many tokens before & after the failure point to report in the Warning message.
848 my $FAILURE_PRETOKENS = 3; # [CONSTANT]
849 my $FAILURE_POSTTOKENS = 1; # [CONSTANT]
850  
851 sub failureReport {
852 my ($self, $document, $mathnode, $rule, $unparsed, @nodes) = @_;
853 if ($LaTeXML::MathParser::STRICT || (($LaTeXML::Common::Error::VERBOSITY || 0) > 1)) {
854 my $loc = "";
855 # If we haven't already done it for this formula, show the original TeX.
856 if (!$LaTeXML::MathParser::WARNED) {
857 $LaTeXML::MathParser::WARNED = 1;
858 my $box = $document->getNodeBox($LaTeXML::MathParser::XNODE);
859 $loc = "In \"" . UnTeX($box) . "\""; }
860 $unparsed =~ s/^\s*//;
861 my @rest = split(/ /, $unparsed);
862 my $pos = scalar(@nodes) - scalar(@rest);
863 # Break up the input at the point where the parse failed.
864 my $max = 50;
865 my $parsed = join(' ', ($pos > $max ? ('...') : ()),
866 (map { node_string($_, $document) } @nodes[max(0, $pos - 50) .. $pos - 1]));
867 my $toparse = join(' ',
868 (map { node_string($_, $document) } @nodes[$pos .. min($pos + 50, $#nodes)]),
869 ($#nodes > $pos + 50 ? ('...') : ()));
870 my $parsefail
871 = join('.', map { $self->getGrammaticalRole($_) }
872 @nodes[($pos - $FAILURE_PRETOKENS >= 0
873 ? $pos - $FAILURE_PRETOKENS : 0) .. $pos - 1])
874 . ">"
875 . join('.', map { $self->getGrammaticalRole($_) }
876 @nodes[$pos .. ($pos + $FAILURE_POSTTOKENS - 1 < $#nodes
877 ? $pos + $FAILURE_POSTTOKENS - 1 : $#nodes)]);
878 my $lexeme = node_location($nodes[$pos] || $nodes[$pos - 1] || $mathnode);
879 my $indent = length($parsed) - 2; $indent = 8 if $indent > 8;
880 Warn('not_parsed', $parsefail, $mathnode,
881 "MathParser failed to match rule '$rule'",
882 ($loc ? ($loc) : ()),
883 ($parsed
884 ? ($parsed, (' ' x $indent) . "> " . $toparse)
885 : ("> " . $toparse)));
886 }
887 return; }
888  
889 # used for debugging & failure reporting.
890 sub node_string {
891 my ($node, $document) = @_;
892 my $role = $node->getAttribute('role') || 'UNKNOWN';
893 my $box = $document->getNodeBox($node);
894 return ($box ? ToString($box) : text_form($node)) . "[[$role]]"; }
895  
896 #%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
897 # Conversion to a less ambiguous, mostly-prefix form.
898 # Mostly for debugging information?
899 # Note that the nodes are true libXML nodes, already absorbed into the document
900 #%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
901 sub text_form {
902 my ($node) = @_;
903 return textrec($node, undef); }
904  
905 my %PREFIX_ALIAS = ( # [CONSTANT]
906 SUPERSCRIPTOP => '^', SUBSCRIPTOP => '_', times => '*',
907 'equals' => '=', 'less-than' => '<', 'greater-than' => '>',
908 'less-than-or-equals' => '<=', 'greater-than-or-equals' => '>=',
909 'much-less-than' => '<<', 'much-greater-than' => '>>',
910 'plus' => '+', 'minus' => '-', 'divide' => '/');
911 # Put infix, along with `binding power'
912 my %IS_INFIX = (METARELOP => 1, # [CONSTANT]
913 RELOP => 2, ARROW => 2,
914 ADDOP => 10, MULOP => 100, FRACOP => 100,
915 SUPERSCRIPTOP => 1000, SUBSCRIPTOP => 1000);
916  
917 sub textrec {
918 my ($node, $outer_bp, $outer_name) = @_;
919 return '[missing]' unless defined $node;
920 $node = realizeXMNode($node);
921 my $tag = getQName($node);
922 $outer_bp = 0 unless defined $outer_bp;
923 $outer_name = '' unless defined $outer_name;
924 # If node has meaning, that's the text form.
925 if (my $meaning = p_getAttribute($node, 'meaning') || p_getAttribute($node, 'name')) {
926 return $PREFIX_ALIAS{$meaning} || $meaning; }
927 elsif ($tag eq 'ltx:XMApp') {
928 my $app_role = $node->getAttribute('role');
929 my ($op, @args) = element_nodes($node);
930 $op = realizeXMNode($op);
931 if ($app_role && $app_role =~ /^FLOAT(SUB|SUPER)SCRIPT$/) {
932 return ($1 eq 'SUPER' ? '^' : '_') . textrec($op); }
933 else {
934 my $name = ((getQName($op) eq 'ltx:XMTok') && getTokenMeaning($op)) || 'unknown';
935 my ($bp, $string) = textrec_apply($name, $op, @args);
936 return (($bp < $outer_bp) || (($bp == $outer_bp) && ($name ne $outer_name))
937 ? '(' . $string . ')' : $string); } }
938 elsif ($tag eq 'ltx:XMDual') {
939 my ($content, $presentation) = element_nodes($node);
940 my $text = textrec($content, $outer_bp, $outer_name); # Just send out the semantic form.
941 # Fall back to presentation, if content has poor semantics (eg. from replacement patterns)
942 return ($text =~ /^\(*Unknown/ ? textrec($presentation, $outer_bp, $outer_name) : $text); }
943 elsif ($tag eq 'ltx:XMTok') {
944 my $name = getTokenMeaning($node);
945 $name = 'Unknown' unless defined $name;
946 return $PREFIX_ALIAS{$name} || $name; }
947 elsif (($tag eq 'ltx:XMWrap') || ($tag eq 'ltx:XMCell')) {
948 # ??
949 return join('@', map { textrec($_) } element_nodes($node)); }
950 elsif ($tag eq 'ltx:XMArray') {
951 return textrec_array($node); }
952 else {
953 return '[' . (p_getValue($node) || '') . ']'; } }
954  
955 sub textrec_apply {
956 my ($name, $op, @args) = @_;
957 my $role = ((ref $op ne 'ARRAY') && $op->getAttribute('role')) || 'Unknown';
958 if (($role =~ /^(SUB|SUPER)SCRIPTOP$/) && (($op->getAttribute('scriptpos') || '') =~ /^pre\d+$/)) {
959 # Note that this will likely get parenthesized due to high bp
960 return (5000, textrec($op) . " " . textrec($args[1]) . " " . textrec($args[0])); }
961 elsif (my $bp = $IS_INFIX{$role}) {
962 # A sub/superscript with a meaning probably should be prefix
963 if (($role =~ /^(SUB|SUPER)SCRIPTOP$/) && $op->getAttribute('meaning')) {
964 return (500, textrec($op, 10000, $name) . '@(' . join(', ', map { textrec($_) } @args) . ')') }
965 else { # Format as infix.
966 return ($bp, (scalar(@args) == 1 # unless a single arg; then prefix.
967 ? textrec($op) . ' ' . textrec($args[0], $bp, $name)
968 : join(' ' . textrec($op) . ' ', map { textrec($_, $bp, $name) } @args))); } }
969 elsif ($role eq 'POSTFIX') {
970 return (10000, textrec($args[0], 10000, $name) . textrec($op)); }
971 elsif ($name eq 'multirelation') {
972 return (2, join(' ', map { textrec($_, 2, $name) } @args)); }
973 else {
974 return (500, textrec($op, 10000, $name) . '@(' . join(', ', map { textrec($_) } @args) . ')'); } }
975  
976 sub textrec_array {
977 my ($node) = @_;
978 my $name = $node->getAttribute('meaning') || $node->getAttribute('name') || 'Array';
979 my @rows = ();
980 foreach my $row (element_nodes($node)) {
981 push(@rows, '[' . join(', ', map { ($_->firstChild ? textrec($_->firstChild) : '') } element_nodes($row)) . ']'); }
982 return $name . '[' . join(', ', @rows) . ']'; }
983  
984 #%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
985 # Cute! Were it NOT for Sub/Superscripts, the whole parsing process only
986 # builds a new superstructure around the sequence of token nodes in the input.
987 # Thus, any internal structure is unchanged.
988 # They get re-parented, but if the parse fails, we've only got to put them
989 # BACK into the original node, to recover the original arrangment!!!
990 # Thus, we don't have to clone, and deal with namespace duplication.
991 # ...
992 # EXCEPT, as I said, for sub/superscripts!!!!
993 #
994  
995 #%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
996 # Constructors used in grammar
997 # All the tree construction in the grammar should come through these operations.
998 # We avoid mucking with the actual XML nodes (both to avoid modifying the original
999 # tree until we have a successful parse, and to avoid XML::LibXML cloning nightmares)
1000 # We are converting XML nodes to array representation: [$tag, {%attr},@children]
1001 # This means any inspection of nodes has to recognize that
1002 # * node may be in XML vs ARRAY representation
1003 # * node may be an XMRef to another node whose properties are the ones we should use.
1004 #
1005 # Also, when we are examining a node's properties (roles, fences, script positioning, etc)
1006 # we should be careful to check for XMRef indirection and examine the properties
1007 # of the node that was referred to.
1008 # HOWEVER, we should construct our parse tree using (a clone of) the XMRef node,
1009 # rather than (a clone of) the referred to node, so as to preserve identity.
1010 #%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1011 # We're currently keeping the id's on the nodes as they get cloned,
1012 # since they'll (maybe) replace the unparsed nodes.
1013 # However, if we consider multiple parses or preserving both parsed & unparsed,
1014 # we may have to do some adaptation and id shifting.
1015 # ================================================================================
1016  
1017 # ================================================================================
1018 # Low-level accessors
1019 sub Lookup {
1020 my ($lexeme) = @_;
1021 return $$LaTeXML::MathParser::LEXEMES{$lexeme}; }
1022  
1023 # The following accessors work on both the LibXML and ARRAY representations
1024 # but they do NOT automatically dereference XMRef!
1025 sub p_getValue {
1026 my ($node) = @_;
1027 if (!defined $node) {
1028 return; }
1029 elsif (ref $node eq 'XML::LibXML::Element') {
1030 my $x;
1031 return (($x = $node->textContent) ne '' ? $x # get content, or fall back to name
1032 : (defined($x = $node->getAttribute('name')) ? $x
1033 : undef)); }
1034 elsif (ref $node eq 'ARRAY') {
1035 my ($op, $attr, @args) = @$node;
1036 if (@args) {
1037 return join('', grep { defined $_ } map { p_getValue($_) } @args); }
1038 else {
1039 return $$node[1]{name}; } }
1040 elsif (ref $node eq 'XML::LibXML::Text') {
1041 return $node->textContent; }
1042 else { # ????
1043 return $node; } }
1044  
1045 sub p_getTokenMeaning {
1046 my ($item) = @_;
1047 if (!defined $item) {
1048 return; }
1049 elsif (ref $item eq 'ARRAY') {
1050 my ($op, $attr, @args) = @$item;
1051 return $$attr{meaning} || $$attr{name} || $args[0] || $$attr{role}; }
1052 elsif (ref $item eq 'XML::LibXML::Element') {
1053 return getTokenMeaning($item); } }
1054  
1055 sub p_getAttribute {
1056 my ($item, $key) = @_;
1057 if (!defined $item) {
1058 return; }
1059 elsif (ref $item eq 'ARRAY') {
1060 return $$item[1]{$key}; }
1061 elsif (ref $item eq 'XML::LibXML::Element') {
1062 return $item->getAttribute($key); } }
1063  
1064 sub p_element_nodes {
1065 my ($item) = @_;
1066 if (!defined $item) {
1067 return (); }
1068 elsif (ref $item eq 'ARRAY') {
1069 my ($op, $attr, @args) = @$item;
1070 return grep { ref $_ } @args; }
1071 elsif (ref $item eq 'XML::LibXML::Element') {
1072 return element_nodes($item); } }
1073  
1074 sub p_getQName {
1075 my ($item) = @_;
1076 if (!defined $item) {
1077 return; }
1078 elsif (ref $item eq 'ARRAY') {
1079 return $$item[0]; }
1080 elsif (ref $item eq 'XML::LibXML::Element') {
1081 return getQName($item); } }
1082  
1083 # Make a new Token node with given name, content, and attributes.
1084 # $content is an array of nodes (which may need to be cloned if still attached)
1085 sub New {
1086 my ($meaning, $content, %attributes) = @_;
1087 my %attr = ();
1088 $attr{meaning} = $meaning if $meaning;
1089 foreach my $key (sort keys %attributes) {
1090 my $value = p_getValue($attributes{$key});
1091 $attr{$key} = $value if defined $value; }
1092 if (!$attr{font}) {
1093 $attr{font} = ($content && $content =~ /\S/
1094 ? LaTeXML::Common::Font->textDefault->specialize($content)
1095 : LaTeXML::Common::Font->new()); }
1096 return ['ltx:XMTok', {%attr}, ($content ? ($content) : ())]; }
1097  
1098 # Like New(), but concatenating several symbols into one new one.
1099 # This accounts for the symbols "disappearing", being replaced by one,
1100 # and thus any references to the old one have to be adjusted ... or removed
1101 # I'm a little concerned that we should be defering this till a successful parse?
1102 sub CatSymbols {
1103 my ($symbol1, $symbol2, $meaning, $content, %attributes) = @_;
1104 my $new = New($meaning, $content, %attributes);
1105 my $repl;
1106 my $symbols = [$symbol1, $symbol2];
1107 my $doc = $LaTeXML::MathParser::DOCUMENT;
1108 foreach my $symbol (@$symbols) {
1109 if (my $id = p_getAttribute(realizeXMNode($symbol), 'xml:id')) {
1110 if (!$repl) {
1111 my $newid = $doc->modifyID($id);
1112 $$new[1]{'xml:id'} = $newid;
1113 ReplacedBy($symbol, $new);
1114 $repl = 1; }
1115 else {
1116 foreach my $r ($doc->findnodes("descendant-or-self::ltx:XMRef[\@idref='$id']")) {
1117 $doc->removeNode($r); } } # ? Hopefully this is safe.
1118 } }
1119 return $new; }
1120  
1121 # Some handy shorthands.
1122 sub Absent {
1123 return New('absent'); }
1124  
1125 sub InvisibleTimes {
1126 return New('times', "\x{2062}", role => 'MULOP', font => LaTeXML::Common::Font->new()); }
1127  
1128 sub InvisibleComma {
1129 return New(undef, "\x{2063}", role => 'PUNCT', font => LaTeXML::Common::Font->new()); }
1130  
1131 # Get n-th arg of an XMApp.
1132 # However, this is really only used to get the script out of a sub/super script
1133 sub Arg {
1134 my ($node, $n) = @_;
1135 my $onode = $node;
1136 $node = realizeXMNode($node);
1137 if (ref $node eq 'ARRAY') {
1138 return $$node[$n + 2]; }
1139 else {
1140 my @args = element_nodes($node);
1141 my $nth = $args[$n];
1142 # Tricky case: if $node is an XMRef, we'll want to reference the SUB node too
1143 # and not just use it directly; else that node will be duplicated in both branches of XMDual
1144 if ($nth && !$node->isSameNode($onode)) {
1145 return LaTeXML::Package::createXMRefs($LaTeXML::MathParser::DOCUMENT, $nth); }
1146 else {
1147 return $args[$n]; } } } # will get cloned if/when needed.
1148  
1149 # Add more attributes to a node.
1150 # Values can be strings or nodes whose text content is used.
1151 # Note that it avoids changing the underlying XML, so it may return a new object!
1152 sub Annotate {
1153 my ($node, %attributes) = @_;
1154 my %attrib = ();
1155 # first scan & convert any attributes, to make sure there really are any values.
1156 foreach my $attr (keys %attributes) {
1157 my $value = p_getValue($attributes{$attr});
1158 $attrib{$attr} = $value if defined $value; }
1159 # Hmm.... maybe we need to merge some things, open close?
1160 if (keys %attrib) { # Any attributes to assign?
1161 # If we've gotten a real XML node, convert to array representation
1162 # We do NOT want to modify any of the original XML!!!!
1163 if (ref $node ne 'ARRAY') {
1164 $node = [getQName($node),
1165 { map { (getQName($_) => $_->getValue) }
1166 grep { $_->nodeType == XML_ATTRIBUTE_NODE } $node->attributes },
1167 $node->childNodes]; }
1168 my $qname = $$node[0];
1169 # Remove any attributes that aren't allowed!!!
1170 foreach my $k (keys %attrib) {
1171 delete $attrib{$k} unless $k =~ /^_/ || $LaTeXML::MathParser::DOCUMENT->canHaveAttribute($qname, $k); }
1172 # Make sure font is "Appropriate", if we're creating a new token
1173 if ($attrib{_font} && ($qname eq 'ltx:XMTok')) {
1174 my $content = join('', @$node[2 .. $#$node]);
1175 if ((!defined $content) || ($content eq '')) {
1176 delete $attrib{_font}; } # No font needed
1177 elsif (my $font = $LaTeXML::MathParser::DOCUMENT->decodeFont($attrib{_font})) {
1178 delete $attrib{_font};
1179 $attrib{font} = $font->specialize($content); } }
1180 map { $$node[1]{$_} = $attrib{$_} } keys %attrib; } # Now add them.
1181 return $node; }
1182  
1183 # ================================================================================
1184 # Mid-level constructors
1185  
1186 # Apply $op to the list of arguments
1187 # args may be array-rep or lexemes (or nodes?)
1188 sub Apply {
1189 my ($op, @args) = @_;
1190 my $font = p_getAttribute($op, '_font');
1191 return ['ltx:XMApp', { ($font ? (_font => $font) : ()) }, $op, @args]; }
1192  
1193 # Apply $op to a `delimited' list of arguments of the form
1194 # open, expr (punct expr)* close
1195 # after extracting the opening and closing delimiters, and the separating punctuation
1196 # Generate an XMDual, so that any styling of delimiters & punctuation is preserved.
1197 sub ApplyDelimited {
1198 my ($op, @stuff) = @_;
1199 my $open = $stuff[0];
1200 my $close = $stuff[-1];
1201 my ($seps, @args) = extract_separators(@stuff[1 .. $#stuff - 1]);
1202 return ['ltx:XMDual', {},
1203 Apply(LaTeXML::Package::createXMRefs($LaTeXML::MathParser::DOCUMENT, $op),
1204 LaTeXML::Package::createXMRefs($LaTeXML::MathParser::DOCUMENT, @args)),
1205 Apply($op, ['ltx:XMWrap', {}, @stuff])]; }
1206  
1207 # This is similar, but "interprets" a delimited list as being the
1208 # application of some operator to the items in the list.
1209 sub InterpretDelimited {
1210 my ($op, @stuff) = @_;
1211 my $open = $stuff[0];
1212 my $close = $stuff[-1];
1213 my ($seps, @args) = extract_separators(@stuff[1 .. $#stuff - 1]);
1214 return ['ltx:XMDual', {},
1215 Apply($op, LaTeXML::Package::createXMRefs($LaTeXML::MathParser::DOCUMENT, @args)),
1216 ['ltx:XMWrap', {}, @stuff]]; }
1217  
1218 # Given a sequence of operators, form the nested application op(op(...(arg)))
1219 sub recApply {
1220 my (@ops) = @_;
1221 return (scalar(@ops) > 1 ? Apply(shift(@ops), recApply(@ops)) : $ops[0]); }
1222  
1223 # Given alternating expressions & separators (punctuation,...)
1224 # extract the separators as a concatenated string,
1225 # returning (separators, args...)
1226 sub extract_separators {
1227 my (@stuff) = @_;
1228 my ($punct, @args);
1229 if (@stuff) {
1230 push(@args, shift(@stuff)); # Grab 1st expression
1231 while (@stuff) { # Expecting pairs of punct, expression
1232 my $p = realizeXMNode(shift(@stuff));
1233 $punct .=
1234 ($punct ? ' ' : '') # Delimited by SINGLE SPACE!
1235 . spacingToString(getXMHintSpacing(p_getAttribute($p, 'lpadding')))
1236 . p_getValue($p)
1237 . spacingToString(getXMHintSpacing(p_getAttribute($p, 'rpadding')));
1238 push(@args, shift(@stuff)); } } # Collect the next expression.
1239 @args = grep { $_ } @args; # drop all undef args, trailing punct could have added an undef
1240 return ($punct, @args); }
1241  
1242 # ================================================================================
1243 # Some special cases
1244  
1245 # This specifies the "meaning" of things within a pair
1246 # of open/close delimiters, depending on the number of things.
1247 # Really should be customizable?
1248 # Note that these are all Best Guesses, but really can have
1249 # alternate interpretations depending on context, field, etc.
1250 # Question: Is there enough context to guess better?
1251 # For example, whether (a,b) is an interval or list?
1252 # (both could reasonably be preceded by \in )
1253 my %balanced = ( # [CONSTANT]
1254 '(' => ')', '[' => ']', '{' => '}',
1255 '|' => '|', '||' => '||',
1256 "\x{230A}" => "\x{230B}", # lfloor, rfloor
1257 "\x{2308}" => "\x{2309}", # lceil, rceil
1258 "\x{2329}" => "\x{232A}", # angle brackets; NOT mathematical, but balance in case they show up.
1259 "\x{27E8}" => "\x{27E9}", # angle brackets (preferred)
1260 "\x{2225}" => "\x{2225}", # lVert, rVert
1261 );
1262 # For enclosing a single object
1263 # Note that the default here is just to put open/closed attributes on the single object
1264 my %enclose1 = ( # [CONSTANT]
1265 '{@}' => 'set', # alternatively, just variant parentheses
1266 '|@|' => 'absolute-value',
1267 '||@||' => 'norm', "\x{2225}@\x{2225}" => 'norm',
1268 "\x{230A}@\x{230B}" => 'floor',
1269 "\x{2308}@\x{2309}" => 'ceiling',
1270 '<@>' => 'expectation', # or just average?
1271 '<@|' => 'bra', '|@>' => 'ket');
1272 # For enclosing more than 2 objects; the punctuation is significant too
1273 my %enclose2 = ( # [CONSTANT]
1274 '(@,@)' => 'open-interval', # alternatively, just a list
1275 '[@,@]' => 'closed-interval',
1276 '(@,@]' => 'open-closed-interval', '[@,@)' => 'closed-open-interval',
1277 '{@,@}' => 'set', # alternatively, just a list ?
1278 );
1279 # For enclosing more than 2 objects.
1280 # assume 1st punct? or should we check all are same?
1281 my %encloseN = ( # [CONSTANT]
1282 '(@,@)' => 'vector', '{@,@}' => 'set',);
1283  
1284 sub isMatchingClose {
1285 my ($open, $close) = @_;
1286 my $oname = p_getValue(realizeXMNode($open));
1287 my $cname = p_getValue(realizeXMNode($close));
1288 my $expect = $oname && $balanced{$oname};
1289 return (defined $expect) && (defined $cname) && ($expect eq $cname); }
1290  
1291 # Given a delimited sequence: open expr (punct expr)* close
1292 # (OR, an empty sequence open close)
1293 # Convert it into the appropriate thing, depending on the specific open & close used.
1294 # Generate an XMDual to preserve any styling of delimiters and punctuation.
1295 sub Fence {
1296 my (@stuff) = @_;
1297 # Peak at delimiters to guess what kind of construct this is.
1298 my $nargs = scalar(@stuff);
1299 Error("expected", "arguments", undef,
1300 "Even number of arguments to Fence(); should be of form open,expr,(punct,expr)*,close",
1301 "got " . join(' ', map { ToString($_) } @stuff))
1302 if ($nargs != 2) && (($nargs % 2) == 0); # either empty or odd number
1303 my ($open, $close) = (realizeXMNode($stuff[0]), realizeXMNode($stuff[-1]));
1304 my $o = p_getValue($open);
1305 my $c = p_getValue($close);
1306 my $n = int(($nargs - 2 + 1) / 2);
1307 my @p = map { p_getValue(realizeXMNode(@stuff[2 * $_])) } 1 .. $n - 1;
1308 my $op = ($n == 0
1309 ? 'list' # ?
1310 : ($n == 1
1311 ? $enclose1{ $o . '@' . $c }
1312 : ($n == 2
1313 ? ($enclose2{ $o . '@' . $p[0] . '@' . $c } || 'list')
1314 : ($encloseN{ $o . '@' . $p[0] . '@' . $c } || 'list'))));
1315 $op = 'delimited-' . $o . $c unless defined $op;
1316 my $decl_id = p_getAttribute($open, 'decl_id');
1317 if (($n == 1) && ($op eq 'delimited-()')) { # Hopefully, can just ignore the parens?
1318 return ['ltx:XMDual', {},
1319 LaTeXML::Package::createXMRefs($LaTeXML::MathParser::DOCUMENT, $stuff[1]),
1320 ['ltx:XMWrap', {}, @stuff]]; }
1321 else {
1322 return InterpretDelimited(New($op, undef, ($decl_id ? (decl_id => $decl_id) : ())), @stuff); } }
1323  
1324 # Compose a complex relational operator from two tokens, such as >=, >>
1325 sub TwoPartRelop {
1326 my ($op1, $op2) = @_;
1327 $op1 = Lookup($op1);
1328 $op2 = Lookup($op2);
1329 my $m1 = p_getTokenMeaning($op1);
1330 my $m2 = p_getTokenMeaning($op2);
1331 my $meaning;
1332 if ($m1 eq $m2) {
1333 $meaning = "much-$m1"; }
1334 else {
1335 $meaning = "$m1-or-$m2"; }
1336 my $content = $op1->textContent . $op2->textContent;
1337 return ['ltx:XMTok', { role => "RELOP", meaning => $meaning }, $content]; }
1338  
1339 # NOTE: It might be best to separate the multiple Formulae into separate XMath's???
1340 # but only at the top level!
1341 sub NewFormulae {
1342 my (@stuff) = @_;
1343 if (scalar(@stuff) == 1) {
1344 return $stuff[0]; }
1345 else {
1346 my ($seps, @formula) = extract_separators(@stuff);
1347 return ['ltx:XMDual', {},
1348 Apply(New('formulae'),
1349 LaTeXML::Package::createXMRefs($LaTeXML::MathParser::DOCUMENT, @formula)),
1350 ['ltx:XMWrap', {}, @stuff]]; } }
1351  
1352 # A Formula is an alternation of expr (relationalop expr)*
1353 # It presumably would be equivalent to (expr1 relop1 expr2) AND (expr2 relop2 expr3) ...
1354 # But, I haven't figured out the ideal prefix form that can easily be converted to presentation.
1355 sub NewFormula {
1356 my (@args) = @_;
1357 my $n = scalar(@args);
1358 if ($n == 1) {
1359 return $args[0]; }
1360 elsif ($n == 3) {
1361 return Apply($args[1], $args[0], $args[2]); }
1362 else {
1363 return Apply(New('multirelation'), @args); } }
1364  
1365 sub NewList {
1366 my (@stuff) = @_;
1367 # drop placeholder token for missing trailing punct, if any
1368 if (scalar(@stuff) > 1 && (p_getTokenMeaning($stuff[-1]) eq 'absent')) {
1369 pop(@stuff); }
1370 if (@stuff == 1) {
1371 return $stuff[0]; }
1372 else {
1373 my ($seps, @items) = extract_separators(@stuff);
1374 return ['ltx:XMDual', {},
1375 Apply(New('list'),
1376 LaTeXML::Package::createXMRefs($LaTeXML::MathParser::DOCUMENT, @items)),
1377 ['ltx:XMWrap', {}, @stuff]]; } }
1378  
1379 # Given alternation of expr (addop expr)*, compose the tree (left recursive),
1380 # flattenning portions that have the same operator
1381 # ie. a + b + c - d => (- (+ a b c) d)
1382 sub LeftRec {
1383 my ($arg1, @more) = @_;
1384 if (@more) {
1385 my $op = shift(@more);
1386 my $opname = p_getTokenMeaning(realizeXMNode($op));
1387 my @args = ($arg1, shift(@more));
1388 while (@more && isSameExpr($op, $more[0])) {
1389 ReplacedBy($more[0], $op, 1);
1390 shift(@more);
1391 push(@args, shift(@more)); }
1392 return LeftRec(Apply($op, @args), @more); }
1393 else {
1394 return $arg1; } }
1395  
1396 # Like apply($op,$arg1,$arg2), but if $op is 'same' as the operator in $arg1,
1397 # then combine as an nary apply of $op to $arg1's arguments and $arg2.
1398 sub ApplyNary {
1399 my ($op, $arg1, $arg2) = @_;
1400 my $rop = realizeXMNode($op);
1401 my $opname = p_getTokenMeaning($rop) || '__undef_meaning__';
1402 my $opcontent = p_getValue($rop) || '__undef_content__';
1403 my @args = ();
1404 if (p_getQName($arg1) eq 'ltx:XMApp') {
1405 my ($op1, @args1) = p_element_nodes($arg1);
1406 my $rop1 = realizeXMNode($op1);
1407 if (isSameExpr($rop, $rop1)
1408 # Check that arg1 isn't wrapped, fenced or enclosed in some restrictive way
1409 # Especially an ID! (but really only important if the id is referenced somewhere?)
1410 && !(grep { p_getAttribute(realizeXMNode($arg1), $_) } qw(enclose xml:id))) {
1411 # Note that $op1 GOES AWAY!!!
1412 ReplacedBy($op1, $rop, 1);
1413 push(@args, @args1); }
1414 else {
1415 push(@args, $arg1); } }
1416 else {
1417 push(@args, $arg1); }
1418 return Apply($op, @args, $arg2); }
1419  
1420 # Usually we just expect to compare a token + to another.
1421 # but want (to some extent) to deal with embellished operators (eg. sub, sup...)
1422 # Rather involved if we want to try to do it "Right".
1423 sub isSameExpr {
1424 my ($op1, $op2) = @_;
1425 $op1 = realizeXMNode($op1);
1426 $op2 = realizeXMNode($op2);
1427 my $tag1 = getQName($op1);
1428 my $tag2 = getQName($op2);
1429 # Either both are tokens,
1430 # OR both have structure, but then we need to compare the children!!!!
1431 # First check, same top-level and critical attributes
1432 return unless
1433 ($tag1 eq $tag2)
1434 && ((p_getTokenMeaning($op1) || '__undef_meaning__')
1435 eq (p_getTokenMeaning($op2) || '__undef_meaning__'))
1436 && ((p_getValue($op1) || '__undef_content__')
1437 eq (p_getValue($op2) || '__undef_content__'))
1438 # Check that ops are used in same way.
1439 && ((p_getAttribute($op1, 'mathstyle') || '<none>')
1440 eq (p_getAttribute($op2, 'mathstyle') || '<none>'));
1441 if ($tag1 eq 'ltx:XMTok') { return 1; } # If tokens, they match
1442 else {
1443 my @ch1 = p_element_nodes($op1);
1444 my @ch2 = p_element_nodes($op2);
1445 my $n = scalar(@ch1);
1446 return unless $n == scalar(@ch2);
1447 foreach my $i (0 .. $n - 1) {
1448 return unless isSameExpr($ch1[$i], $ch1[$i]); }
1449 return 1; } }
1450  
1451 # There are several cases where parsing a formula will rearrange nodes
1452 # such that some nodes will no-longer be used. For example, when
1453 # converting a nested set of infix + into a single n-ary sum.
1454 # In effect, all those excess +'s are subsumed by the single first one.
1455 # It may be, however, that those lost nodes are referenced (XMRef) from the
1456 # other branch of an XMDual, and those references should be updated to refer
1457 # to the single node replacing the lost ones.
1458 # This function records that replacement, and the top-level parser fixes up the tree.
1459 # NOTE: There may be cases (in the Grammar, eg) where punctuation & ApplyOp's
1460 # get lost completely? Watch out for this!
1461 # If $isdup, assume the two trees are equivalent structure,
1462 # and so mark corresponding internal nodes as "replaced" as well.
1463 sub ReplacedBy {
1464 my ($lostnode, $keepnode, $isdup) = @_;
1465 return unless ref $lostnode && ref $keepnode;
1466 if (my $lostid = p_getAttribute($lostnode, 'xml:id')) {
1467 # Could be we want to generate an id for $keepnode, here?
1468 if (my $keepid = p_getAttribute($keepnode, 'xml:id')) {
1469 $$LaTeXML::MathParser::LOSTNODES{$lostid} = $keepid; }
1470 else {
1471 Warn('expected', 'id', undef, "LOST $lostid but no replacement!\n"); } }
1472  
1473 # The following recurses into the two trees,
1474 # This is on the assumption that they are "equivalent" trees
1475 if ($isdup) {
1476 my @lostkids = p_element_nodes($lostnode);
1477 my @keepkids = p_element_nodes($keepnode);
1478 my $n = scalar(@lostkids);
1479 my $m = scalar(@keepkids);
1480 if ($n != $m) {
1481 Error("unexpected", "nodes", undef, "Nodes aren't the same structure ($n vs $m)",
1482 "Old: " . printNode($lostnode),
1483 "New: " . printNode($keepnode)
1484 );
1485 $n = $m if $m < $n; }
1486 foreach my $i (0 .. $n - 1) {
1487 ReplacedBy($lostkids[$i], $keepkids[$i], $isdup); } }
1488 return; }
1489  
1490 # ================================================================================
1491 # Construct an appropriate application of sub/superscripts
1492 # This accounts for script positioning:
1493 # Whether it precedes (float), is over/under (if base requests),
1494 # or follows (normal case), along with whether sub/super.
1495 # the alignment of multiple sub/superscripts derived from the binding level when created.
1496 # scriptpos = (pre|mod|post) number; where number is the binding-level.
1497 # If $pos is given (pre|mid|post), it overrides the position implied by the script
1498 sub NewScript {
1499 my ($base, $script, $pos) = @_;
1500 my $role;
1501 my $rbase = realizeXMNode($base);
1502 my $rscript = realizeXMNode($script);
1503 my $ibase = $rbase;
1504 # Get "inner" (content) base, if the base is a dual it may be more relevant
1505 if (p_getQName($rbase) eq 'ltx:XMDual') {
1506 ($ibase) = p_element_nodes($rbase); }
1507 elsif (p_getQName($rbase) eq 'ltx:XMApp') {
1508 my ($op, $a1, @rest) = p_element_nodes($rbase);
1509 if ((p_getQName($op) eq 'ltx:XMTok')
1510 && ((p_getAttribute($op, 'role') || '') =~ /^(FLOAT|POST)?(SUB|SUPER)SCRIPT(OP)?$/)) {
1511 $ibase = $op; } }
1512 my @bsp = grep { $_ } (p_getAttribute($rbase, 'scriptpos'),
1513 p_getAttribute($rbase, 'scriptpos'),
1514 p_getAttribute($ibase, 'scriptpos'),
1515 'post');
1516 my ($bx) = grep { $_ } map { /^(pre|mid|post)?(\d+)?$/ && $1; } @bsp;
1517 my ($bl) = grep { $_ } map { /^(pre|mid|post)?(\d+)?$/ && $2; } @bsp;
1518 my ($sx, $sl) = (p_getAttribute($rscript, 'scriptpos') || 'post') =~ /^(pre|mid|post)?(\d+)?$/;
1519 $bl = ($sl || 1) unless $bl;
1520 $sl = ($bl || 1) unless $sl;
1521 $sx = ($bl == $sl ? $bx : 'post') unless $sx;
1522 my ($mode, $y) = p_getAttribute($rscript, 'role') =~ /^(FLOAT|POST)?(SUB|SUPER)SCRIPT$/;
1523 my $x = ($pos ? $pos : ($mode eq 'FLOAT' ? 'pre'
1524 : ($bl == $sl ? $bx : $sx) || 'post'));
1525 my $lpad = ($x eq 'pre') && p_getAttribute($rscript, 'lpadding');
1526 my $rpad = ($x ne 'pre') && p_getAttribute($rscript, 'rpadding');
1527 my $t;
1528 my $l = $sl || $bl ||
1529 (($t = $LaTeXML::MathParser::DOCUMENT->getNodeBox($script))
1530 && ($t->getProperty('scriptlevel'))) || 0;
1531 # If the INNER script was a floating script (ie. {}^{x})
1532 # we'll NOT want this one to stack over it so bump the level.
1533 my $bumped;
1534 if (p_getAttribute($rbase, '_wasfloat')) {
1535 $l++; $bumped = 1 }
1536 elsif (my $innerl = p_getAttribute($rbase, '_bumplevel')) {
1537 $l = $innerl; }
1538 my $app = Apply(New(undef, undef, role => $y . 'SCRIPTOP', scriptpos => "$x$l"),
1539 $base, Arg($script, 0));
1540 # Record whether this script was a floating one
1541 $$app[1]{_wasfloat} = 1 if $mode eq 'FLOAT';
1542 $$app[1]{_bumplevel} = $l if $bumped;
1543 $$app[1]{lpadding} = $lpad if $lpad && !$$app[1]{lpadding}; # better to add?
1544 $$app[1]{rpadding} = $rpad if $rpad && !$$app[1]{rpadding}; # better to add?
1545 return $app; }
1546  
1547 # Basically, like NewScript, but decorates an operator with sub/superscripts
1548 # (with vague unknown implications for meaning?)
1549 # but which will preserve the role (& meaning?)
1550 sub DecorateOperator {
1551 my ($op, $script) = @_;
1552 my $decop = NewScript($op, $script);
1553 my $rop = realizeXMNode($op);
1554 my $role = p_getAttribute($rop, 'role');
1555 return Annotate($decop, role => $role); }
1556  
1557 sub NewEvalAt {
1558 my ($base, $vertbar, $lower, $upper) = @_;
1559 my $pres = ['ltx:XMWrap', {}, $base, Annotate($vertbar, role => 'CLOSE')];
1560 $pres = NewScript($pres, $lower) if $lower;
1561 $pres = NewScript($pres, $upper) if $upper;
1562 return ['ltx:XMDual', {},
1563 ['ltx:XMApp', {},
1564 ['ltx:XMTok', { meaning => 'evaluated-at' }],
1565 LaTeXML::Package::createXMRefs($LaTeXML::MathParser::DOCUMENT,
1566 $base,
1567 ($lower ? (Arg($lower, 0)) : ()),
1568 ($upper ? (Arg($upper, 0)) : ()))],
1569 $pres]; }
1570  
1571 # ================================================================================
1572 # A "notation" is a language construct or set thereof.
1573  
1574 # Called from the grammar to record the fact that a notation was seen.
1575 sub SawNotation {
1576 my ($notation, $node) = @_;
1577 $LaTeXML::MathParser::SEEN_NOTATIONS{$notation} = 1;
1578 return 1; }
1579  
1580 # Called by the grammar to determine whether we should try productions
1581 # which involve the given notation.
1582 sub IsNotationAllowed {
1583 my ($notation) = @_;
1584 return ($LaTeXML::MathParser::DISALLOWED_NOTATIONS{$notation} ? undef : 1); }
1585  
1586 # ================================================================================
1587  
1588 # Note that an UNKNOWN token may have been used as a function.
1589 # For simplicity in the grammar, we accept a token that has sub|super scripts applied.
1590 sub MaybeFunction {
1591 my ($token) = @_;
1592 $token = realizeXMNode($token);
1593 my $self = $LaTeXML::MathParser::PARSER;
1594 while (p_getQName($token) eq 'ltx:XMApp') {
1595 $token = Arg($token, 1); }
1596 my $name = token_prettyname($token);
1597 # DANGER!!
1598 # We want to be using Annotate here, but we're screwed up by the
1599 # potential "embellishing" of the function token.
1600 # (ie. the descent above past all XMApp's)
1601 $token->setAttribute('possibleFunction', 'yes');
1602 $$self{maybe_functions}{$name}++
1603 if $LaTeXML::MathParser::STRICT && !$$self{suspicious_tokens}{$token};
1604 $$self{suspicious_tokens}{$token} = 1;
1605 return; }
1606  
1607 # ================================================================================
1608 1;
1609  
1610 __END__