From 222323eaa0cdb7e6a96f0db14df806d1ad9c5bf0 Mon Sep 17 00:00:00 2001 From: Graham Date: Sat, 8 Aug 2020 11:22:03 +0100 Subject: [PATCH] Add AssignExpr support to IdentityTransformer It can now simplify expressions like `x += 0`. Signed-off-by: Graham --- .../deob/ast/transform/IdentityTransformer.kt | 24 +++++++++++++++++++ 1 file changed, 24 insertions(+) diff --git a/deob-ast/src/main/java/dev/openrs2/deob/ast/transform/IdentityTransformer.kt b/deob-ast/src/main/java/dev/openrs2/deob/ast/transform/IdentityTransformer.kt index a57d96c47b..979b29d1ff 100644 --- a/deob-ast/src/main/java/dev/openrs2/deob/ast/transform/IdentityTransformer.kt +++ b/deob-ast/src/main/java/dev/openrs2/deob/ast/transform/IdentityTransformer.kt @@ -1,11 +1,13 @@ package dev.openrs2.deob.ast.transform import com.github.javaparser.ast.CompilationUnit +import com.github.javaparser.ast.expr.AssignExpr import com.github.javaparser.ast.expr.BinaryExpr import com.github.javaparser.ast.expr.Expression import com.github.javaparser.ast.expr.IntegerLiteralExpr import com.github.javaparser.ast.expr.LongLiteralExpr import com.github.javaparser.ast.expr.UnaryExpr +import com.github.javaparser.ast.stmt.ExpressionStmt import dev.openrs2.deob.ast.Library import dev.openrs2.deob.ast.LibraryGroup import dev.openrs2.deob.ast.util.walk @@ -46,6 +48,28 @@ class IdentityTransformer : Transformer() { } } } + + unit.walk { expr: AssignExpr -> + val identity = when (expr.operator) { + // x += 0, x -= 0 + AssignExpr.Operator.PLUS, AssignExpr.Operator.MINUS -> expr.value.isZero() + // x *= 1, x /= 1 + AssignExpr.Operator.MULTIPLY, AssignExpr.Operator.DIVIDE -> expr.value.isOne() + else -> false + } + + if (!identity) { + return@walk + } + + expr.parentNode.ifPresent { parent -> + if (parent is ExpressionStmt) { + parent.remove() + } else { + expr.replace(expr.target.clone()) + } + } + } } private fun Expression.isZero(): Boolean {