Map 定义初始化表达式,添加支持 key 可以为 int、long、float、double、true、false、null 常量

This commit is contained in:
James
2017-12-10 19:40:40 +08:00
parent bd1949fc56
commit e0abc218b1
6 changed files with 117 additions and 68 deletions

View File

@@ -83,6 +83,51 @@ public class Unary extends Expr {
throw new TemplateException("Unsupported operator: " + op.value(), location);
}
}
/**
* 如果可能的话,将 Unary 表达式转化成 Const 表达式,类似于 ExprParser.buildMapEntry() 需要这种转化来简化实现
* 除了可简化程序外,还起到一定的性能优化作用
*
* Number : +123 -456 +3.14 -0.12
* Boolean : !true !false
*
* 特别注意:
* Boolean 的支持并不需要,!true、!false 已在 ExprParser 中被 Logic 表达式接管,在此仅为逻辑上的完备性而添加
*/
public Expr toConstIfPossible() {
if (expr instanceof Const && (op == Sym.SUB || op == Sym.ADD || op == Sym.NOT)) {
} else {
return this;
}
Expr ret = this;
Const c = (Const)expr;
if (op == Sym.SUB) {
if (c.isInt()) {
ret = new Const(Sym.INT, -c.getInt());
} else if (c.isLong()) {
ret = new Const(Sym.LONG, -c.getLong());
} else if (c.isFloat()) {
ret = new Const(Sym.FLOAT, -c.getFloat());
} else if (c.isDouble()) {
ret = new Const(Sym.DOUBLE, -c.getDouble());
}
} else if (op == Sym.ADD) {
if (c.isNumber()) {
ret = c;
}
} else if (op == Sym.NOT) {
if (c.isBoolean()) {
ret = c.isTrue() ? Const.FALSE : Const.TRUE;
}
}
return ret;
}
public String toString() {
return op.toString() + expr.toString();
}
}