基于antlr的表达式解析器
package formula;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.antlr.runtime.ANTLRStringStream;
import org.antlr.runtime.CommonTokenStream;
import org.antlr.runtime.tree.BaseTree;
import formula.function.Add;
import formula.function.Function;
import formula.function.FunctionException;
import formula.function.Max;
public class ExpressionEvaluator {
// Contains all of the functions in use.
private Map functions = new HashMap();
// Contains all of the variables in use.
private Map variables = new HashMap();
public ExpressionEvaluator(Map variables) {
// TODO Auto-generated constructor stub
this.variables = variables;
this.putFunction(new Max());
this.putFunction(new Add());
}
/**
* Adds a function to the list of functions to use when evaluating
* expressions.
*
* @param function
* The function being added.
*
* @exception IllegalArgumentException
* Thrown when the function name is not valid or the function
* name is already in use.
*/
public void putFunction(final Function function) {
// Make sure the function name is valid.
// Make sure the function name isn't already in use.
final Function existingFunction = (Function) functions.get(function
.getName());
if (existingFunction == null) {
functions.put(function.getName(), function);
} else {
throw new IllegalArgumentException("A function with the same name "
+ "already exists.");
}
}
/**
* Returns a funtion from the list of functions. If the function can not be
* found in the list of functions, then null will be returned.
*
* @param functionName
* The name of the function to retrieve the value for.
*
* @return The value for a function in the list of function.
*/
public Function getFunction(final String functionName) {
return (Function) functions.get(functionName);
}
/**
* Removes the function from the list of functions to use when evaluating
* expressions.
*
* @param functionName
* The name of the function to remove.
*/
public void removeFunction(final String functionName) {
if (functions.containsKey(functionName)) {
functions.remove(functionName);
} else {
throw new IllegalArgumentException("The function does not exist.");
}
}
/**
* Rturns the map of functions currently set on this object.
*
* @return the map of functions currently set on this object.
*/
public Map getFunctions() {
return functions;
}
/**
* Sets the map of functions for this object.
*
* @param functions
* The map of functions for this object.
*/
public void setFunctions(Map functions) {
this.functions = functions;
}
public ActiveOperand eval(BaseTree tree) throws FunctionException {
ActiveOperand result = null;
switch (tree.getType()) {
case FormulaLexer.NUM:
Integer temp = Integer.valueOf(tree.getChild(0).toStringTree());
result = new ActiveOperand(temp.getClass(), temp);
break;
case FormulaLexer.CALL:
result = evalFunction(tree);
break;
case FormulaLexer.T__18:
result = addFunction(tree);
break;
case FormulaLexer.VAR:
String varName = tree.getChild(0).toStringTree();
Object varValue = variables.get(varName);
result = new ActiveOperand(varValue.getClass(), varValue);
break;
}
return result;
}
// call has two oprands ,e.g. call max 2
private ActiveOperand addFunction(BaseTree tree) throws FunctionException {
List<Object> children = tree.getChildren();
if (null == children || children.size() != 2) {
throw new FunctionException("Two numeric arguments are required.");
}
Integer paramNum = children.size();
ActiveOperand[] arguments = new ActiveOperand[paramNum];
for (int i = 0; i < paramNum; i++) {
BaseTree t = (BaseTree) children.get(i);
arguments[i] = eval(t);
}
return evalFunction("add", arguments);
// stack.push(frame);
// asn 赋值 assign 一个操作数 栈顶元素出栈,存储于数据存储器中
}
// call has two oprands ,e.g. call max 2
private ActiveOperand evalFunction(BaseTree tree) throws FunctionException {
List<Object> children = tree.getChildren();
Integer paramNum = children.size() - 1;
ActiveOperand[] arguments = new ActiveOperand[paramNum];
for (int i = 0; i < paramNum; i++) {
BaseTree t = (BaseTree) children.get(i + 1);
arguments[i] = eval(t);
}
return evalFunction(((BaseTree) children.get(0)).toStringTree(),
arguments);
// stack.push(frame);
// asn 赋值 assign 一个操作数 栈顶元素出栈,存储于数据存储器中
}
// call has two oprands ,e.g. call max 2
private ActiveOperand evalFunction(String functionName,
ActiveOperand[] arguments) throws FunctionException {
Function function = this.getFunction(functionName);
return function.execute(arguments);
// stack.push(frame);
// asn 赋值 assign 一个操作数 栈顶元素出栈,存储于数据存储器中
}
public static void main(String[] args) throws Exception {
String[] testStr = { "max(3,max(1,2))", "2", "a + b + 3", "a - (b + 3)"
// "a + (b * 3",
// "11.1+12b+a*b",
};
for (String s : testStr) {
System.out.println("Input expr: " + s);
run(s);
}
}
public static void run(String expr) throws Exception {
ANTLRStringStream in = new ANTLRStringStream(expr);
// 词法分析器
FormulaLexer lexer = new FormulaLexer(in);
CommonTokenStream tokens = new CommonTokenStream(lexer);
// 语法分析器
FormulaParser parser = new FormulaParser(tokens);
FormulaParser.prog_return ret = parser.prog();
Map variables = new HashMap();
variables.put("a", Integer.valueOf(2));
variables.put("b", Integer.valueOf(3));
ExpressionEvaluator evaluator = new ExpressionEvaluator(variables);
System.out.println(evaluator.eval((((BaseTree) ret.getTree()))));
// System.out.println(((BaseTree)ret.getTree()).toStringTree());
// toStringTree(((BaseTree)ret.getTree()));
}
}
基于antlr的表达式解析器的更多相关文章
- java字符串应用之表达式解析器
一.表达式的组成 1.数字 2.运算符:+ - / * ^ % = 3.圆括号 4.变量二.运算符优先级 由高到低分别为:+-(正负号).^.*/%.+-.= 优先 ...
- 基于Jquery的XML解析器,返回定制的HTML
依据HTML模板返回解析的XML 依赖jQuery 1.41. [代码]基于Jquery的xml解析器并返回定制的HTML /** * jQuery插件 * Author: pureco ...
- OO第四单元——基于UML的UML解析器总结&OO课程总结
OO第四单元--基于UML的UML解析器总结&OO课程总结 前言:一学期愉快(痛苦)的OO课程学习结束了,OO几个单元作业都各有特色,实验也各有特色,仔细回味起来,不再是单纯的敲代码(但自己还 ...
- OSS.Core基于Dapper封装(表达式解析+Emit)仓储层的构思及实现
最近趁着不忙,在构思一个搭建一个开源的完整项目,至于原因以及整个项目框架后边文章我再说明.既然要起一个完整的项目,那么数据仓储访问就必不可少,这篇文章我主要介绍这个新项目(OSS.Core)中我对仓储 ...
- [LeetCode] Ternary Expression Parser 三元表达式解析器
Given a string representing arbitrarily nested ternary expressions, calculate the result of the expr ...
- C 四则运算表达式解析器
下载实例:http://www.wisdomdd.cn/Wisdom/resource/articleDetail.htm?resourceId=1074 程序主要包括:基础结构定义.词法分析.语法分 ...
- dom4j解析器 基于dom4j的xpath技术 简单工厂设计模式 分层结构设计思想 SAX解析器 DOM编程
*1 dom4j解析器 1)CRUD的含义:CreateReadUpdateDelete增删查改 2)XML解析器有二类,分别是DOM和SAX(simple Api for xml). ...
- 基于Java的简易表达式解析工具(一)
最近需要用到相关表达式解析的工具,然后去网上搜索,找到了一个用C#写的表达式解析工具,仔细看了功能后发现,这正是我需要的,如果我能将它改造成基于Java语言的方式,岂不是更好吗,所以花了一段时间,把网 ...
- atitit.java解析sql语言解析器解释器的实现
atitit.java解析sql语言解析器解释器的实现 1. 解析sql的本质:实现一个4gl dsl编程语言的编译器 1 2. 解析sql的主要的流程,词法分析,而后进行语法分析,语义分析,构建sq ...
- 在.NET Core中使用Irony实现自己的查询语言语法解析器
在之前<在ASP.NET Core中使用Apworks快速开发数据服务>一文的评论部分,.NET大神张善友为我提了个建议,可以使用Compile As a Service的Roslyn为语 ...
随机推荐
- JDK有用的新特性-Switch
目录 箭头表达式,新的 case 标签 yeild 返回值 Java Record Switch 的三个方面,参考: JEP 361 支持箭头表达式 支持 yied 返回值 支持 Java Recor ...
- 六,Spring Boot 容器中 Lombok 插件的详细使用,简化配置,提高开发效率
六,Spring Boot 容器中 Lombok 插件的详细使用,简化配置,提高开发效率 @ 目录 六,Spring Boot 容器中 Lombok 插件的详细使用,简化配置,提高开发效率 1. Lo ...
- EasyDarwin,EasyNVR, EasyNVS, EasyDSS...这些都是啥
EasyDarwin 是开源的基础版本, 其他都是衍生产品(http://www.easydarwin.org/) EasyNVR, 就是视频监控录像机,可以查看实时监控和保存监控视频, 如下图, ( ...
- Coursera self-driving2, State Estimation and Localization Week2, kalman filter 卡尔曼滤波
KF - Kalman Filter: EKF - Extended Kalman Filter: ES-EKF - Error State Extended Kalman Filter 和EKF一样 ...
- SQL SEVER CDC 启动和关闭 操作说明
什么是变更数据捕获 (CDC)? 变更数据捕获使用 SQL Server 代理记录表中发生的插入.更新及删除. 因此,它使得可以通过关系格式轻松使用这些数据更改. 将为修改的行捕获将这些更改数据应用到 ...
- frp_v0.37.1内网穿透,内网服务公网用不求人
前言: 公司内网无法访问,出差又需要用到公司内网进行办公,苦恼了好一阵.这时候想到了内网穿透,这就不得不提到几年前被安利的frp,一看GitHub竟然已经5年了,网上估计大把教程了. 那么什么是frp ...
- duxapp:基于Taro使用模块化开发,提升开发效率
duxapp是基于Taro二次开发的模块化框架 使用这个框架,结合框架提供的UI库和工具库,能帮助你快速且高质量的完成项目,且能实现同时开发小程序.H5.APP(React Native),并且保证各 ...
- SuperMap iServer新增支持FlatGeobuf数据格式,查询渲染性能提升2-3倍
导语 FlatGeobuf是一种地理数据存储格式,采用了二进制编码,相比其他文本或XML格式更高效,可以显著减小文件大小,这使得数据的传输和存储更加快速和高效. SuperMap iServer 11 ...
- 左值 <->右值
左值引用指向左值 右值引用指向右值 int a = 5; int &ref_a = a; // 左值引用指向左值,编译通过 int &ref_a = 5; // 左值引用指向了右值,会 ...
- Solon 3.0 新特性:HttpUtils 了解一下
Solon 3.0 引入一个叫 HttpUtils 小插件,这是一个简单的同步 HTTP 客户端,基于 URLConnection 适配(也支持切换为 OkHttp 适配).使得编写 HTTP 客户端 ...