Antlr4: getting an ordered list of tokens?

Tags: ,



I have this parser rule:

multiplication
    : pow (operator = (TIMES | DIVIDE | FLOOR_DIVIDE | MODULO) pow)*
    ;

And I’m iterating over the pows using ctx.pow(), but I would like to know too what operator there was. Unfortunately, ctx.operator just gives the last one encountered and ctx.TIMES() just gives a dumb list with a reapeted ‘*’.

Do I really have to do a sub-rule for that?

Answer

You can do operator +=:

multiplication
    : pow (operator += (TIMES | DIVIDE | FLOOR_DIVIDE | MODULO) pow)*
    ;

which will cause the operators to be placed in a List.



Source: stackoverflow