Undocummented operator in ANTLR4 grammar: expr op=('*'|'/') expr

Viewed 31

The book of anltr4 includes this example, in lableledExpr.g4 https://github.com/jszheng/py3antlr4book/blob/master/04-Calc/LabeledExpr.g4

with these lines:

expr:   expr op=('*'|'/') expr      # MulDiv
    |   expr op=('+'|'-') expr      # AddSub
... ;

but I can't find the documentation which is the objetive, and meaning of op=('*'|'/')

would that be equivalent to?

expr:   expr opmult expr      # MulDiv
    |   expr opplus expr      # AddSub
... ;

opmult : ('*'|'/') ;
opplus : ('+'|'-') ;

1 Answers

It’s “similar”, but not the same.

The op=('*'|'/') just means that, if the ’*’ or ’/‘ tokens are encountered they will be available through an op property. This can be used for any part of a parser rule and just allows you to name parts of your rule so that you context object will be easier to work with in your code.

The

expr:   expr opmult expr      # MulDiv
    |   expr opplus expr      # AddSub
... ;

opmult : ('*'|'/') ;
opplus : ('+'|'-') ;

Will parse the same input, but will put the ’*’ or ’/‘ token into a separate context object.

Look at your generated code each way and the difference will be obvious. (Maybe even try the first rule as just expr ('*'|'/') expr. And think about the code you’d need to determine which operator was used, compared to the code when you have the op=.)

Related