Adder.java
Adder.g4
grammar Adder; WS : [ \t\r\n]+ -> skip ; Num : (‘-‘)?[0-9]+ | (‘-‘)?[0-9]+’.'[0-9]+ ; expr : expr ‘+’ expr # addExpr | Num # numExpr ; start : expr EOF ; Error : . ;
Adder.java
Adder.java
import org . antlr . v4 . runtime . * ;
import org . antlr . v4 . runtime . tree . * ;
import java . io . * ;
public class Adder {
public static void main ( String [] args ) throws IOException {
BufferedReader in =
new BufferedReader ( new InputStreamReader ( System . in ));
CharStream inputStream = CharStreams . fromReader ( in );
AdderLexer lexer = new AdderLexer ( inputStream );
CommonTokenStream commonTokenStream = new CommonTokenStream ( lexer );
AdderParser parser = new AdderParser ( commonTokenStream );
parser . setErrorHandler ( new BailErrorStrategy ());
ParseTree tree = parser . start ();
AdderInterpreter interpreter = new AdderInterpreter ();
Float result = interpreter . visit ( tree );
System . out . println ( result . toString ());
}
}
AdderInterpreter.java
AdderInterpreter.java
public class AdderInterpreter extends AdderBaseVisitor < Float > {
@ Override
public Float visitAddExpr ( AdderParser . AddExprContext ctx ) {
float result = visit ( ctx . expr ( 0 )). floatValue () +
visit ( ctx . expr ( 1 )). floatValue ();
return Float . valueOf ( result );
}
@ Override
public Float visitNumExpr ( AdderParser . NumExprContext ctx ) {
return Float . valueOf ( ctx . Num (). getText ());
}
@ Override
public Float visitStart ( AdderParser . StartContext ctx ) {
return visit ( ctx . expr ());
}
}