Search code examples
parsingcompiler-constructionantlr4lexer

Antlr4 parsing issue


When I try to work my message.expr file with Zmes.g4 grammar file via antlr-4.7.1-complete only first line works and there is no reaction for second one. Grammar is

grammar Zmes;
prog    :   stat+;
stat    :  (message|define);
message :  'MSG'     MSGNUM    TEXT; 
define  :  'DEF:'  ('String '|'int ')  ID ( ','  ('String '|'Int ')  ID)* ';';
fragment QUOTE      :   '\'';
MSGNUM              :   [0-9]+; 
TEXT                :   QUOTE ~[']* QUOTE;
MODULE              :   [A-Z][A-Z][A-Z] ;
ID                  :   [A-Z]([A-Za-z0-9_])*;
SKIPS               :   (' '|'\t'|'\r'?'\n'|'\r')+ -> skip;

and message.expr is

MSG 100  'MESSAGE YU';
DEF: String Svar1,Int Intv1;`

On cmd when I run like this

grun Zmes prog -tree message.expr

(prog (stat (message MSG 100 'MESSAGE YU'))) and there is no second reaction. Why can it be.


Solution

  • Your message should include ';' at the end:

    message :  'MSG'     MSGNUM    TEXT ';';
    

    Also, in your define rule you have 'int ', which should probably be 'Int' (no space and a capital i).

    I'd go for something like this:

    grammar Zmes;
    
    prog    : stat+ EOF;
    stat    : (message | define) SCOL;
    message : MSG MSGNUM TEXT;
    define  : DEF COL type ID (COMMA type ID)*;
    type    : STRING | INT;
    
    MSG    : 'MSG';
    DEF    : 'DEF';
    STRING : 'String';
    INT    : 'Int';
    COL    : ':';
    SCOL   : ';';
    COMMA  : ',';
    MSGNUM : [0-9]+;
    TEXT   : '\'' ~[']* '\'';
    MODULE : [A-Z] [A-Z] [A-Z] ;
    ID     : [A-Z] [A-Za-z0-9_]*;
    SKIPS  : (' '|'\t'|'\r'?'\n'|'\r')+ -> skip;
    

    which produces:

    enter image description here