# /=====================================================================\ #
# |  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 Parse::RecDescent;
use LaTeXML::Global;
use base (qw(Exporter));

our @EXPORT_OK = (qw(&Lookup &New &Absent &Apply &ApplyNary &recApply
		     &Annotate &InvisibleTimes &InvisibleComma
		     &NewFormulae &NewFormula &NewList
		     &ApplyDelimited &NewScript
		     &LeftRec
		     &Arg &Problem &MaybeFunction
		     &SawNotation &IsNotationAllowed
		     &isMatchingClose &Fence));
our %EXPORT_TAGS = (constructors
		    => [qw(&Lookup &New &Absent &Apply &ApplyNary &recApply
			   &Annotate &InvisibleTimes &InvisibleComma
			   &NewFormulae &NewFormula &NewList
			   &ApplyDelimited &NewScript
			   &LeftRec
			   &Arg &Problem &MaybeFunction
			   &SawNotation &IsNotationAllowed
			   &isMatchingClose &Fence)]);
our $nsURI = "http://dlmf.nist.gov/LaTeXML";
our $nsXML = "http://www.w3.org/XML/1998/namespace";
#our $DEFAULT_FONT = LaTeXML::MathFont->default();
our $DEFAULT_FONT = LaTeXML::MathFont->new(family=>'serif', series=>'medium',
					   shape=>'upright', size=>'normal',
					   color=>'black');

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

  my $internalparser = LaTeXML::MathGrammar->new();
  die("Math Parser grammar failed") unless $internalparser;

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

sub parseMath {
  my($self,$document,%options)=@_;
  local $LaTeXML::MathParser::DOCUMENT = $document;
  $self->clear;			# Not reentrant!
  $$self{idcache}={};
  foreach my $node ($document->findnodes("//*[\@xml:id]")){
    $$self{idcache}{$node->getAttribute('xml:id')} = $node; }

  if(my @math =  $document->findnodes('descendant-or-self::ltx:XMath[not(ancestor::ltx:XMath)]')){
    NoteBegin("Math Parsing"); NoteProgress(scalar(@math)." formulae ...");
    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"); }
    NoteEnd("Math Parsing");  }
  $document; }

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

# ================================================================================
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;
}

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(' ',values %attr);
    $name .= "{$desc}" if $desc; }
  else {
    $name = 'Unknown';
    Warn(":parse  What is this: \"".$node->toString."\"?"); }
  $name; }

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

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

# Get the Token's  meaning, else name, else content, else role
sub getTokenMeaning {
  my($node)=@_;
  my $x;
  (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'));
    ($r && $l ? "$r ($l)" : $r || $l); }
  else {
    '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(":internal:Mystery: XMath node has DOCUMENT_FRAGMENT for parent!"); }}
    $p->setAttribute('text',text_form($result)); }
}

our %TAG_FEEDBACK=('ltx:XMArg'=>'a','ltx:XMWrap'=>'w');
# 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($node->removeChild($_),element_nodes($node));
     XML_addNodes($node,$result);
     $result = [element_nodes($node)]->[0]; }
    else {			# Replace the whole node for XMArg, XMWrap; preserve some attributes
      NoteProgress($TAG_FEEDBACK{$tag}||'.') if $LaTeXML::Global::STATE->lookupValue('VERBOSITY') >= 1;
      $result = Annotate($result,
			 role=>$node->getAttribute('role'),
			 'xml:id'=>$node->getAttribute('xml:id'));
      $result = XML_replaceNode($result,$node); }
    $result; }
  else {
    if($tag eq 'ltx:XMath'){
      NoteProgress('[F'.++$$self{n_parsed}.']'); }
    elsif($tag eq 'ltx:XMArg'){
      NoteProgress('-a') if $LaTeXML::Global::STATE->lookupValue('VERBOSITY') >= 1; }
    $$self{failed}{$tag}++;
    undef; }}

# 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); }
    elsif($tag =~ /^ltx:(XMApp|XMDual|XMArray|XMRow|XMCell)$/){
      $self->parse_children($child,$document); }
}}

#======================================================================
# Candidates for Common::XML ?
sub XML_replaceNode {
  my($new,$old)=@_;
  my $parent = $old->parentNode;
  my @following = ();		# Collect the matching and following nodes
  while(my $sib = $parent->lastChild){
    $parent->removeChild($sib);
    last if $$sib == $$old;
    unshift(@following,$sib); }
  XML_addNodes($parent,$new);
  my $inserted = $parent->lastChild;
  map($parent->appendChild($_),@following); # No need for clone
  $inserted; }

##### DAMN!!!
# append_nodes in Common::XML does _NOT_ interpret the array representation!
# That code is currently only in Post!

# This is a copy from Post::Document
my %sortalias =(open=>'zbopen',close=>'zclose',
		argopen=>'zzzzopen',argclose=>'zzzzclose', separators=>'zzzzseparators',
		scriptpos=>'zzzscriptpos');
sub XML_addNodes {
  my($node,@data)=@_;
  foreach my $child (@data){
    if(ref $child eq 'ARRAY'){
      my($tag,$attributes,@children)=@$child;
      my($prefix,$localname)= $tag =~ /^(.*):(.*)$/;
      my $nsuri = $prefix && $LaTeXML::MathParser::DOCUMENT->getModel->getNamespace($prefix);
      warn "No namespace on $tag" unless $nsuri;
      my $new = $node->addNewChild($nsuri,$localname);
      if($attributes){
###	foreach my $key (keys %$attributes){
	foreach my $key (sort {($sortalias{$a}||$a) cmp ($sortalias{$b}||$b)} keys %$attributes){
	  next unless defined $$attributes{$key};
	  my($attrprefix,$attrname)= $key =~ /^(.*):(.*)$/;
	  my $value = $$attributes{$key};
	  if($key eq 'xml:id'){	# Ignore duplicated IDs!!!
#	    if(!defined $$self{idcache}{$value}){
#	      $$self{idcache}{$value} = $new;
	      $new->setAttribute($key, $value); }#}
	  elsif($attrprefix && ($attrprefix ne 'xml')){
	    my $attrnsuri = $attrprefix && $LaTeXML::MathParser::DOCUMENT->getModel->getNamespace($attrprefix);
	    $new->setAttributeNS($attrnsuri,$attrname, $$attributes{$key}); }
	  else {
	    $new->setAttribute($key, $$attributes{$key}); }
	}}
      XML_addNodes($new,@children); }
    elsif((ref $child) =~ /^XML::LibXML::/){
      my $type = $child->nodeType;
      if($type == XML_ELEMENT_NODE){
	my $new = $node->addNewChild($child->namespaceURI,$child->localname);
	foreach my $attr ($child->attributes){
	  my $atype = $attr->nodeType;
	  if($atype == XML_ATTRIBUTE_NODE){
	    my $key = $attr->nodeName;
	    if($key eq 'xml:id'){
	      my $value = $attr->getValue;
#	      if(!defined $$self{idcache}{$value}){
#		$$self{idcache}{$value} = $new;
		$new->setAttribute($key, $value); }#}
	    elsif(my $ns = $attr->namespaceURI){
	      $new->setAttributeNS($ns,$attr->localname,$attr->getValue); }
	    else {
	      $new->setAttribute( $attr->localname,$attr->getValue); }}
	}
	XML_addNodes($new, $child->childNodes); }
      elsif($type == XML_DOCUMENT_FRAG_NODE){
	XML_addNodes($node,$child->childNodes); }
      elsif($type == XML_TEXT_NODE){
	$node->appendTextNode($child->textContent); }
    }
    elsif(ref $child){
      warn "Dont know how to add $child to $node; ignoring"; }
    elsif(defined $child){
      $node->appendTextNode($child); }}}

#%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
# 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 = grep( getQName($_) ne 'ltx:XMHint', # Strip out Hints
		    element_nodes($mathnode));

  my($punct,$result,$unparsed);
  # Extract trailing punctuation, if rule allows it.
  if($rule =~ s/,$//){
    my ($x,$r) = ($nodes[$#nodes]);
    $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);
    undef; }
  # Success!
  else {
    $result = Annotate($result,punctuation=>$punct);
    if($LaTeXML::MathParser::DEBUG){
      print STDERR "\n=>".ToString($result)."\n"; }
    $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?

  ($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 = $$self{idcache}{$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 = $node->firstChild->getAttribute('role'); }
    $role = 'ATOM' unless defined $role; }
  $self->note_unknown($rnode) if ($role eq 'UNKNOWN') && $LaTeXML::MathParser::STRICT;
  $role; }

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 formula \"".ToString($box)." from ".$box->getLocator."\n"; }
    $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 $lexeme = node_location($nodes[$pos] || $nodes[$pos-1] || $mathnode);
    Warn(":parse:$rule ".$loc."  MathParser failed to match rule $rule for "
	 .getQName($mathnode)." at pos. $pos in $lexeme at\n   "
	 . ($parsed ? $parsed."   \n".(' ' x (length($parsed)-2)) : '')."> ".$toparse);
    }}

# used for debugging & failure reporting.
sub node_string {
  my($node,$document)=@_;
  my $role = $node->getAttribute('role') || 'UNKNOWN';
  my $box = $document->getNodeBox($node);
  ($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;
  $text; }


our %PREFIX_ALIAS=(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'
our %IS_INFIX = (METARELOP=>1, 
		 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($op,@args) = element_nodes($node);
    my $name = ((getQName($op) eq 'ltx:XMTok') && getTokenMeaning($op)) || 'unknown';
    my $role  =  $op->getAttribute('role') || 'Unknown';
    my ($bp,$string);
    if($bp = $IS_INFIX{$role}){
      # Format as infix.
      $string = (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'){
      $bp = 10000;
      $string = textrec($args[0],$bp,$name).textrec($op); }
    elsif($name eq 'multirelation'){
      $bp = 2;
      $string = join(' ',map(textrec($_,$bp,$name),@args)); }
##    elsif($name eq 'fenced'){
##      $bp = -1;			# to force parentheses
##      $string = join(', ',map(textrec($_),@args)); }
    else {
      $bp = 500;
      $string = textrec($op,10000,$name) .'@(' . join(', ',map(textrec($_),@args)). ')'; }
    (($bp < $outer_bp)||(($bp==$outer_bp)&&($name ne $outer_name)) ? '('.$string.')' : $string); }
  elsif($tag eq 'ltx:XMDual'){
    my($content,$presentation)=element_nodes($node);
    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;
    $PREFIX_ALIAS{$name} || $name; }
  elsif($tag eq 'ltx:XMWrap'){
    # ??
    join('@',map(textrec($_), element_nodes($node))); }
  elsif($tag eq 'ltx:XMArray'){
    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))).']');}
    $name.'['.join(', ',@rows).']';  }
  else {
#    my $string = ($tag eq 'ltx:XMText' ? $node->textContent : $node->getAttribute('tex') || '?');
    my $string = $node->textContent;
    "[$string]"; }}

#%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
# 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)=@_;
  $$LaTeXML::MathParser::LEXEMES{$lexeme}; }

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

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

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

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

sub p_getQName {
  my($item)=@_;
  if(! defined $item){ undef; }
  elsif(ref $item eq 'ARRAY'){ $$item[0]; }
  elsif(ref $item eq 'XML::LibXML::Element'){ 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; }
  ['ltx:XMTok',{%attr}, ($content ? ($content):())]; }

# Some handy shorthands.
sub Absent { New('absent'); }
sub InvisibleTimes { New('times',"\x{2062}", role=>'MULOP'); }
sub InvisibleComma { New(undef,"\x{2063}", role=>'PUNCT'); }

# 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'){
    $$node[$n+2]; }
  else {
    my @args = element_nodes($node);
    $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; }
  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]; }
    map($$node[1]{$_}=$attrib{$_}, keys %attrib); } # Now add them.
  $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)=@_;
  ['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);
  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)=@_;
  (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));
    while(@stuff){
      $punct .= p_getValue(shift(@stuff));
      push(@args,shift(@stuff)); }}
  ($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 )
our %balanced = ( '(' => ')', '['=>']', '{'=>'}', 
		  '|'=>'|', '||'=>'||',
		  "\x{230A}"=>"\x{230B}", # lfloor, rfloor
		  "\x{2308}"=>"\x{2309}", # lceil, rceil
		  "\x{2329}"=>"\x{232A}");
# For enclosing a single object
# Note that the default here is just to put open/closed attributes on the single object
our %enclose1 = ('{@}'=>'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 two objects
our %enclose2 = ( '(@)'=>'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.
our %encloseN = ( '(@)'=>'vector','{@}'=>'set',);

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

# Given a delimited sequence: open expr (punct expr)* 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 ($open,$close) = ($stuff[0],$stuff[$#stuff]);
  my $o  = p_getValue($open);
  my $c = p_getValue($close);
  my $key = $o.'@'.$c;
  my $n = int(scalar(@stuff)-2+1)/2;
  my $op = ($n==1
	    ?  $enclose1{$key}
	    : ($n==2 
	      ? ($enclose2{$key} || 'list')
	       : ($encloseN{$key} || 'list')));
  if(($n==1) && (!defined $op)){ # Simple case.
    Annotate($stuff[1],open=>($open ? $open : undef), close=>($close ? $close : undef)); }
  else {
    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){ $stuff[0]; }
  else { 
    my ($seps,@formula)=extract_separators(@stuff);
    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){ $args[0];}
  elsif($n == 3){ Apply($args[1],$args[0],$args[2]); }
  else          { Apply(New('multirelation'),@args); }}

sub NewList {
  my(@stuff)=@_;
  if(@stuff == 1){ $stuff[0]; }
  else {
    my ($seps,@items)=extract_separators(@stuff);
    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)); }
    LeftRec(Apply($op,@args),@more); }
  else {
    $arg1; }}

# Like apply($op,$arg1,$arg2), but if $op is same as the operator in $arg1 is the same,
# then combine as nary.
sub ApplyNary {
  my($op,$arg1,$arg2)=@_;
  my $opname = p_getTokenMeaning($op);
  my @args = ();
  if(p_getQName($arg1) eq 'ltx:XMApp'){
    my($op1,@args1)=p_element_nodes($arg1);
    if((p_getTokenMeaning($op1) eq $opname)
       && !grep($_ ,map((p_getAttribute($op,$_)||'<none>') ne (p_getAttribute($op1,$_)||'<none>'),
			qw(style)))) { # Check ops are used in similar way
      push(@args,@args1); }
    else {
      push(@args,$arg1); }}
  else {
    push(@args,$arg1); }
  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.
sub NewScript {
  my($base,$script)=@_;
  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 ($x,$y)   = p_getAttribute($script,'role')               =~ /^(FLOAT|POST)?(SUB|SUPER)SCRIPT$/;
  $x = ($x eq 'FLOAT' ? 'pre' : $bx || 'post');
  my $t;
  my $l = $sl || $bl ||
    (($t=$LaTeXML::MathParser::DOCUMENT->getNodeBox($script))
     && ($t->getProperty('level'))) || 0;
  my $app = Apply(New(undef,undef, role=>$y.'SCRIPTOP',scriptpos=>"$x$l"),
		  $base,Arg($script,0));
  $$app[1]{scriptpos}=$bx if $bx ne 'post';
  $app; }

# ================================================================================
# 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; }

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

# ================================================================================
sub Problem { Warn(":parse MATH Problem? ",@_); }

# 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}++ 
    unless !$LaTeXML::MathParser::STRICT or   $$self{suspicious_tokens}{$token};
  $$self{suspicious_tokens}{$token}=1; }

# ================================================================================
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<< Problem($text); >>

Warn of a potential math parsing problem.

=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

