简体   繁体   中英

Java ANTLR4 mismatched input '<EOF>' expecting KEY

I'm trying to define a simple grammar to parse expressions like

s=1,b=2

or

s=1,b=[1,2,3]

The grammar is (not full):

grammar KeyVal;
program : exprs EOF ;
exprs : expr (',' expr)* ;
expr  :  KEY '=' VALUE  ;         // match key=value

KEY : [a-zA-Z]+ ;             // match lower-case identifiers

VALUE : NUMBER | LIST ;

LIST : '[' NUMBER (',' NUMBER)* ']';



NUMBER   : INTEGER   ;

INTEGER    : DECIMAL_INTEGER    ;


DECIMAL_INTEGER   : NON_ZERO_DIGIT DIGIT* | '0'+
;

fragment NON_ZERO_DIGIT   : [1-9]    ;
/// digit          ::=  "0"..."9"
fragment DIGIT     : [0-9]    ;

WS : [ \t\r\n]+ -> skip ; // skip spaces, tabs, newlines

Java program which uses generated classes:

    String s = " s=1,a=2";
    KeyValLexer lexer = new KeyValLexer(CharStreams.fromString(s));
    CommonTokenStream commonTokenStream = new CommonTokenStream(lexer);
    KeyValParser parser = new KeyValParser(commonTokenStream);
    ProgramContext tree = parser.program();

provides error

line 1:8 mismatched input '<EOF>' expecting KEY

How can i avoid this error?

LIST should be a parser rule. Something like this should do it:

grammar KeyVal;

program
 : exprs EOF
 ;

exprs
 : expr ( ',' expr )*
 ;

expr
 :  KEY '=' value
 ;

value
 : DECIMAL_INTEGER
 | list
 ;

list
 : '[' value ( ',' value )* ']'
 ;

KEY
 : [a-zA-Z]+
 ;

DECIMAL_INTEGER
 : [1-9] [0-9]*
 | '0'+
 ;

WS
 : [ \t\r\n]+ -> skip
 ;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM