基于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为语 ...
随机推荐
- Kali初次使用,如何获得root权限?【转】
最新的kali 系统,安装的时候会创建一个新用户,不是root的,然后安装软件的时候会要求root权限,要启用root账号可以按下面这个写的 方法1已经确认可以.方法2没尝试,自己试试吧. 1.确定用 ...
- Innodb 单表索引查询和连接查询效率分析
一.MySQL查询访问方法 mysql执行查询语句的方式叫做访问方法或访问类型,这些访问类型具体为 const.ref.range.index.all等. 同一个查询语句可以使用多种不同的访问方法来执 ...
- 18 Python如何操作文件?
本篇是 Python 系列教程第 18 篇,更多内容敬请访问我的 Python 合集 1 打开文件 通常使用内置的 open(文件路径, 模式, encoding="utf-8") ...
- 小tips:...运算符(展开运算符、剩余操作符)
如下例子: 1. var set = new Set([1, 2, 3, 4, 4,4,4,4,2,2,2]) set=[...set] 2. let [head, ...tail] = [1, 2, ...
- ASP.NET Core – HttpClient
前言 以前写过的文章 Asp.net core 学习笔记 ( HttpClient ). 其实 HttpClient 内容是挺多的, 但是我自己用到的很少. 所以这篇记入一下自己用到的就好了. 参考 ...
- Figma 学习笔记 – Image
参考: Figma Tutorial: Images 3 Ways to Insert Image 1. rectangle / frame + fill 画一个 rectangle / frame ...
- 如何用VMWARE创建一个Linux虚拟机
序言 各位好啊,我是会编程的蜗牛,作为java开发者,我们都是需要接触Linux服务器的,一般部署应用都是部署在Linux服务器上的~ 但一般的服务器要么需要购买,要么只是公司里的,那么有没有免费的L ...
- C#/.NET/.NET Core技术前沿周刊 | 第 6 期(2024年9.16-9.22)
前言 C#/.NET/.NET Core技术前沿周刊,你的每周技术指南针!记录.追踪C#/.NET/.NET Core领域.生态的每周最新.最实用.最有价值的技术文章.社区动态.优质项目和学习资源等. ...
- Linux服务器磁盘空间占用情况分析与清理指南
为确保重大节日期间,团队负责的测试环境服务器磁盘不会占用过高,导致频繁报警.我们要求在重大节假日前对服务器磁盘占用情况进行检查.如果发现占用过高,则需人为介入,进行相应清理. 一.检查要求 查看各分区 ...
- Microsoft 发布 .NET 9 RC 2
距离最终版本还有一个月的时间,Microsoft 已经交付了 .NET 9 的第二个也是最后一个候选版本..NET 团队在公告帖子中写道[1],"当我们为 11 月的 .NET 9 正式发布 ...