Reputation: 1940
In Terence Parr'S Definitiv ANTLR Reference on page 39 an assignment ist defined like this:
stat: expr (NL|SEMI) # printExpr
| var EQL expr (NL|SEMI) # assign // x = 5; y = x
| (NL|SEMI) # blank
;
...
WS : [ \r\t]+ -> skip;
NL : '\r' ? '\n';
SEMI: ';';
...
This works fine.
But, how can I achieve something like this x = 6 y=x ?
Here: two assignments separated by a single whitespace (WS is skipped, btw.)
Upvotes: 1
Views: 101
Reputation: 5991
A language designed to be dependent on occasional whitespace significance is nearly always a bad idea, and moreso when trying to parse it using a context-free parser. That said, there are two alternatives, at least for this example:
First, put the WS
on the hidden channel. Then, use a predicate to test for a WS
token in the token stream where it is significant:
| var EQL expr ( {atWS()}? | NL | SEMI ) # assign
Second, don't hide or skip the WS
. Then, use like any other token where it should be significant:
| var WS? EQL WS? expr ( WS | NL | SEMI ) # assign
And, add a rule to capture otherwise unused WS
:
ws: WS ; // will pollute the parse tree, but can be ignored there
Both alternatives have consequences, moderate to severe, depending on what you are trying to accomplish.
Upvotes: 1