[antlr-interest] How to handle negation...

Jeff Vincent JVincent at Novell.Com
Tue Oct 28 15:23:09 PST 2003


Hey,
 
I am trying to work around an issue in my tree parser with number negation.  The way my rules are set up, the NEGATIVE (negative sign) is separate from the number string itself.  So the number -149 has two nodes whose AST respresentation is:
NEGATIVE("-")*>null
  |
  V
LITERAL_INT("149")-->null
  |
  V
null
Where the unaryExpression has the following:
 
    unaryExpression :
        ...
       | #( NEGATIVE retValue=unaryExpression { negate(retValue); } )
        ...
       ;
 
Through recursion, unaryExpression calls primaryExpression then the number rule.  The number rule converts the "149" string to a real int (Integer.decode("149");) and returns it back to primaryExpression then to unaryExpression where the value is then negated.  This works perfect for all cases except Integer.MIN_VALUE, Long.MIN_VALUE, etc., because the LITERAL_INT portion of the resulting AST (value before negation) is TOO LARGE (by 1) for an Integer (or Long, etc.) and causes a NumberFormatException during the decode().
 
I thought that somehow I could prepend the negative sign before the number is parsed.  I tried the following:
 
    #( NEGATIVE { if (#ue.getType == LITERAL_INT) #ue.setText("-" + #ue.getText()); } retValue = ue:unaryExpression )
 
However, at this stage, #ue is null.  I also tried passing the prefex to the sub-rules, like:
 
    #( NEGATIVE retValue = ue:unaryExpression["-"] )

 
the prefix is then prepended before calling decode().  I think this last option is too messy and both options won't work if someone tries to negate a variable (int j = -i;).  I was hoping someone had a better idea.
 
Thanks,
 
Jeff

-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://www.antlr.org/pipermail/antlr-interest/attachments/20031028/70eb314c/attachment.html


More information about the antlr-interest mailing list