I'm using nuget package Antlr4.Runtime.Standard v4.11.1 in .NET 6 and have this grammar rule:
term : factor ( op = ( PLUS | MINUS ) factor )* ;
Note that alias op
is inside the *
. PLUS and MINUS are defined as ' ' and '-'
But, when i put this in the parser and my custom visitor:
1 2-3
... the generated context in my visitor gives me factor
as an array of 3, but op
as a single field, containing only the last occurrence '-'.
So, is there a way to get all occurrences of that op
, somehow? Or do I have to process rules like this by walking the children array, and finding out what is what myself?
thanks
CodePudding user response:
The
in ANTLR just (re) assigns the token to op
. To collect all tokens, you can do =
:
term
: factor ( op =( PLUS | MINUS ) factor )*
;
where op
will now be a list of tokens. Or just don't use *
at all:
term
: factor ( ( PLUS | MINUS ) term )?
;
in which case you'll always have only 1 expression to evaluate (if PLUS
or MINUS
is present).