Skip to content
Advertisement

Antlr4: getting an ordered list of tokens?

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?

Advertisement

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.

User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement