What is wrong with this grammar? (ANTLRWorks 1.4)

心已入冬 提交于 2019-12-04 16:20:27

You've put 'drop' and 'put' in two different lexer-rules:

PUT_SYN  : 'put' | 'place' | 'drop';          // drop & put
PUT2_SYN : 'put' | 'douse';                   //        put
...
DROP_SYN : 'drop' | 'throw' | 'relinquish';   // drop

When put is encountered by the lexer, PUT_SYN will always be the rule that matches it, so 'put' could (or should) be removed from the PUT2_SYN rule.

So, your problem with parsing the string drop object: the parser will try to match drop_a : (DROP_SYN)(ID); but the "drop" will be matched in the lexer rule PUT_SYN.

EDIT

Those synonym-lists can be better made into parser rules (instead of lexer-rules). Here's a small demo:

grammar TextAdventure;

parse
  :  command (EndCommand command)* EOF
  ;

command
  :  put_syn_1 OtherWord in_syn OtherWord
  |  put_syn_2 out_syn_1 OtherWord
  |  out_syn_2 OtherWord
  |  Drop Kick OtherWord
  |  drop_syn OtherWord
  ;

drop_syn
  :  Drop
  |  Throw 
  |  Relinquish
  ;

in_syn
  :  In
  |  Into
  |  Inside
  |  Within
  ; 

put_syn_1
  :  Put
  |  Place
  |  Drop
  ;

put_syn_2
  :  Put
  |  Douse
  ;

out_syn_1
  :  Out
  ;

out_syn_2
  :  Extinguish
  |  Douse
  ;

Space      : (' ' | '\t' | '\r' | '\n'){$channel=HIDDEN;};
EndCommand : ';';
Put        : 'put';
Place      : 'place';
Drop       : 'drop';
Douse      : 'douse';
In         : 'in';
Into       : 'into';
Inside     : 'inside';
Within     : 'within';    
Out        : 'out';
Extinguish : 'extinguish';
Throw      : 'throw';
Relinquish : 'relinquish';
Kick       : 'kick';
OtherWord  : ('a'..'z' | 'A'..'Z')+;

When interpreting the following source:

drop object ; put yourself in myshoes ; place it in avase

you'll see ANTLRWorks generate the following parse-tree:

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!