I have the following ANTLR grammar:
grammar mygrammar;
ASSIGNMENT
: ID '=' INT
;
ID : ('a'..'z'|'A'..'Z'|'_') ('a'..'z'|'A'..'Z'|'0'..'9'|'_')*
;
INT : '0'..'9'+
;
WS : ( ' '
| '\t'
| '\r'
| '\n'
) {$channel=HIDDEN;}
;
Only the ASSIGNMENT rule is actually mine, the rest are defaults added by ANTLRWorks 1.4.3.
When I come to try the grammar in the interpreter, strings such as "a=5" succeed, but strings such as "b[space]=[space]6" fail: I get a MismatchedTokenException because of the spaces:
From reading the ANTLR website, and the
Ignore rules: WSand
{$channel=HIDDEN}text/grammar rule, it seems the whitespace should be ignored, however this is not the case.
What am I doing wrong?
I know you already found the answer, but let me explain why changing ASSIGNMENT
to assignment
solved it.
Because rules that start with a capital, are lexer rules (i.e. tokens). And {skip();}
or {$channel=HIDDEN;}
cause lexer rules to be skipped (or hidden) from parser rules, not from lexer rules.
That is why ASSIGNMENT
(lexer rule) didn't accept any white spaces, and assignment
(parser rule) does ignore them.