Improve Expression.negate()

This commit makes two changes:

* Uses the is operator instead of the isXXX methods provided by
  JavaParser, allowing smart casts to be used.
* Wraps unsupported expressions with a unary minus expression, rather
  than throwing an exception.

Signed-off-by: Graham <gpe@openrs2.dev>
Graham 4 years ago
parent e0708458f9
commit d33c03c708
  1. 17
      deob-ast/src/main/java/dev/openrs2/deob/ast/util/ExprUtils.kt

@ -32,22 +32,23 @@ fun Long.toLongLiteralExpr(): LongLiteralExpr {
} }
fun Expression.negate(): Expression { fun Expression.negate(): Expression {
return if (isUnaryExpr && asUnaryExpr().operator == UnaryExpr.Operator.MINUS) { return when (this) {
asUnaryExpr().expression.clone() is UnaryExpr -> when (operator) {
} else if (isIntegerLiteralExpr) { UnaryExpr.Operator.PLUS -> UnaryExpr(expression.clone(), UnaryExpr.Operator.MINUS)
when (val n = asIntegerLiteralExpr().asNumber()) { UnaryExpr.Operator.MINUS -> expression.clone()
else -> UnaryExpr(clone(), UnaryExpr.Operator.MINUS)
}
is IntegerLiteralExpr -> when (val n = asNumber()) {
IntegerLiteralExpr.MAX_31_BIT_UNSIGNED_VALUE_AS_LONG -> IntegerLiteralExpr(Integer.MIN_VALUE.toString()) IntegerLiteralExpr.MAX_31_BIT_UNSIGNED_VALUE_AS_LONG -> IntegerLiteralExpr(Integer.MIN_VALUE.toString())
is Int -> IntegerLiteralExpr((-n.toInt()).toString()) is Int -> IntegerLiteralExpr((-n.toInt()).toString())
else -> error("Invalid IntegerLiteralExpr type") else -> error("Invalid IntegerLiteralExpr type")
} }
} else if (isLongLiteralExpr) { is LongLiteralExpr -> when (val n = asNumber()) {
when (val n = asLongLiteralExpr().asNumber()) {
LongLiteralExpr.MAX_63_BIT_UNSIGNED_VALUE_AS_BIG_INTEGER -> Long.MIN_VALUE.toLongLiteralExpr() LongLiteralExpr.MAX_63_BIT_UNSIGNED_VALUE_AS_BIG_INTEGER -> Long.MIN_VALUE.toLongLiteralExpr()
is Long -> (-n).toLongLiteralExpr() is Long -> (-n).toLongLiteralExpr()
else -> error("Invalid LongLiteralExpr type") else -> error("Invalid LongLiteralExpr type")
} }
} else { else -> UnaryExpr(clone(), UnaryExpr.Operator.MINUS)
throw IllegalArgumentException()
} }
} }

Loading…
Cancel
Save