antlrantlr4antlrworks

ANTLR code for given grammar


I was trying to write ANTLR code for below grammar. I am quite new to ANTLR . Can somebody pls help me. I looked around and could find only tutorials related to basic calculations like addition ,subtraction etc.

PRINT a+b should print a+b expression and PRINT "This is test" should print This is test . INTEGER a,b should be accepted . I can do for INTEGER a but not for more than one INTEGER at a time.


Solution

  • maybe you could use the following grammar as a starting point

    grammar Simple;
    
    Opname: [a-zA-Z]+[_a-zA-ZA0-9]*;
    Operation: '+' | '-';
    Datatype: 'INTEGER';
    String : '"' (~('"') | '\\\"')* '"' | '\'' (~('\'') | '\\\'')* '\'' ;
    
    s: (print | sequence)* EOF;
    
    print: 'PRINT' (expression | string);
    
    string: String;
    
    expression: Opname Operation Opname;
    
    parlist: Opname (',' Opname)*;
    
    sequence:  Datatype parlist;
    
    WS  :  [ \t\r\n]+ -> skip;
    

    You could hook in a simple parse tree listener in order to collect the expressions or strings.

    Regarding the integer range: I would not do a validity check on the range in the grammar -- In the grammar, I would just ensure that the provided value is an int with something like Number: '-'? ([0-9]|[1-9][0-9]+);. Expressing the range as a regular expression that just accepts values that fall into that range inside the grammar is not a good idea. It is better to do this in the program that processes the values. Otherwise, you end up with something like this ;-):

    (-[0-1][0-9][0-9][0-9][0-9][0-9][0-9][0-9][0-9][0-9]|-20[0-9][0-9][0-9][0-9][0-9][0-9][0-9][0-9]|-21[0-3][0-9][0-9][0-9][0-9][0-9][0-9][0-9]|-214[0-6][0-9][0-9][0-9][0-9][0-9][0-9]|-2147[0-3][0-9][0-9][0-9][0-9][0-9]|-21474[0-7][0-9][0-9][0-9][0-9]|-214748[0-2][0-9][0-9][0-9]|-2147483[0-5][0-9][0-9]|-21474836[0-3][0-9]|-214748364[0-2]|-[1-9][0-9]{0,8}|-[1-9][0-9]{0,8}|-[1-9][0-9]{0,8}|-[1-9][0-9]{0,8}|-[1-9][0-9]{0,8}|-[1-9][0-9]{0,8}|-[1-9][0-9]{0,8}|-[1-9][0-9]{0,8}|-[1-9][0-9]{0,8}|-[1-9][0-9]{0,8}|[0-9]|[1-9][0-9]*)&([0-1][0-9][0-9][0-9][0-9][0-9][0-9][0-9][0-9][0-9]|20[0-9][0-9][0-9][0-9][0-9][0-9][0-9][0-9]|21[0-3][0-9][0-9][0-9][0-9][0-9][0-9][0-9]|214[0-6][0-9][0-9][0-9][0-9][0-9][0-9]|2147[0-3][0-9][0-9][0-9][0-9][0-9]|21474[0-7][0-9][0-9][0-9][0-9]|214748[0-2][0-9][0-9][0-9]|2147483[0-5][0-9][0-9]|21474836[0-3][0-9]|214748364[0-2]|[1-9][0-9]{0,8}|[1-9][0-9]{0,8}|[1-9][0-9]{0,8}|[1-9][0-9]{0,8}|[1-9][0-9]{0,8}|[1-9][0-9]{0,8}|[1-9][0-9]{0,8}|[1-9][0-9]{0,8}|[1-9][0-9]{0,8}|[1-9][0-9]{0,8}|0|-[1-9][0-9]*)