我仍然在my quest for a really simple language,我现在知道没有。所以我正在使用ANTLR3自己编写一个。扩展简单的ANTLR语法来支持输入变量
我发现this answer一个真正伟大的例子:
Exp.g:
grammar Exp;
eval 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);}
| '(' exp=additionExp ')' {$value = $exp.value;}
;
Number
: ('0'..'9')+ ('.' ('0'..'9')+)?
;
WS
: (' ' | '\t' | '\r'| '\n') {$channel=HIDDEN;}
;
Java代码:
public Double evaluate(String string, Map<String, Double> input) throws RecognitionException {
ANTLRStringStream in = new ANTLRStringStream(string);
ExpLexer lexer = new ExpLexer(in);
CommonTokenStream tokens = new CommonTokenStream(lexer);
return new ExpParser(tokens).eval();
}
使用这个ANTLR语法,我可以计算表达式像
(12+14)/2
并得到13结果。
现在唯一缺少的用例是一种向此注入简单双变量的方法,以便通过提供{“A”:12.0,“B”:14.0}作为输入来评估以下内容地图:
(A+B)/2
任何想法?
再次感谢!!! – arturh 2010-01-11 14:49:32
没问题,再次! :) – 2010-01-11 14:50:17