ANTLR How to differentiate input arguments of the same type

我的梦境 提交于 2019-12-11 14:44:47

问题


If I have my input message:

name IS (Jon, Ted) IS NOT (Peter);

I want this AST:

      name
       |
    |-----|
   IS   IS NOT
    |     |
    |    Peter
 |----|
Jon  Ted

But I'm receiving:

                name
                  |
        |-----------------|
       IS              IS NOT
        |                 |
        |                 |
   |----|-----|      |----|-----|
  Jon  Ted  Peter   Jon  Ted  Peter 

My Grammar file has:

...

expression
    |   NAME 'IS' OParen Identifier (Comma Identifier)* CParen 'IS NOT' OParen 
Identifier (Comma Identifier)* CParen
    ->  ^(NAME ^('IS' ^(Identifier)*) ^('IS NOT' ^(Identifier)*))
    ;

...

NAME
    :   'name'
    ;

Identifier
    :   ('a'..'z' | 'A'..'Z' | '_' | '.' | Digit)*
    ;

How can I differentiate what "belongs" to the 'IS' and what to belongs to the 'IS NOT' ?


回答1:


Something like this should do it:

expression
 : NAME IS left=id_list IS NOT right=id_list -> ^(NAME ^(IS $left) ^(NOT $right))
 ;

id_list
 : '(' ID (',' ID)* ')' -> ID+
 ;

IS : 'IS';
NOT : 'NOT'; // not a single token that is 'IS NOT'

ID
 : ('a'..'z' | 'A'..'Z' | '_' | '.' | Digit)+ 
   // Not `(...)*`: it should always match a single char!
 ;


来源:https://stackoverflow.com/questions/23516645/antlr-how-to-differentiate-input-arguments-of-the-same-type

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