lib/LaTeXML/MathParser.pm untested

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