The following alternatives can never be achieved: 2

I am trying to create a very simple grammar to learn how to use ANTLR, but I get the following message:

"The following alternatives can never be achieved: 2"

This is my grammar attempt:

grammar Robot; file : command+; command : ( delay|type|move|click|rclick) ; delay : 'wait' number ';'; type : 'type' id ';'; move : 'move' number ',' number ';'; click : 'click' ; rclick : 'rlick' ; id : ('a'..'z'|'A'..'Z')+ ; number : ('0'..'9')+ ; WS : (' ' | '\t' | '\r' | '\n' ) { skip();} ; 

I am using the ANTLRWorks plugin for IDEA:

This is what it looks like

+6
source share
1 answer

Rules .. (range) inside the parser mean something other than the internal rules of the lexer. Inside lexer rules, this means: β€œfrom char X to char Y”, and inside the parser rule, it corresponds to β€œfrom token M to token N”. And since you made the rule t2> the parser rule, it does not do what you think it does (and this requires an error message).

Solution: make number lexer rule (so write it: number ):

 grammar Robot; file : command+; command : (delay | type | move | Click | RClick) ; delay : 'wait' Number ';'; type : 'type' Id ';'; move : 'move' Number ',' Number ';'; Click : 'click' ; RClick : 'rlick' ; Id : ('a'..'z'|'A'..'Z')+ ; Number : ('0'..'9')+ ; WS : (' ' | '\t' | '\r' | '\n') { skip();} ; 

And, as you can see, I also used the id , click and rclick lexer rclick . If you don’t know what the difference between parser and lexer rules is, tell me about it and I will add an explanation for this answer.

+4
source

Source: https://habr.com/ru/post/890251/


All Articles