| Refresh | Home EGTry.com

return value from rules


grammar

grammar P;

prog returns [int n] 
  :
   d1=D op='+'  d2=D 
     { 
        n=Integer.parseInt($d1.text) + Integer.parseInt($d2.text); 
     } 
  ;

D: '0' .. '9';

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


import java.io.FileInputStream;
import java.io.StringReader;

import org.antlr.runtime.*;

public class PMain {
    public static void main(String[] args) throws Exception {

    
        ANTLRStringStream input = new ANTLRStringStream("2+3");
        PLexer lexer = new PLexer(input);
        CommonTokenStream tokens = new CommonTokenStream(lexer);
        PParser parser = new PParser(tokens);
        int n=parser.prog();
        System.out.println("result: "+n);
    }
}


input

2+3


Output

result: 5