This file is indexed.

/usr/share/perl5/LaTeXML/MathParser.pm is in latexml 0.8.0-1.

This file is owned by root:root, with mode 0o644.

The actual contents of the file can be viewed below.

   1
   2
   3
   4
   5
   6
   7
   8
   9
  10
  11
  12
  13
  14
  15
  16
  17
  18
  19
  20
  21
  22
  23
  24
  25
  26
  27
  28
  29
  30
  31
  32
  33
  34
  35
  36
  37
  38
  39
  40
  41
  42
  43
  44
  45
  46
  47
  48
  49
  50
  51
  52
  53
  54
  55
  56
  57
  58
  59
  60
  61
  62
  63
  64
  65
  66
  67
  68
  69
  70
  71
  72
  73
  74
  75
  76
  77
  78
  79
  80
  81
  82
  83
  84
  85
  86
  87
  88
  89
  90
  91
  92
  93
  94
  95
  96
  97
  98
  99
 100
 101
 102
 103
 104
 105
 106
 107
 108
 109
 110
 111
 112
 113
 114
 115
 116
 117
 118
 119
 120
 121
 122
 123
 124
 125
 126
 127
 128
 129
 130
 131
 132
 133
 134
 135
 136
 137
 138
 139
 140
 141
 142
 143
 144
 145
 146
 147
 148
 149
 150
 151
 152
 153
 154
 155
 156
 157
 158
 159
 160
 161
 162
 163
 164
 165
 166
 167
 168
 169
 170
 171
 172
 173
 174
 175
 176
 177
 178
 179
 180
 181
 182
 183
 184
 185
 186
 187
 188
 189
 190
 191
 192
 193
 194
 195
 196
 197
 198
 199
 200
 201
 202
 203
 204
 205
 206
 207
 208
 209
 210
 211
 212
 213
 214
 215
 216
 217
 218
 219
 220
 221
 222
 223
 224
 225
 226
 227
 228
 229
 230
 231
 232
 233
 234
 235
 236
 237
 238
 239
 240
 241
 242
 243
 244
 245
 246
 247
 248
 249
 250
 251
 252
 253
 254
 255
 256
 257
 258
 259
 260
 261
 262
 263
 264
 265
 266
 267
 268
 269
 270
 271
 272
 273
 274
 275
 276
 277
 278
 279
 280
 281
 282
 283
 284
 285
 286
 287
 288
 289
 290
 291
 292
 293
 294
 295
 296
 297
 298
 299
 300
 301
 302
 303
 304
 305
 306
 307
 308
 309
 310
 311
 312
 313
 314
 315
 316
 317
 318
 319
 320
 321
 322
 323
 324
 325
 326
 327
 328
 329
 330
 331
 332
 333
 334
 335
 336
 337
 338
 339
 340
 341
 342
 343
 344
 345
 346
 347
 348
 349
 350
 351
 352
 353
 354
 355
 356
 357
 358
 359
 360
 361
 362
 363
 364
 365
 366
 367
 368
 369
 370
 371
 372
 373
 374
 375
 376
 377
 378
 379
 380
 381
 382
 383
 384
 385
 386
 387
 388
 389
 390
 391
 392
 393
 394
 395
 396
 397
 398
 399
 400
 401
 402
 403
 404
 405
 406
 407
 408
 409
 410
 411
 412
 413
 414
 415
 416
 417
 418
 419
 420
 421
 422
 423
 424
 425
 426
 427
 428
 429
 430
 431
 432
 433
 434
 435
 436
 437
 438
 439
 440
 441
 442
 443
 444
 445
 446
 447
 448
 449
 450
 451
 452
 453
 454
 455
 456
 457
 458
 459
 460
 461
 462
 463
 464
 465
 466
 467
 468
 469
 470
 471
 472
 473
 474
 475
 476
 477
 478
 479
 480
 481
 482
 483
 484
 485
 486
 487
 488
 489
 490
 491
 492
 493
 494
 495
 496
 497
 498
 499
 500
 501
 502
 503
 504
 505
 506
 507
 508
 509
 510
 511
 512
 513
 514
 515
 516
 517
 518
 519
 520
 521
 522
 523
 524
 525
 526
 527
 528
 529
 530
 531
 532
 533
 534
 535
 536
 537
 538
 539
 540
 541
 542
 543
 544
 545
 546
 547
 548
 549
 550
 551
 552
 553
 554
 555
 556
 557
 558
 559
 560
 561
 562
 563
 564
 565
 566
 567
 568
 569
 570
 571
 572
 573
 574
 575
 576
 577
 578
 579
 580
 581
 582
 583
 584
 585
 586
 587
 588
 589
 590
 591
 592
 593
 594
 595
 596
 597
 598
 599
 600
 601
 602
 603
 604
 605
 606
 607
 608
 609
 610
 611
 612
 613
 614
 615
 616
 617
 618
 619
 620
 621
 622
 623
 624
 625
 626
 627
 628
 629
 630
 631
 632
 633
 634
 635
 636
 637
 638
 639
 640
 641
 642
 643
 644
 645
 646
 647
 648
 649
 650
 651
 652
 653
 654
 655
 656
 657
 658
 659
 660
 661
 662
 663
 664
 665
 666
 667
 668
 669
 670
 671
 672
 673
 674
 675
 676
 677
 678
 679
 680
 681
 682
 683
 684
 685
 686
 687
 688
 689
 690
 691
 692
 693
 694
 695
 696
 697
 698
 699
 700
 701
 702
 703
 704
 705
 706
 707
 708
 709
 710
 711
 712
 713
 714
 715
 716
 717
 718
 719
 720
 721
 722
 723
 724
 725
 726
 727
 728
 729
 730
 731
 732
 733
 734
 735
 736
 737
 738
 739
 740
 741
 742
 743
 744
 745
 746
 747
 748
 749
 750
 751
 752
 753
 754
 755
 756
 757
 758
 759
 760
 761
 762
 763
 764
 765
 766
 767
 768
 769
 770
 771
 772
 773
 774
 775
 776
 777
 778
 779
 780
 781
 782
 783
 784
 785
 786
 787
 788
 789
 790
 791
 792
 793
 794
 795
 796
 797
 798
 799
 800
 801
 802
 803
 804
 805
 806
 807
 808
 809
 810
 811
 812
 813
 814
 815
 816
 817
 818
 819
 820
 821
 822
 823
 824
 825
 826
 827
 828
 829
 830
 831
 832
 833
 834
 835
 836
 837
 838
 839
 840
 841
 842
 843
 844
 845
 846
 847
 848
 849
 850
 851
 852
 853
 854
 855
 856
 857
 858
 859
 860
 861
 862
 863
 864
 865
 866
 867
 868
 869
 870
 871
 872
 873
 874
 875
 876
 877
 878
 879
 880
 881
 882
 883
 884
 885
 886
 887
 888
 889
 890
 891
 892
 893
 894
 895
 896
 897
 898
 899
 900
 901
 902
 903
 904
 905
 906
 907
 908
 909
 910
 911
 912
 913
 914
 915
 916
 917
 918
 919
 920
 921
 922
 923
 924
 925
 926
 927
 928
 929
 930
 931
 932
 933
 934
 935
 936
 937
 938
 939
 940
 941
 942
 943
 944
 945
 946
 947
 948
 949
 950
 951
 952
 953
 954
 955
 956
 957
 958
 959
 960
 961
 962
 963
 964
 965
 966
 967
 968
 969
 970
 971
 972
 973
 974
 975
 976
 977
 978
 979
 980
 981
 982
 983
 984
 985
 986
 987
 988
 989
 990
 991
 992
 993
 994
 995
 996
 997
 998
 999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
# /=====================================================================\ #
# |  LaTeXML::MathParser                                                | #
# | Parse Math                                                          | #
# |=====================================================================| #
# | Part of LaTeXML:                                                    | #
# |  Public domain software, produced as part of work done by the       | #
# |  United States Government & not subject to copyright in the US.     | #
# |---------------------------------------------------------------------| #
# | Bruce Miller <bruce.miller@nist.gov>                        #_#     | #
# | http://dlmf.nist.gov/LaTeXML/                              (o o)    | #
# \=========================================================ooo==U==ooo=/ #
# ================================================================================
# LaTeXML::MathParser  Math Parser for LaTeXML using Parse::RecDescent.
# Parse the intermediate representation generated by the TeX processor.
# ================================================================================
package LaTeXML::MathParser;
use strict;
use warnings;
use Parse::RecDescent;
use LaTeXML::Global;
use LaTeXML::Common::Object;
use LaTeXML::Common::Error;
use LaTeXML::Core::Token;
use LaTeXML::Common::Font;
use LaTeXML::Common::XML;
use base (qw(Exporter));

our @EXPORT_OK = (qw(&Lookup &New &Absent &Apply &ApplyNary &recApply
    &Annotate &InvisibleTimes &InvisibleComma
    &NewFormulae &NewFormula &NewList
    &ApplyDelimited &NewScript &DecorateOperator
    &LeftRec
    &Arg &MaybeFunction
    &SawNotation &IsNotationAllowed
    &isMatchingClose &Fence));
our %EXPORT_TAGS = (constructors
    => [qw(&Lookup &New &Absent &Apply &ApplyNary &recApply
      &Annotate &InvisibleTimes &InvisibleComma
      &NewFormulae &NewFormula &NewList
      &ApplyDelimited &NewScript &DecorateOperator
      &LeftRec
      &Arg &MaybeFunction
      &SawNotation &IsNotationAllowed
      &isMatchingClose &Fence)]);

my $DEFAULT_FONT = LaTeXML::Common::Font->new(    # [CONSTANT]
  family => 'serif',   series     => 'medium',
  shape  => 'upright', size       => 'normal',
  color  => 'black',   background => 'white', opacity => 1);

# ================================================================================
sub new {
  my ($class, %options) = @_;
  require LaTeXML::MathGrammar;

  my $internalparser = LaTeXML::MathGrammar->new();
  Fatal("expected", "MathGrammar", undef,
    "Compilation of Math Parser grammar failed") unless $internalparser;

  my $self = bless { internalparser => $internalparser }, $class;
  return $self; }

sub parseMath {
  my ($self, $document, %options) = @_;
  local $LaTeXML::MathParser::DOCUMENT = $document;
  $self->clear;    # Not reentrant!
  if (my @math = $document->findnodes('descendant-or-self::ltx:XMath[not(ancestor::ltx:XMath)]')) {
    NoteBegin("Math Parsing"); NoteProgress(scalar(@math) . " formulae ...");
#### SEGFAULT TEST
####    $document->doctest("before parse",1);
    foreach my $math (@math) {
      $self->parse($math, $document); }

    NoteProgress("\nMath parsing succeeded:"
        . join('', map { "\n   $_: "
            . $$self{passed}{$_} . "/" . ($$self{passed}{$_} + $$self{failed}{$_}) }
          grep { $$self{passed}{$_} + $$self{failed}{$_} }
          keys %{ $$self{passed} }) . "\n");
    if (my @unk = keys %{ $$self{unknowns} }) {
      NoteProgress("Symbols assumed as simple identifiers (with # of occurences):\n   "
          . join(', ', map { "'$_' ($$self{unknowns}{$_})" } sort @unk) . "\n"); }
    if (my @funcs = keys %{ $$self{maybe_functions} }) {
      NoteProgress("Possibly used as functions?\n  "
          . join(', ', map { "'$_' ($$self{maybe_functions}{$_}/$$self{unknowns}{$_} usages)" }
            sort @funcs) . "\n"); }
#### SEGFAULT TEST
####    $document->doctest("IN scope",1);
    NoteEnd("Math Parsing"); }
#### SEGFAULT TEST
####    $document->doctest("OUT of scope",1);
  return $document; }

sub getQName {
  my ($node) = @_;
  return $LaTeXML::MathParser::DOCUMENT->getModel->getNodeQName($node); }

# ================================================================================
sub clear {
  my ($self) = @_;
  $$self{passed} = { 'ltx:XMath' => 0, 'ltx:XMArg' => 0, 'ltx:XMWrap' => 0 };
  $$self{failed} = { 'ltx:XMath' => 0, 'ltx:XMArg' => 0, 'ltx:XMWrap' => 0 };
  $$self{unknowns}        = {};
  $$self{maybe_functions} = {};
  $$self{n_parsed}        = 0;
  return; }

sub token_prettyname {
  my ($node) = @_;
  my $name = $node->getAttribute('name');
  if (defined $name) { }
  elsif ($name = $node->textContent) {
    my $font = $LaTeXML::MathParser::DOCUMENT->getNodeFont($node);
    my %attr = $font->relativeTo($DEFAULT_FONT);
    my $desc = join(' ', map { ToString($_) } values %attr);
    $name .= "{$desc}" if $desc; }
  else {
    $name = Stringify($node); }    # what else ????
  return $name; }

sub note_unknown {
  my ($self, $node) = @_;
  my $name = token_prettyname($node);
  $$self{unknowns}{$name}++;
  return; }

# debugging utility, should be somewhere handy.
sub printNode {
  my ($node) = @_;
  if (ref $node eq 'ARRAY') {
    my ($tag, $attr, @children) = @$node;
    my @keys = sort keys %$attr;
    return "<$tag"
      . (@keys ? ' ' . join(' ', map { "$_='$$attr{$_}'" } @keys) : '')
      . (@children
      ? ">\n" . join('', map { printNode($_) } @children) . "</$tag>"
      : '/>')
      . "\n"; }
  else {
    return ToString($node); } }

# ================================================================================
# Some more XML utilities, but math specific (?)

# Get the Token's  meaning, else name, else content, else role
sub getTokenMeaning {
  my ($node) = @_;
  my $x;
  return (defined($x = $node->getAttribute('meaning')) ? $x
    : (defined($x = $node->getAttribute('name')) ? $x
      : (($x = $node->textContent) ne '' ? $x
        : (defined($x = $node->getAttribute('role')) ? $x
          : undef)))); }

sub node_location {
  my ($node) = @_;
  my $n = $node;
  while ($n && (ref $n !~ /^XML::LibXML::Document/)    # Sometimes DocuementFragment ???
    && !$n->getAttribute('refnum') && !$n->getAttribute('labels')) {
    $n = $n->parentNode; }
  if ($n && (ref $n !~ /^XML::LibXML::Document/)) {
    my ($r, $l) = ($n->getAttribute('refnum'), $n->getAttribute('labels'));
    return ($r && $l ? "$r ($l)" : $r || $l); }
  else {
    return 'Unknown'; } }

#%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
# Parser
#%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
# Top-level per-formula parse.
# We do a depth-first traversal of the content of the XMath element,
# since various sub-elements (XMArg & XMWrap) act as containers of
# nominally complete subexpressions.
# We do these first for two reasons.
# Firstly, since after parsing, the parent will be rebuilt from the result,
# we lose the node "identity"; ie. we can't find the child to replace it!
# Secondly, in principle (although this isn't used yet), parsing the
# child could reveal something interesting about it; say, it's effective role.
# Then, this information could be used when parsing the parent.
# In fact, this could work the other way too; parsing the parent could tell
# us something about what the child must be....
sub parse {
  my ($self, $xnode, $document) = @_;
  local $LaTeXML::MathParser::STRICT = 1;
  local $LaTeXML::MathParser::WARNED = 0;
  local $LaTeXML::MathParser::XNODE  = $xnode;

  if (my $result = $self->parse_rec($xnode, 'Anything,', $document)) {
    # Add text representation to the containing Math element.
    my $p = $xnode->parentNode;
    # This is a VERY screwy situation? How can the parent be a document fragment??
    # This has got to be a LibXML bug???
    if ($p->nodeType == XML_DOCUMENT_FRAG_NODE) {
      my @n = $p->childNodes;
      if (scalar(@n) == 1) {
        $p = $n[0]; }
      else {
        Fatal('malformed', '<XMath>', $xnode, "XMath node has DOCUMENT_FRAGMENT for parent!"); } }
    $p->setAttribute('text', text_form($result)); }
  return; }

my %TAG_FEEDBACK = ('ltx:XMArg' => 'a', 'ltx:XMWrap' => 'w');    # [CONSTANT]
# Recursively parse a node with some internal structure
# by first parsing any structured children, then it's content.
sub parse_rec {
  my ($self, $node, $rule, $document) = @_;
  $self->parse_children($node, $document);
  # This will only handle 1 layer nesting (successfully?)
  # Note that this would have been found by the top level xpath,
  # but we've got to worry about node identity: the parent is being rebuilt
  foreach my $nested ($document->findnodes('descendant::ltx:XMath', $node)) {
    $self->parse($nested, $document); }
  my $tag = getQName($node);
  if (my $requested_rule = $node->getAttribute('rule')) {
    $rule = $requested_rule; }
  if (my $result = $self->parse_single($node, $document, $rule)) {
    $$self{passed}{$tag}++;
    if ($tag eq 'ltx:XMath') {    # Replace the content of XMath with parsed result
      NoteProgress('[' . ++$$self{n_parsed} . ']');
      map { $document->unRecordNodeIDs($_) } element_nodes($node);
      map { $_->unbindNode() } $node->childNodes;
      $document->appendTree($node, $result);
      $result = [element_nodes($node)]->[0]; }
    else {                        # Replace the whole node for XMArg, XMWrap; preserve some attributes
      NoteProgressDetailed($TAG_FEEDBACK{$tag} || '.');
      # Copy all attributes (Annotate will sort out)
      $result = Annotate($result,
        map { (getQName($_) => $_->getValue) }
          grep { $_->nodeType == XML_ATTRIBUTE_NODE } $node->attributes);
      $result = $document->replaceTree($result, $node); }
    return $result; }
  else {
    $self->parse_kludge($node, $document);
    if ($tag eq 'ltx:XMath') {
      NoteProgress('[F' . ++$$self{n_parsed} . ']'); }
    elsif ($tag eq 'ltx:XMArg') {
      NoteProgressDetailed('-a'); }
    $$self{failed}{$tag}++;
    return; } }

# Depth first parsing of XMArg nodes.
sub parse_children {
  my ($self, $node, $document) = @_;
  foreach my $child (element_nodes($node)) {
    my $tag = getQName($child);
    if ($tag eq 'ltx:XMArg') {
      $self->parse_rec($child, 'Anything', $document); }
    elsif ($tag eq 'ltx:XMWrap') {
      local $LaTeXML::MathParser::STRICT = 0;
      $self->parse_rec($child, 'Anything', $document); }
### A nice evolution would be to use the Kludge parser for
### the presentation form in XMDual
### This would avoid silly "parses" of non-semantic stuff; eg assuming times between tokens!
### However, it needs some experimentation to match DLMF's enhancements
####      $self->parse_children($child,$document);
####      $self->parse_kludge($child,$document); }
    elsif ($tag =~ /^ltx:(XMApp|XMArray|XMRow|XMCell)$/) {
      $self->parse_children($child, $document); }
    elsif ($tag eq 'ltx:XMDual') {
      $self->parse_children($child, $document); } }
  return; }

my $HINT_PUNCT_THRESHOLD = 10.0;    # \quad or bigger becomes punctuation ? [CONSTANT]

sub filter_hints {
  my ($self, $document, @nodes) = @_;
  my @filtered = ();
  my $prev     = undef;
  while (@nodes) {
    my $c = shift(@nodes);
    if (getQName($c) ne 'ltx:XMHint') {    # Is it NOT a Hint node?
      push(@filtered, $c); $prev = $c; }    # Keep it.
    elsif (my $width = $c->getAttribute('width')) {    # Is it a spacing hint?
          # Get the pts (combining w/any following spacing hints)
      my $pts = getXMHintSpacing($width);
      while (@nodes && (getQName($nodes[0]) eq 'ltx:XMHint')    # Combine w/ more?
        && ($width = $c->getAttribute('width'))) {
        $pts += getXMHintSpacing($width);
        shift(@nodes); }                                        # and remove the extra hints
          # A wide space, between Stuff, is likely acting like punctuation, so convert it
      if ($prev && (($prev->getAttribute('role') || '') ne 'PUNCT')
        && scalar(@nodes) && ($pts >= $HINT_PUNCT_THRESHOLD)) {
        $c = $c->cloneNode(1); $c->setNodeName('XMTok');
        $c->removeAttribute('width');
        $c->removeAttribute('height');    # ?
        $c->setAttribute(role => 'PUNCT');    # convert to punctuation!
        $c->appendText(spacingToString($pts));
        push(@filtered, $c); }
      else {
        if ($pts) {
          if ($prev) {                        # Else add rpadding to previous item
            $prev->setAttribute(rpadding => $pts . 'pt'); }
          elsif (scalar(@nodes)) {            # or maybe lpadding to next??
            $nodes[0]->setAttribute(lpadding => $pts . 'pt'); }
        } }
      $prev = undef; }                        # at any rate, remove it now
    else {
      $prev = undef; } }                      # other hint; remove it now
  return @filtered; }

# Given a width attribute on an XMHint, return the pts, if any
sub getXMHintSpacing {
  my ($width) = @_;
  if ($width && ($width =~ /^$LaTeXML::Common::Glue::GLUE_re$/)) {
    return ($2 eq 'mu' ? $1 / 1.8 : $1); }
  else {
    return 0; } }

# We've pretty much builtin the assumption that the target XML is "As If" 10 pts,
# so we'll assume that 1em is 10 pts.
my $POINTS_PER_EM = 10.0;    # [CONSTANT]
# Convert spacing, given as a number of points, to a string of appropriate spacing chars
sub spacingToString {
  my ($points) = @_;
  my $spacing  = '';
  my $ems      = $points / $POINTS_PER_EM;
  my $n        = int($ems);
  if ($n > 0)       { $spacing .= ("\x{2003}" x $n); $ems -= $n; }
  if ($ems > 0.500) { $spacing .= "\x{2002}";        $ems -= 0.500; }
  if ($ems > 0.333) { $spacing .= "\x{2003}";        $ems -= 0.333; }
  if ($ems > 0.250) { $spacing .= "\x{2005}";        $ems -= 0.250; }
  if ($ems > 0.166) { $spacing .= "\x{2006}";        $ems -= 0.166; }
  return $spacing; }

#%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
# Low-Level hack parsing when "real" parsing fails;
# Two issues cause generated Presentation MathML to be really bad:
# (1) not having mrow/mfenced structures wrapping OPEN...CLOSE sequences
#     throws off MathML's stretchiness treatment of the fences
#     (they're all the same size; big)
# (2) un-attached sub/superscripts won't position correctly,
#     unless they're attached to something plausible.
# NOTE: we should be able to optionally switch this off.
# Especially, when we want to try alternative parse strategies.
sub parse_kludge {
  my ($self, $mathnode, $document) = @_;
  my @nodes = $self->filter_hints($document, element_nodes($mathnode));
  # the 1st array in stack accumlates the nodes within the current fenced row.
  # When there's only a single array, it's single entry will be the complete row.
  my @stack = ([], []);
  my @pairs = map { [$_, $self->getGrammaticalRole($_)] } @nodes;
  while (scalar(@pairs) || (scalar(@stack) > 1)) {
    my $pair = shift(@pairs);
    my $role = ($pair ? $$pair[1] : 'CLOSE');
    if ($role eq 'OPEN') {
      unshift(@stack, [$pair]); }    # Start new fenced row;
    elsif ($role eq 'CLOSE') {       # Close the current row
      my $row = shift(@stack);       # get the current list of items
      push(@$row, $pair) if $pair;   # Put the close (if any) into it
      my @kludged = $self->parse_kludgeScripts_rec(@$row);    # handle scripts
                                                              # wrap, if needed.
      $row = [(scalar(@kludged) > 1 ? ['ltx:XMWrap', {}, @kludged] : $kludged[0]), 'FENCED'];
      push(@{ $stack[0] }, $row); }    # and put this constructed row at end of containing row.
    else {
      push(@{ $stack[0] }, $pair); } }    # Otherwise, just put this item into current row.

  # If we got to here, remove the nodes and replace them by the kludged structure.
  map { $document->unRecordNodeIDs($_) } element_nodes($mathnode);
  map { $_->unbindNode() } $mathnode->childNodes;
  # We're hoping for a single list on the stack,
  # But extra CLOSEs will leave extra junk behind, so process all the stacked lists.
  my @replacements = ();
  foreach my $pair (@{ $stack[0] }) {
    my $kludge = $$pair[0];
    push(@replacements, (ref $kludge eq 'ARRAY') && ($$kludge[0] eq 'ltx:XMWrap')
      ? @$kludge[2 .. $#$kludge] : ($kludge)); }
  $document->appendTree($mathnode, @replacements);
  return; }

sub parse_kludgeScripts_rec {
  my ($self, $a, $b, @more) = @_;
  if (!defined $b) {
    return ($$a[0]); }
  elsif ($$a[1] =~ /^FLOAT(SUB|SUPER)SCRIPT$/) {
    # A floating script is applied to the following thing as a pre-script.
    my ($base, @rest) = $self->parse_kludgeScripts_rec($b, @more);
    return (NewScript($base, $$a[0]), @rest); }
  elsif ($$b[1] =~ /^POST(SUB|SUPER)SCRIPT$/) {
    # or a postscript is applied to the preceding thing.
    return $self->parse_kludgeScripts_rec([NewScript($$a[0], $$b[0]), ''], @more); }
  else {
    return ($$a[0], $self->parse_kludgeScripts_rec($b, @more)); } }

# sub parse_kludge {
#   my($self,$mathnode,$document)=@_;
#   my @nodes = $self->filter_hints($document,element_nodes($mathnode));
#   map { $mathnode->removeChild($_) } @nodes;
#   my @result=();
#   while(@nodes){
#     @nodes = $self->parse_kludge_rec(@nodes);
#     push(@result,shift(@nodes)); }
#   $document->appendTree($mathnode,@result); }

# # Kludge Parse the next thing, and then add any following scripts to it.
# sub parse_kludge_rec {
#   my($self,@more)=@_;
#   my($item,$open,$close,$seps,$arg);
#   ($item,@more) = $self->parse_kludge_reca(@more);
#   while(@more && (($self->getGrammaticalRole($more[0])||'') =~ /^POST(SUB|SUPER)SCRIPT$/)){
#     $item = NewScript($item,shift(@more)); }
#   if(@more && (($self->getGrammaticalRole($more[0])||'') eq 'APPLYOP')){
#     shift(@more);
#     if(@more && (($self->getGrammaticalRole($more[0])||'') eq 'OPEN')){
#       ($open,$close,$seps,$arg,@more)=$self->parse_kludge_fence(@more);
#       $item = Apply(Annotate($item,argopen=>$open, argclose=>$close, separators=>$seps),@$arg); }
#     else {
#       ($arg,@more)=$self->parse_kludge_rec(@more);
#       $item = Apply($item,$arg); }}
#   ($item,@more); }

# sub parse_kludge_reca {
#   my($self,$next,@more)=@_;
#   my $role = $self->getGrammaticalRole($next);
#   if($role =~ /^FLOAT(SUB|SUPER)SCRIPT$/){
#     my($base,@rest) = $self->parse_kludge_rec(@more);
#     (NewScript($base,$next),@rest); }
#   elsif($role eq 'OPEN'){
#     my($open,$close,$seps,$list,@more)=$self->parse_kludge_fence($next,@more);
#     (Apply(Annotate(New(undef,undef,role=>'FENCED'),
#     argopen=>$open, argclose=>$close, separators=>$seps),@$list), @more); }
#   else {
#     ($next,@more); }}

# sub parse_kludge_fence {
#   my($self,$next,@more)=@_;
#   my($open,$close,$punct,$r,$item,@list)=($next,undef,'',undef);
#   while(@more){
#     my @i=();
#     while(@more && (($r=($self->getGrammaticalRole($more[0])||'')) !~ /^(CLOSE|PUNCT)$/)){
#       ($item,@more)=$self->parse_kludge_rec(@more);
#       push(@i,$item); }
#     push(@list,(scalar(@i > 1) ? ['ltx:XMWrap',{},@i] : $i[0]));
#     if($r eq 'CLOSE'){
#       $close=shift(@more); last; }
#     else {
#       $punct .= ($punct ? ' ':''). p_getValue(shift(@more)); }} # Delimited by SINGLE SPACE!
#   ($open,$close,$punct,[@list],@more); }

#%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
# Low-level Parser: parse a single expression
#%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
# Convert to textual form for processing by MathGrammar
sub parse_single {
  my ($self, $mathnode, $document, $rule) = @_;
  my @nodes = $self->filter_hints($document, element_nodes($mathnode));

  my ($punct, $result, $unparsed);
  # Extract trailing punctuation, if rule allows it.
  if ($rule =~ s/,$//) {
    my ($x, $r) = ($nodes[-1]);
    $punct = ($x && (getQName($x) eq 'ltx:XMTok')
        && ($r = $x->getAttribute('role')) && (($r eq 'PUNCT') || ($r eq 'PERIOD'))
      ? pop(@nodes) : undef); }

  if (scalar(@nodes) < 2) {    # Too few nodes? What's to parse?
    $result = $nodes[0] || Absent(); }
  else {
    if ($LaTeXML::MathParser::DEBUG) {
      $::RD_TRACE = 1;         # Turn on MathGrammar tracing
      my $box = $document->getNodeBox($LaTeXML::MathParser::XNODE);
      print STDERR "\n" . ('=' x 40) .
        "\nParsing formula \"" . ToString($box) . "\" from " . $box->getLocator
        . "\n == \"" . join(' ', map { node_string($_, $document) } @nodes) . "\"\n"; }

    # Now do the actual parse.
    ($result, $unparsed) = $self->parse_internal($rule, @nodes); }

  # Failure? No result or uparsed lexemes remain.
  # NOTE: Should do script hack??
  if ((!defined $result) || $unparsed) {
    $self->failureReport($document, $mathnode, $rule, $unparsed, @nodes);
    return; }
  # Success!
  else {
    $result = Annotate($result, punctuation => $punct);
    if ($LaTeXML::MathParser::DEBUG) {
      print STDERR "\n=>" . ToString($result) . "\n"; }
    return $result; } }

sub parse_internal {
  my ($self, $rule, @nodes) = @_;
  #------------
  # Generate a textual token for each node; The parser operates on this encoded string.
  local $LaTeXML::MathParser::LEXEMES = {};
  my $i       = 0;
  my $lexemes = '';
  foreach my $node (@nodes) {
    my $role = $self->getGrammaticalRole($node);
    my $text = getTokenMeaning($node);
    $text = 'Unknown' unless defined $text;
    my $lexeme = $role . ":" . $text . ":" . ++$i;
    $lexeme =~ s/\s//g;
    $$LaTeXML::MathParser::LEXEMES{$lexeme} = $node;
    $lexemes .= ' ' . $lexeme; }

  #------------
  # apply the parser to the textified sequence.
  local $LaTeXML::MathParser::PARSER               = $self;
  local %LaTeXML::MathParser::SEEN_NOTATIONS       = ();
  local %LaTeXML::MathParser::DISALLOWED_NOTATIONS = ();
  local $LaTeXML::MathParser::MAX_ABS_DEPTH        = 1;
  my $unparsed = $lexemes;
  my $result   = $$self{internalparser}->$rule(\$unparsed);
  if (((!defined $result) || $unparsed)    # If parsing Failed
    && $LaTeXML::MathParser::SEEN_NOTATIONS{QM}) {    # & Saw some QM stuff.
    $LaTeXML::MathParser::DISALLOWED_NOTATIONS{QM} = 1;    # Retry w/o QM notations
    $unparsed = $lexemes;
    $result = $$self{internalparser}->$rule(\$unparsed); }
  while (((!defined $result) || $unparsed)                 # If parsing Failed
    && ($LaTeXML::MathParser::SEEN_NOTATIONS{AbsFail})     # & Attempted deeper abs nesting?
    && ($LaTeXML::MathParser::MAX_ABS_DEPTH < 3)) {        # & Not ridiculously deep
    delete $LaTeXML::MathParser::SEEN_NOTATIONS{AbsFail};
    ++$LaTeXML::MathParser::MAX_ABS_DEPTH;                 # Try deeper.
    $unparsed = $lexemes;
    $result   = $$self{internalparser}->$rule(\$unparsed); }

  # If still failed, try other strategies?

  return ($result, $unparsed); }

sub getGrammaticalRole {
  my ($self, $node) = @_;
  my $tag   = getQName($node);
  my $rnode = $node;
  if ($tag eq 'ltx:XMRef') {
    if (my $id = $node->getAttribute('id')) {
      $rnode = $LaTeXML::MathParser::DOCUMENT->lookupID($id);
      $tag   = getQName($rnode); } }
  my $role = $rnode->getAttribute('role');
  if (!defined $role) {
    if ($tag eq 'ltx:XMTok') {
      $role = 'UNKNOWN'; }
    elsif ($tag eq 'ltx:XMDual') {
      $role = $LaTeXML::MathParser::DOCUMENT->getFirstChildElement($node)->getAttribute('role'); }
    $role = 'ATOM' unless defined $role; }
  $self->note_unknown($rnode) if ($role eq 'UNKNOWN') && $LaTeXML::MathParser::STRICT;
  return $role; }

# How many tokens before & after the failure point to report in the Warning message.
my $FAILURE_PRETOKENS  = 3;    # [CONSTANT]
my $FAILURE_POSTTOKENS = 1;    # [CONSTANT]

sub failureReport {
  my ($self, $document, $mathnode, $rule, $unparsed, @nodes) = @_;
  if ($LaTeXML::MathParser::STRICT || (($STATE->lookupValue('VERBOSITY') || 0) > 1)) {
    my $loc = "";
    # If we haven't already done it for this formula, show the original TeX.
    if (!$LaTeXML::MathParser::WARNED) {
      $LaTeXML::MathParser::WARNED = 1;
      my $box = $document->getNodeBox($LaTeXML::MathParser::XNODE);
      $loc = "In \"" . UnTeX($box) . "\""; }
    $unparsed =~ s/^\s*//;
    my @rest = split(/ /, $unparsed);
    my $pos = scalar(@nodes) - scalar(@rest);
    # Break up the input at the point where the parse failed.
    my $parsed  = join(' ', map { node_string($_, $document) } @nodes[0 .. $pos - 1]);
    my $toparse = join(' ', map { node_string($_, $document) } @nodes[$pos .. $#nodes]);
    my $parsefail
      = join('.', map { $self->getGrammaticalRole($_) }
        @nodes[($pos - $FAILURE_PRETOKENS >= 0
          ? $pos - $FAILURE_PRETOKENS : 0) .. $pos - 1])
      . ">"
      . join('.', map { $self->getGrammaticalRole($_) }
        @nodes[$pos .. ($pos + $FAILURE_POSTTOKENS - 1 < $#nodes
          ? $pos + $FAILURE_POSTTOKENS - 1 : $#nodes)]);
    my $lexeme = node_location($nodes[$pos] || $nodes[$pos - 1] || $mathnode);
    my $indent = length($parsed) - 2; $indent = 8 if $indent > 8;
    Warn('not_parsed', $parsefail, $mathnode,
      "MathParser failed to match rule '$rule'",
      ($loc ? ($loc) : ()),
      ($parsed
        ? ($parsed, (' ' x $indent) . "> " . $toparse)
        : ("> " . $toparse)));
  }
  return; }

# used for debugging & failure reporting.
sub node_string {
  my ($node, $document) = @_;
  my $role = $node->getAttribute('role') || 'UNKNOWN';
  my $box = $document->getNodeBox($node);
  return ($box ? ToString($box) : text_form($node)) . "[[$role]]"; }

#%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
# Conversion to a less ambiguous, mostly-prefix form.
# Mostly for debugging information?
#%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
sub text_form {
  my ($node) = @_;
  #  $self->textrec($node,0); }
  # Hmm, Something Weird is broken!!!!
  # With <, I get "unterminated entity reference" !?!?!?
  #  my $text= $self->textrec($node,0);
  my $text = textrec($node, undef);
  $text =~ s/</less/g;
  return $text; }

my %PREFIX_ALIAS = (    # [CONSTANT]
  SUPERSCRIPTOP => '^', SUBSCRIPTOP => '_', times          => => '*',
  'equals'      => '=', 'less-than' => '<', 'greater-than' => '>',
  'less-than-or-equals' => '<=', 'greater-than-or-equals' => '>=',
  'much-less-than'      => '<<', 'much-greater-than'      => '>>',
  'plus'                => '+',  'minus'                  => '-', 'divide' => '/');
# Put infix, along with `binding power'
my %IS_INFIX = (METARELOP => 1,    # [CONSTANT]
  RELOP         => 2,    ARROW       => 2,
  ADDOP         => 10,   MULOP       => 100,
  SUPERSCRIPTOP => 1000, SUBSCRIPTOP => 1000);

sub textrec {
  my ($node, $outer_bp, $outer_name) = @_;
  my $tag = getQName($node);
  $outer_bp   = 0  unless defined $outer_bp;
  $outer_name = '' unless defined $outer_name;
  if ($tag eq 'ltx:XMApp') {
    my $app_role = $node->getAttribute('role');
    my ($op, @args) = element_nodes($node);
    if ($app_role && $app_role =~ /^FLOAT(SUB|SUPER)SCRIPT$/) {
      return ($1 eq 'SUPER' ? '^' : '_') . textrec($op); }
    else {
      my $name = ((getQName($op) eq 'ltx:XMTok') && getTokenMeaning($op)) || 'unknown';
      my ($bp, $string) = textrec_apply($name, $op, @args);
      return (($bp < $outer_bp) || (($bp == $outer_bp) && ($name ne $outer_name))
        ? '(' . $string . ')' : $string); } }
  elsif ($tag eq 'ltx:XMDual') {
    my ($content, $presentation) = element_nodes($node);
    return textrec($content, $outer_bp, $outer_name); }    # Just send out the semantic form.
  elsif ($tag eq 'ltx:XMTok') {
    my $name = getTokenMeaning($node);
    $name = 'Unknown' unless defined $name;
    return $PREFIX_ALIAS{$name} || $name; }
  elsif ($tag eq 'ltx:XMWrap') {
    # ??
    return join('@', map { textrec($_) } element_nodes($node)); }
  elsif ($tag eq 'ltx:XMArray') {
    return textrec_array($node); }
  else {
    return '[' . $node->textContent . ']'; } }

sub textrec_apply {
  my ($name, $op, @args) = @_;
  my $role = $op->getAttribute('role') || 'Unknown';
  if (($role =~ /^(SUB|SUPER)SCRIPTOP$/) && (($op->getAttribute('scriptpos') || '') =~ /^pre\d+$/)) {
    # Note that this will likely get parenthesized due to high bp
    return (5000, textrec($op) . " " . textrec($args[1]) . " " . textrec($args[0])); }
  elsif (my $bp = $IS_INFIX{$role}) {
    # Format as infix.
    return ($bp, (scalar(@args) == 1    # unless a single arg; then prefix.
        ? textrec($op) . ' ' . textrec($args[0], $bp, $name)
        : join(' ' . textrec($op) . ' ', map { textrec($_, $bp, $name) } @args))); }
  elsif ($role eq 'POSTFIX') {
    return (10000, textrec($args[0], 10000, $name) . textrec($op)); }
  elsif ($name eq 'multirelation') {
    return (2, join(' ', map { textrec($_, 2, $name) } @args)); }
  else {
    return (500, textrec($op, 10000, $name) . '@(' . join(', ', map { textrec($_) } @args) . ')'); } }

sub textrec_array {
  my ($node) = @_;
  my $name = $node->getAttribute('meaning') || $node->getAttribute('name') || 'Array';
  my @rows = ();
  foreach my $row (element_nodes($node)) {
    push(@rows, '[' . join(', ', map { ($_->firstChild ? textrec($_->firstChild) : '') } element_nodes($row)) . ']'); }
  return $name . '[' . join(', ', @rows) . ']'; }

#%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
# Cute! Were it NOT for Sub/Superscripts, the whole parsing process only
# builds a new superstructure around the sequence of token nodes in the input.
# Thus, any internal structure is unchanged.
#  They get re-parented, but if the parse fails, we've only got to put them
# BACK into the original node, to recover the original arrangment!!!
# Thus, we don't have to clone, and deal with namespace duplication.
# ...
# EXCEPT, as I said, for sub/superscripts!!!!
#

#%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
# Constructors used in grammar
# All the tree construction in the grammar should come through these operations.
# We have to be _extremely_ careful about cloning nodes when using addXML::LibXML!!!
# If we add one node to another, it is _silently_ removed from any parent it may have had!
#%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

# ================================================================================
# Morph these away!!!
# What's the point?
# So that we can do the parse, obtaining a parse tree,
# but WITHOUT modifying, moving, or otherwise affecting the existing nodes.
# This is so we can (potentially) keep the parsed & unparsed separate,
# and even try out Earley style parsers that give multiple parse trees.
#
# In principle, the existing code allows that, but undoubtedly has leaks
# where the existing nodes get altered (esp. attributes added/changed).
# Also, some code is quite convoluted in order to keep namespace declarations clean.
#
# Much easier approach is to use the array rep, then let Common::XML code
# build/clone as needed; this should get the namespaces right.
# Also, we can defer doing the Lookup till later...
# However, this means that the API that the MathGrammar sees, may
# be passing us:
#    strings (either explicit, or lexemes!
#       can we assume lexeme names will never be mistaken for explicit strings?
#    arrays (representing nodes to be built)
#    nodes (? at least embedded in the arrays)
# So, this is simpler?
#
# How many "partial trees" get built during parsing that eventually fail?
# ================================================================================

# ================================================================================
# Low-level accessors
sub Lookup {
  my ($lexeme) = @_;
  return $$LaTeXML::MathParser::LEXEMES{$lexeme}; }

# The following accessors work on both the LibXML and ARRAY representations
sub p_getValue {
  my ($node) = @_;
  if (!defined $node) {
    return; }
  elsif (ref $node eq 'XML::LibXML::Element') {
    my $x;
    return (($x = $node->textContent) ne '' ? $x    # get content, or fall back to name
      : (defined($x = $node->getAttribute('name')) ? $x
        : undef)); }
  elsif (ref $node eq 'ARRAY') {
    my ($op, $attr, @args) = @$node;
    if (@args) {
      return join('', grep { defined $_ } map { p_getValue($_) } @args); }
    else {
      return $$node[1]{name}; } }
  else {                                            # ????
    return $node; } }

sub p_getTokenMeaning {
  my ($item) = @_;
  if (!defined $item) {
    return; }
  elsif (ref $item eq 'ARRAY') {
    my ($op, $attr, @args) = @$item;
    return $$attr{meaning} || $$attr{name} || $args[0] || $$attr{role}; }
  elsif (ref $item eq 'XML::LibXML::Element') {
    return getTokenMeaning($item); } }

sub p_getAttribute {
  my ($item, $key) = @_;
  if (!defined $item) {
    return; }
  elsif (ref $item eq 'ARRAY') {
    return $$item[1]{$key}; }
  elsif (ref $item eq 'XML::LibXML::Element') {
    return $item->getAttribute($key); } }

sub p_element_nodes {
  my ($item) = @_;
  if (!defined $item) {
    return (); }
  elsif (ref $item eq 'ARRAY') {
    my ($op, $attr, @args) = @$item;
    return @args; }
  elsif (ref $item eq 'XML::LibXML::Element') {
    return element_nodes($item); } }

sub p_getQName {
  my ($item) = @_;
  if (!defined $item) {
    return; }
  elsif (ref $item eq 'ARRAY') {
    return $$item[0]; }
  elsif (ref $item eq 'XML::LibXML::Element') {
    return getQName($item); } }

# Make a new Token node with given name, content, and attributes.
# $content is an array of nodes (which may need to be cloned if still attached)
sub New {
  my ($meaning, $content, %attributes) = @_;
  my %attr = ();
  $attr{meaning} = $meaning if $meaning;
  foreach my $key (sort keys %attributes) {
    my $value = p_getValue($attributes{$key});
    $attr{$key} = $value if defined $value; }
  if (!$attr{font}) {
    $attr{font} = ($content && $content =~ /\S/ ? $DEFAULT_FONT->specialize($content) : LaTeXML::Common::Font->new()); }
  return ['ltx:XMTok', {%attr}, ($content ? ($content) : ())]; }

# Some handy shorthands.
sub Absent {
  return New('absent'); }

sub InvisibleTimes {
  return New('times', "\x{2062}", role => 'MULOP', font => LaTeXML::Common::Font->new()); }

sub InvisibleComma {
  return New(undef, "\x{2063}", role => 'PUNCT', font => LaTeXML::Common::Font->new()); }

# Get n-th arg of an XMApp.
# However, this is really only used to get the script out of a sub/super script
sub Arg {
  my ($node, $n) = @_;
  if (ref $node eq 'ARRAY') {
    return $$node[$n + 2]; }
  else {
    my @args = element_nodes($node);
    return $args[$n]; } }    # will get cloned if/when needed.

# Add more attributes to a node.
# Values can be strings or nodes whose text content is used.
sub Annotate {
  my ($node, %attributes) = @_;
  my %attrib = ();
  # first scan & convert any attributes, to make sure there really are any values.
  foreach my $attr (keys %attributes) {
    my $value = p_getValue($attributes{$attr});
    $attrib{$attr} = $value if defined $value; }
  # Hmm.... maybe we need to merge some things, open close?
  if (keys %attrib) {    # Any attributes to assign?
                         # If we've gotten a real XML node, convert to array representation
                         # We do NOT want to modify any of the original XML!!!!
    if (ref $node ne 'ARRAY') {
      $node = [getQName($node),
        { map { (getQName($_) => $_->getValue) }
            grep { $_->nodeType == XML_ATTRIBUTE_NODE } $node->attributes },
        $node->childNodes]; }
    my $qname = $$node[0];
    # Remove any attributes that aren't allowed!!!
    foreach my $k (keys %attrib) {
      delete $attrib{$k} unless $k =~ /^_/ || $LaTeXML::MathParser::DOCUMENT->canHaveAttribute($qname, $k); }
    # Special treatment for some attributes:
    # Combine opens & closes
    foreach my $k (qw(open argopen)) {
      $attrib{$k} = $attrib{$k} . $$node[1]{$k} if $attrib{$k} && $$node[1]{$k}; }
    foreach my $k (qw(close argclose)) {
      $attrib{$k} = $$node[1]{$k} . $attrib{$k} if $attrib{$k} && $$node[1]{$k}; }
    # Make sure font is "Appropriate", if we're creating a new token
    if ($attrib{_font} && ($qname eq 'ltx:XMTok')) {
      my $content = join('', @$node[2 .. $#$node]);
      if ((!defined $content) || ($content eq '')) {
        delete $attrib{_font}; }    # No font needed
      elsif (my $font = $LaTeXML::MathParser::DOCUMENT->decodeFont($attrib{_font})) {
        delete $attrib{_font};
        $attrib{font} = $font->specialize($content); } }
    map { $$node[1]{$_} = $attrib{$_} } keys %attrib; }    # Now add them.
  return $node; }

# ================================================================================
# Mid-level constructors

# Apply $op to the list of arguments
# args may be array-rep or lexemes (or nodes?)
sub Apply {
  my ($op, @args) = @_;
  return ['ltx:XMApp', {}, $op, @args]; }

# Apply $op to a `delimited' list of arguments of the form
#     open, expr (punct expr)* close
# after extracting the opening and closing delimiters, and the separating punctuation
sub ApplyDelimited {
  my ($op, @stuff) = @_;
  my $open  = shift(@stuff);
  my $close = pop(@stuff);
  my ($seps, @args) = extract_separators(@stuff);
  return Apply(Annotate($op, argopen => $open, argclose => $close, separators => $seps), @args); }

# Given a sequence of operators, form the nested application op(op(...(arg)))
sub recApply {
  my (@ops) = @_;
  return (scalar(@ops) > 1 ? Apply(shift(@ops), recApply(@ops)) : $ops[0]); }

# Given  alternating expressions & separators (punctuation,...)
# extract the separators as a concatenated string,
# returning (separators, args...)
sub extract_separators {
  my (@stuff) = @_;
  my ($punct, @args);
  if (@stuff) {
    push(@args, shift(@stuff));    # Grab 1st expression
    while (@stuff) {               # Expecting pairs of punct, expression
      my $p = shift(@stuff);
      $punct .=
        ($punct ? ' ' : '')        # Delimited by SINGLE SPACE!
        . spacingToString(getXMHintSpacing(p_getAttribute($p, 'lpadding')))
        . p_getValue($p)
        . spacingToString(getXMHintSpacing(p_getAttribute($p, 'rpadding')));
      push(@args, shift(@stuff)); } }    # Collect the next expression.
  return ($punct, @args); }

# ================================================================================
# Some special cases

# This specifies the "meaning" of things within a pair
# of open/close delimiters, depending on the number of things.
# Really should be customizable?
# Note that these are all Best Guesses, but really can have
# alternate interpretations depending on context, field, etc.
# Question: Is there enough context to guess better?
# For example, whether (a,b) is an interval or list?
#  (both could reasonably be preceded by \in )
my %balanced = (    # [CONSTANT]
  '(' => ')', '[' => ']', '{' => '}',
  '|' => '|', '||' => '||',
  "\x{230A}" => "\x{230B}",    # lfloor, rfloor
  "\x{2308}" => "\x{2309}",    # lceil, rceil
  "\x{2329}" => "\x{232A}",    # angle brackets; NOT mathematical, but balance in case they show up.
  "\x{27E8}" => "\x{27E9}",    # angle brackets (prefered)
  "\x{2225}" => "\x{2225}",    # lVert, rVert
);
# For enclosing a single object
# Note that the default here is just to put open/closed attributes on the single object
my %enclose1 = (    # [CONSTANT]
  '{@}'   => 'set',                                   # alternatively, just variant parentheses
  '|@|'   => 'absolute-value',
  '||@||' => 'norm', "\x{2225}@\x{2225}" => 'norm',
  "\x{230A}@\x{230B}" => 'floor',
  "\x{2308}@\x{2309}" => 'ceiling',
  '<@>'               => 'expectation',               # or just average?
  '<@|'               => 'bra', '|@>' => 'ket');
# For enclosing more than 2 objects; the punctuation is significant too
my %enclose2 = (                                      # [CONSTANT]
  '(@,@)' => 'open-interval',                                           # alternatively, just a list
  '[@,@]' => 'closed-interval',
  '(@,@]' => 'open-closed-interval', '[@,@)' => 'closed-open-interval',
  '{@,@}' => 'set',                                                     # alternatively, just a list ?
);
# For enclosing more than 2 objects.
# assume 1st punct? or should we check all are same?
my %encloseN = (    # [CONSTANT]
  '(@,@)' => 'vector', '{@,@}' => 'set',);

sub isMatchingClose {
  my ($open, $close) = @_;
  my $oname  = p_getValue($open);
  my $cname  = p_getValue($close);
  my $expect = $balanced{$oname};
  return (defined $expect) && ($expect eq $cname); }

# Given a delimited sequence: open expr (punct expr)* close
# (OR, an empty sequence open close)
# Convert it into the appropriate thing, depending on the specific open & close used.
# If the open/close are `simple' delimiters and there is only one expr,
# simply add open/close attributes.
sub Fence {
  my (@stuff) = @_;
  # Peak at delimiters to guess what kind of construct this is.
  my $nargs = scalar(@stuff);
  Error("expected", "arguments", undef,
    "Even number of arguments to Fence(); should be of form open,expr,(punct,expr)*,close",
    "got " . join(' ', map { ToString($_) } @stuff))
    if ($nargs != 2) && (($nargs % 2) == 0);    # either empty or odd number
  my ($open, $close) = ($stuff[0], $stuff[-1]);
  my $lpad = (ref $open)  && $open->getAttribute('lpadding');
  my $rpad = (ref $close) && $close->getAttribute('rpadding');
  my $o    = p_getValue($open);
  my $c    = p_getValue($close);
  my $n    = int(($nargs - 2 + 1) / 2);
  my @p = map { p_getValue(@stuff[2 * $_]) } 1 .. $n - 1;
  my $op = ($n == 0
    ? 'list'                                    # ?
    : ($n == 1
      ? $enclose1{ $o . '@' . $c }
      : ($n == 2
        ? ($enclose2{ $o . '@' . $p[0] . '@' . $c } || 'list')
        : ($encloseN{ $o . '@' . $p[0] . '@' . $c } || 'list'))));
  # When we're parsing XMWrap, we shouldn't try so hard to infer a meaning (it'll usually be wrong)
  $op = undef unless $LaTeXML::MathParser::STRICT;
  if (($n == 1) && (!defined $op)) {            # Simple case.
    return Annotate($stuff[1],
      open     => ($open  ? $open  : undef),
      close    => ($close ? $close : undef),
      lpadding => ($lpad  ? $lpad  : undef),
      rpadding => ($rpad  ? $rpad  : undef)); }
  else {
    return ApplyDelimited(New($op, undef, role => 'FENCED'), @stuff); } }

# NOTE: It might be best to separate the multiple Formulae into separate XMath's???
# but only at the top level!
sub NewFormulae {
  my (@stuff) = @_;
  if (scalar(@stuff) == 1) {
    return $stuff[0]; }
  else {
    my ($seps, @formula) = extract_separators(@stuff);
    return Apply(New('formulae', undef, separators => $seps), @formula); } }

# A Formula is an alternation of expr (relationalop expr)*
# It presumably would be equivalent to (expr1 relop1 expr2) AND (expr2 relop2 expr3) ...
# But, I haven't figured out the ideal prefix form that can easily be converted to presentation.
sub NewFormula {
  my (@args) = @_;
  my $n = scalar(@args);
  if ($n == 1) {
    return $args[0]; }
  elsif ($n == 3) {
    return Apply($args[1], $args[0], $args[2]); }
  else {
    return Apply(New('multirelation'), @args); } }

sub NewList {
  my (@stuff) = @_;
  if (@stuff == 1) {
    return $stuff[0]; }
  else {
    my ($seps, @items) = extract_separators(@stuff);
    return Apply(New('list', undef, separators => $seps, role => 'FENCED'), @items); } }

# Given alternation of expr (addop expr)*, compose the tree (left recursive),
# flattenning portions that have the same operator
# ie. a + b + c - d  =>  (- (+ a b c) d)
sub LeftRec {
  my ($arg1, @more) = @_;
  if (@more) {
    my $op     = shift(@more);
    my $opname = p_getTokenMeaning($op);
    my @args   = ($arg1, shift(@more));
    while (@more && ($opname eq p_getTokenMeaning($more[0]))) {
      shift(@more);
      push(@args, shift(@more)); }
    return LeftRec(Apply($op, @args), @more); }
  else {
    return $arg1; } }

# Like apply($op,$arg1,$arg2), but if $op is 'same' as the operator in $arg1,
# then combine as an nary apply of $op to $arg1's arguments and $arg2.
sub ApplyNary {
  my ($op, $arg1, $arg2) = @_;
  my $opname    = p_getTokenMeaning($op) || '__undef_meaning__';
  my $opcontent = p_getValue($op)        || '__undef_content__';
  my @args      = ();
  if (p_getQName($arg1) eq 'ltx:XMApp') {
    my ($op1, @args1) = p_element_nodes($arg1);
    if (((p_getTokenMeaning($op1) || '__undef_meaning__') eq $opname)    # Same operator?
      && ((p_getValue($op1) || '__undef_content__') eq $opcontent)
      # Check that ops are used in same way.
      && !(grep { (p_getAttribute($op, $_) || '<none>') ne (p_getAttribute($op1, $_) || '<none>') }
        qw(mathstyle))                                                   # Check ops are used in similar way
          # Check that arg1 isn't wrapped, fenced or enclosed in some restrictive way
      && !(grep { p_getAttribute($arg1, $_) } qw(open close enclose))) {
      push(@args, @args1); }
    else {
      push(@args, $arg1); } }
  else {
    push(@args, $arg1); }
  return Apply($op, @args, $arg2); }

# ================================================================================
# Construct an appropriate application of sub/superscripts
# This accounts for script positioning:
#   Whether it precedes (float), is over/under (if base requests),
# or follows (normal case), along with whether sub/super.
#   the alignment of multiple sub/superscripts derived from the binding level when created.
# scriptpos = (pre|mod|post) number; where number is the binding-level.
# If $pos is given (pre|mid|post), it overrides the position implied by the script
sub NewScript {
  my ($base, $script, $pos) = @_;
  my $role;
  my ($bx, $bl) = (p_getAttribute($base,   'scriptpos') || 'post') =~ /^(pre|mid|post)?(\d+)?$/;
  my ($sx, $sl) = (p_getAttribute($script, 'scriptpos') || 'post') =~ /^(pre|mid|post)?(\d+)?$/;
  my ($mode, $y) = p_getAttribute($script, 'role') =~ /^(FLOAT|POST)?(SUB|SUPER)SCRIPT$/;
  my $x = ($pos ? $pos : ($mode eq 'FLOAT' ? 'pre' : $bx || 'post'));
  my $lpad = ($x eq 'pre') && p_getAttribute($script, 'lpadding');
  my $rpad = ($x ne 'pre') && p_getAttribute($script, 'rpadding');
  my $t;
  my $l = $sl || $bl ||
    (($t = $LaTeXML::MathParser::DOCUMENT->getNodeBox($script))
    && ($t->getProperty('level'))) || 0;
  # If the INNER script was a floating script (ie. {}^{x})
  # we'll NOT want this one to stack over it so bump the level.
  my $bumped;
  if (p_getAttribute($base, '_wasfloat')) {
    $l++; $bumped = 1 }
  elsif (my $innerl = p_getAttribute($base, '_bumplevel')) {
    $l = $innerl; }
  my $app = Apply(New(undef, undef, role => $y . 'SCRIPTOP', scriptpos => "$x$l"),
    $base, Arg($script, 0));
  # Record whether this script was a floating one
  $$app[1]{_wasfloat}  = 1   if $mode eq 'FLOAT';
  $$app[1]{_bumplevel} = $l  if $bumped;
  $$app[1]{scriptpos}  = $bx if $bx ne 'post';
  $$app[1]{lpadding} = $lpad if $lpad && !$$app[1]{lpadding};    # better to add?
  $$app[1]{rpadding} = $rpad if $rpad && !$$app[1]{rpadding};    # better to add?
  return $app; }

# Basically, like NewScript, but decorates an operator with sub/superscripts
# (with vague unknown implications for meaning?)
# but which will preserve the role (& meaning?)
sub DecorateOperator {
  my ($op, $script) = @_;
  my $decop = NewScript($op, $script);
  my $role    = p_getAttribute($op, 'role');
  my $meaning = p_getAttribute($op, 'meaning');
  return Annotate($decop, role => $role, meaning => $meaning); }

# ================================================================================
# A "notation" is a language construct or set thereof.

# Called from the grammar to record the fact that a notation was seen.
sub SawNotation {
  my ($notation, $node) = @_;
  $LaTeXML::MathParser::SEEN_NOTATIONS{$notation} = 1;
  return 1; }

# Called by the grammar to determine whether we should try productions
# which involve the given notation.
sub IsNotationAllowed {
  my ($notation) = @_;
  return ($LaTeXML::MathParser::DISALLOWED_NOTATIONS{$notation} ? undef : 1); }

# ================================================================================

# Note that an UNKNOWN token may have been used as a function.
# For simplicity in the grammar, we accept a token that has sub|super scripts applied.
sub MaybeFunction {
  my ($token) = @_;
  my $self = $LaTeXML::MathParser::PARSER;
  while (p_getQName($token) eq 'ltx:XMApp') {
    $token = Arg($token, 1); }
  my $name = token_prettyname($token);
  # DANGER!!
  # We want to be using Annotate here, but we're screwed up by the
  # potential "embellishing" of the function token.
  # (ie. the descent above past all XMApp's)
  $token->setAttribute('possibleFunction', 'yes');
  $$self{maybe_functions}{$name}++
    if $LaTeXML::MathParser::STRICT && !$$self{suspicious_tokens}{$token};
  $$self{suspicious_tokens}{$token} = 1;
  return; }

# ================================================================================
1;

__END__

=pod 

=head1 NAME

C<LaTeXML::MathParser> - parses mathematics content

=head1 DESCRIPTION

C<LaTeXML::MathParser> parses the mathematical content of a document.
It uses L<Parse::RecDescent> and a grammar C<MathGrammar>.

=head2 Math Representation

Needs description.

=head2 Possibile Customizations

Needs description.

=head2 Convenience functions

The following functions are exported for convenience in writing the
grammar productions.

=over 4

=item C<< $node = New($name,$content,%attributes); >>

Creates a new C<XMTok> node with given C<$name> (a string or undef),
and C<$content> (a string or undef) (but at least one of name or content should be provided),
and attributes.

=item C<< $node = Arg($node,$n); >>

Returns the C<$n>-th argument of an C<XMApp> node;
0 is the operator node.

=item C<< Annotate($node,%attributes); >>

Add attributes to C<$node>.

=item C<< $node = Apply($op,@args); >>

Create a new C<XMApp> node representing the application of the node
C<$op> to the nodes C<@args>.

=item C<< $node = ApplyDelimited($op,@stuff); >>

Create a new C<XMApp> node representing the application of the node
C<$op> to the arguments found in C<@stuff>.  C<@stuff> are 
delimited arguments in the sense that the leading and trailing nodes
should represent open and close delimiters and the arguments are
seperated by punctuation nodes.  The text of these delimiters and
punctuation are used to annotate the operator node with
C<argopen>, C<argclose> and C<separator> attributes.

=item C<< $node = recApply(@ops,$arg); >>

Given a sequence of operators and an argument, forms the nested
application C<op(op(...(arg)))>>.

=item C<< $node = InvisibleTimes; >>

Creates an invisible times operator.

=item C<< $boole = isMatchingClose($open,$close); >>

Checks whether C<$open> and C<$close> form a `normal' pair of
delimiters, or if either is ".".

=item C<< $node = Fence(@stuff); >>

Given a delimited sequence of nodes, starting and ending with open/close delimiters,
and with intermediate nodes separated by punctuation or such, attempt to guess what
type of thing is represented such as a set, absolute value, interval, and so on.
If nothing specific is recognized, creates the application of C<FENCED> to the arguments.

This would be a good candidate for customization!

=item C<< $node = NewFormulae(@stuff); >>

Given a set of formulas, construct a C<Formulae> application, if there are more than one,
else just return the first.

=item C<< $node = NewList(@stuff); >>

Given a set of expressions, construct a C<list> application, if there are more than one,
else just return the first.

=item C<< $node = LeftRec($arg1,@more); >>

Given an expr followed by repeated (op expr), compose the left recursive tree.
For example C<a + b + c - d> would give C<(- (+ a b c) d)>>

=item C<< MaybeFunction($token); >>

Note the possible use of C<$token> as a function, which may cause incorrect parsing.
This is used to generate warning messages.

=back

=head1 AUTHOR

Bruce Miller <bruce.miller@nist.gov>

=head1 COPYRIGHT

Public domain software, produced as part of work done by the
United States Government & not subject to copyright in the US.

=cut