Antlr left recursive problem

情到浓时终转凉″ 提交于 2019-12-01 00:46:48

Okay, this should do the trick:

grammar Test;

/************************************** PARSER **************************************/
program
    :   function EOF 
    ;

function
    :   ID (OPEN_PAREN (attribute (COMMA attribute)*)? CLOSE_PAREN)?
        (OPEN_BRACE function* CLOSE_BRACE)?
        SEMICOLON?
    ;

attribute
    :   ID (COLON | EQUALS)? expression
    ;

expression
    :   atom (PLUS atom)*
    ;

atom
    :   ID
    |   STRING
    |   BOOLEAN
    |   NUMBER
    |   array
    |   lookup
    ;

array
    :   OPEN_BOX (expression (COMMA expression)*)? CLOSE_BOX
    ;

lookup
    :   OPEN_BRACE (ID (PERIOD ID)*) CLOSE_BRACE
    ;

/************************************** LEXER **************************************/
NUMBER          :   ('+' | '-')? (INTEGER | FLOAT)
                ;

STRING          :  '"' ( ESC_SEQ | ~('\\'|'"') )* '"'
                ;

BOOLEAN         :   'true' | 'TRUE' | 'false' | 'FALSE'
                ;

ID              :   (LETTER|'_') (LETTER | INTEGER |'_')*
                ;

COMMENT         :   '//' ~('\n'|'\r')* ('\r'? '\n'| EOF) {$channel=HIDDEN;}
                |   '/*' ( options {greedy=false;} : . )* '*/' {$channel=HIDDEN;}
                ;

WHITESPACE      :   (' ' | '\t' | '\r' | '\n') {$channel=HIDDEN;} ;

COLON           :   ':' ;
SEMICOLON       :   ';' ;

COMMA           :   ',' ;
PERIOD          :   '.' ;
PLUS            :   '+' ;
EQUALS          :   '=' ;   

OPEN_PAREN      :   '(' ;
CLOSE_PAREN     :   ')' ;

OPEN_BRACE      :   '{' ;   
CLOSE_BRACE     :   '}' ;

OPEN_BOX        :   '[' ;
CLOSE_BOX       :   ']' ;

fragment 
LETTER          :   'a'..'z' | 'A'..'Z' ;
fragment
INTEGER         :   '0'..'9'+ ;
fragment
FLOAT           :   INTEGER+ '.' INTEGER* ;
fragment
ESC_SEQ         :   '\\' ('b'|'t'|'n'|'f'|'r'|'\"'|'\''|'\\') ;

Note that I've changed the name of OPEN_BRACKET and CLOSE_BRACKET into OPEN_PAREN and CLOSE_PAREN. The round ones, ( and ), are parenthesis, the square ones, [ and ], are called brackets (the ones you called boxes, but calling them boxes doesn't hurt IMO).

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