0

I keep getting MissingTokenException, NullPointerException, and if I remember correctly NoViableAlterativeException. The logfile / console output from ANTLRWorks is not helpful enough for me.

What I'm after is a rewrite such as the following:

(expression | FLOAT) '(' -> (expression | FLOAT) '*('

Here below is a sample of my grammar that I snatched out to create a test file with.

grammar Test;

expression
: //FLOAT '(' -> (FLOAT '*(')+
| add EOF!
;
term
:   
| '(' add ')'
| FLOAT
| IMULT
;

IMULT
:   (add ('(' add)*) -> (add ('*' add)*)
;
negation
:   '-'* term
;

unary
:   ('+' | '-')* negation
;

mult
:   unary (('*' | '/') unary)*
;

add
:   mult (('+' | '-') mult)*
;

ID  :   ('a'..'z'|'A'..'Z'|'_') ('a'..'z'|'A'..'Z'|'0'..'9'|'_')*
;

FLOAT
:   ('0'..'9')+ '.' ('0'..'9')*// EXPONENT?
|   '.' ('0'..'9')+ //EXPONENT?
|   ('0'..'9')+ //EXPONENT
;

WS  :   ( ' '
    | '\t'
    | '\r'
    | '\n'
    ) {$channel=HIDDEN;}
;

I've also tried :

imult
: FLOAT '(' -> FLOAT '*('
;

And this:

IMULT / imult
: expression '(' -> expression '*'
;

As well as countless other versions (hacks) that I have lost count of.

Can anyone help me out with this ?

Chellsie
  • 11
  • 3

1 Answers1

1

I've run into this problem before. The basic answer is that ANTLR doesn't allow you to use tokens on the right hand side of a '->' statement that weren't present on the left hand side. However, what you can do is use extra tokens defined specifically for AST's. Just create a tokens block before the grammar rules as follows:

tokens { ABSTRACTTOKEN; }

You can use them on the right hand side of the grammar statement like this.

imult
: FLOAT '(' -> ^(ABSTRACTTOKEN FLOAT) 
;

Hope that helps.

Joe
  • 366
  • 1
  • 6