|
| 1 | +package rs.lostcity.deob.ast.transform; |
| 2 | + |
| 3 | +import com.github.javaparser.ast.CompilationUnit; |
| 4 | +import com.github.javaparser.ast.expr.*; |
| 5 | +import com.github.javaparser.resolution.UnsolvedSymbolException; |
| 6 | + |
| 7 | +public class RedundantThisTransformer extends AstTransformer { |
| 8 | + |
| 9 | + @Override |
| 10 | + public void transformUnit(CompilationUnit unit) { |
| 11 | + var fields = findAll(unit, FieldAccessExpr.class, |
| 12 | + expr -> isUnqualifiedThis(expr.getScope())); |
| 13 | + |
| 14 | + for (var expr : fields) { |
| 15 | + var nameExpr = new NameExpr(expr.getNameAsString()); |
| 16 | + expr.replace(nameExpr); |
| 17 | + |
| 18 | + try { |
| 19 | + if (nameExpr.resolve().isField()) { |
| 20 | + // still resolves to a field, `this` was redundant |
| 21 | + continue; |
| 22 | + } |
| 23 | + } catch (UnsolvedSymbolException e) { |
| 24 | + // can't resolve, revert to be safe |
| 25 | + // System.err.println("[" + getName() + "] WARNING: " + e.getMessage()); |
| 26 | + } |
| 27 | + |
| 28 | + // revert since replacing `this.someName` with `someName` did not resolve to a field (shadowed) |
| 29 | + nameExpr.replace(expr); |
| 30 | + } |
| 31 | + |
| 32 | + walk(unit, MethodCallExpr.class, expr -> { |
| 33 | + // this.someMethod() |
| 34 | + if (expr.getScope().filter(RedundantThisTransformer::isUnqualifiedThis).isPresent()) { |
| 35 | + expr.setScope(null); |
| 36 | + } |
| 37 | + }); |
| 38 | + } |
| 39 | + |
| 40 | + private static boolean isUnqualifiedThis(Expression expr) { |
| 41 | + return expr instanceof ThisExpr thisExpr && thisExpr.getTypeName().isEmpty(); |
| 42 | + } |
| 43 | +} |
0 commit comments