I an trying to extend the grammar given in the following link
I want to evaluate expressions like Height* @cos(x+y)
here @cos
is my project function. i want to add many such other system function
in my grammar added
CosExp return [double value]
: exp=additionExp {$value = Math.cos($exp.value);}
;
complete grammar (edited the working grammar) is given below:
grammar Exp;
@header {
package antlr.output;
import java.util.HashMap;
}
@parser::members {
private java.util.HashMap<String, Double> memory = new java.util.HashMap<String, Double>();
public static Double eval(String expression) throws Exception {
return eval(expression, new java.util.HashMap<String, Double>());
}
public static Double eval(String expression, java.util.Map<String, Double> vars) throws Exception {
ANTLRStringStream in = new ANTLRStringStream(expression);
ExpLexer lexer = new ExpLexer(in);
CommonTokenStream tokens = new CommonTokenStream(lexer);
ExpParser parser = new ExpParser(tokens);
parser.memory.putAll(vars);
return parser.parse();
}
}
parse returns [double value]
: exp=additionExp {$value = $exp.value;}
;
additionExp returns [double value]
: m1=multiplyExp {$value = $m1.value;}
( '+' m2=multiplyExp {$value += $m2.value;}
| '-' m2=multiplyExp {$value -= $m2.value;}
)*
;
multiplyExp returns [double value]
: a1=atomExp {$value = $a1.value;}
( '*' a2=atomExp {$value *= $a2.value;}
| '/' a2=atomExp {$value /= $a2.value;}
)*
;
atomExp returns [double value]
: n=Number {$value = Double.parseDouble($n.text);}
| i=Identifier {$value = memory.get($i.text);}
| '(' exp=additionExp ')' {$value = $exp.value;}
;
CosExp return [double value] // I have added these lines
: exp=additionExp {$value = Math.cos($exp.value);} // I have added these lines
;
Identifier
: ('a'..'z' | 'A'..'Z' | '_') ('a'..'z' | 'A'..'Z' | '_' | '0'..'9')*
;
Number
: ('0'..'9')+ ('.' ('0'..'9')+)?
;
WS
: (' ' | '\t' | '\r'| '\n') {$channel=HIDDEN;}
;
in my Java code
Map<String, Double> vars = new HashMap<String, Double>();
vars.put("Height", 12.0);
vars.put("x", 2.0);
vars.put("y", 2.0);
System.out.println(ExpParser.eval("Height* @cos(x+y)", vars));
when i run the code i am getting java.lang.NullPointerException
i know there is error in grammar but not able to figure out.