1

考虑以下简单的语法。

grammar test;

options {  
  language = Java; 
  output = AST;
}                     
//imaginary tokens
tokens{ 
}


parse
    : declaration
    ;

declaration
    : forall
    ;
forall
    :'forall' '('rule1')' '[' (( '(' rule2 ')' '|' )* ) ']' 
    ;
rule1
    : INT
    ;
rule2
    : ID
    ;
ID  
    : ('a'..'z' | 'A'..'Z'|'_')('a'..'z' | 'A'..'Z'|'0'..'9'|'_')*
    ;
INT 
    : ('0'..'9')+
    ;
WHITESPACE
    : ('\t' | ' ' | '\r' | '\n' | '\u000C')+ {$channel = HIDDEN;}
    ;

这是输入

forall (1) [(first) | (second) | (third) | (fourth) | (fifth) |]  

语法适用于上述输入,但我想从输入中删除额外的管道符号(输入中的倒数第二个字符)。
有什么想法/想法吗?

4

1 回答 1

1

My antlr syntax is a bit rusty but you should try something like this:

forall
    :'forall' '('rule1')' '[' ('(' rule2 ')' ('|' '(' rule2 ')' )* )? ']' 
    ;

That is, instead of (r|)* write (r(|r)*)?. You can see how the latter allows for zero, one or many rules with pipes inbetween.

于 2012-12-19T15:58:29.100 回答