java-decompiler: optimization (less string buffer allocations on generating text)

This commit is contained in:
Roman Shevchenko 2014-09-04 14:30:28 +04:00
parent f4f9e8be28
commit 1cea85e49a
20 changed files with 835 additions and 1055 deletions

File diff suppressed because it is too large Load Diff

View File

@ -34,15 +34,13 @@ import org.jetbrains.java.decompiler.struct.attr.StructInnerClassesAttribute;
import org.jetbrains.java.decompiler.struct.gen.VarType;
import org.jetbrains.java.decompiler.util.InterpreterUtil;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.StringWriter;
import java.util.*;
import java.util.Map.Entry;
public class ClassesProcessor {
private HashMap<String, ClassNode> mapRootClasses = new HashMap<String, ClassNode>();
private Map<String, ClassNode> mapRootClasses = new HashMap<String, ClassNode>();
public ClassesProcessor(StructContext context) {
@ -96,7 +94,7 @@ public class ClassesProcessor {
arr[3] = entry[3];
// enclosing class
String enclClassName = null;
String enclClassName;
if (entry[1] != 0) {
enclClassName = strentry[1];
}
@ -186,9 +184,9 @@ public class ClassesProcessor {
Object[] arr = mapInnerClasses.get(nestedClass);
if ((Integer)arr[2] == ClassNode.CLASS_MEMBER) {
//if ((Integer)arr[2] == ClassNode.CLASS_MEMBER) {
// FIXME: check for consistent naming
}
//}
nestednode.type = (Integer)arr[2];
nestednode.simpleName = (String)arr[1];
@ -234,56 +232,49 @@ public class ClassesProcessor {
}
}
public void writeClass(StructClass cl, BufferedWriter writer) throws IOException {
public void writeClass(StructClass cl, StringBuilder buffer) throws IOException {
ClassNode root = mapRootClasses.get(cl.qualifiedName);
if (root.type != ClassNode.CLASS_ROOT) {
return;
}
try {
DecompilerContext.setImportCollector(new ImportCollector(root));
ImportCollector importCollector = new ImportCollector(root);
DecompilerContext.setImportCollector(importCollector);
DecompilerContext.setCounterContainer(new CounterContainer());
// lambda processing
LambdaProcessor lambda_proc = new LambdaProcessor();
lambda_proc.processClass(root);
new LambdaProcessor().processClass(root);
// add simple class names to implicit import
addClassnameToImport(root, DecompilerContext.getImportCollector());
// build wrappers for all nested classes
// that's where the actual processing takes place
addClassnameToImport(root, importCollector);
// build wrappers for all nested classes (that's where actual processing takes place)
initWrappers(root);
NestedClassProcessor nestedproc = new NestedClassProcessor();
nestedproc.processClass(root, root);
new NestedClassProcessor().processClass(root, root);
NestedMemberAccess nstmember = new NestedMemberAccess();
nstmember.propagateMemberAccess(root);
new NestedMemberAccess().propagateMemberAccess(root);
ClassWriter clwriter = new ClassWriter();
StringBuilder classBuffer = new StringBuilder();
new ClassWriter().classToJava(root, classBuffer, 0);
StringWriter strwriter = new StringWriter();
clwriter.classToJava(root, new BufferedWriter(strwriter), 0);
String lineSeparator = DecompilerContext.getNewLineSeparator();
int index = cl.qualifiedName.lastIndexOf("/");
if (index >= 0) {
String packageName = cl.qualifiedName.substring(0, index).replace('/', '.');
writer.write("package ");
writer.write(packageName);
writer.write(";");
writer.write(DecompilerContext.getNewLineSeparator());
writer.write(DecompilerContext.getNewLineSeparator());
buffer.append("package ");
buffer.append(packageName);
buffer.append(";");
buffer.append(lineSeparator);
buffer.append(lineSeparator);
}
DecompilerContext.setProperty(DecompilerContext.CURRENT_CLASS_NODE, root);
if (importCollector.writeImports(buffer)) {
buffer.append(lineSeparator);
}
DecompilerContext.getImportCollector().writeImports(writer);
writer.write(DecompilerContext.getNewLineSeparator());
writer.write(strwriter.toString());
writer.flush();
buffer.append(classBuffer);
}
finally {
destroyWrappers(root);
@ -327,7 +318,7 @@ public class ClassesProcessor {
}
}
public HashMap<String, ClassNode> getMapRootClasses() {
public Map<String, ClassNode> getMapRootClasses() {
return mapRootClasses;
}
@ -369,7 +360,7 @@ public class ClassesProcessor {
public ClassNode(String content_class_name,
String content_method_name,
String content_method_descriptor,
int content_method_invokation_type,
int content_method_invocation_type,
String lambda_class_name,
String lambda_method_name,
String lambda_method_descriptor,
@ -386,7 +377,7 @@ public class ClassesProcessor {
lambda_information.content_class_name = content_class_name;
lambda_information.content_method_name = content_method_name;
lambda_information.content_method_descriptor = content_method_descriptor;
lambda_information.content_method_invokation_type = content_method_invokation_type;
lambda_information.content_method_invocation_type = content_method_invocation_type;
lambda_information.content_method_key =
InterpreterUtil.makeUniqueKey(lambda_information.content_method_name, lambda_information.content_method_descriptor);
@ -401,7 +392,7 @@ public class ClassesProcessor {
lambda_information.is_method_reference = is_method_reference;
lambda_information.is_content_method_static =
(lambda_information.content_method_invokation_type == CodeConstants.CONSTANT_MethodHandle_REF_invokeStatic); // FIXME: redundant?
(lambda_information.content_method_invocation_type == CodeConstants.CONSTANT_MethodHandle_REF_invokeStatic); // FIXME: redundant?
}
public ClassNode(int type, StructClass classStruct) {
@ -428,7 +419,7 @@ public class ClassesProcessor {
public String content_class_name;
public String content_method_name;
public String content_method_descriptor;
public int content_method_invokation_type; // values from CONSTANT_MethodHandle_REF_*
public int content_method_invocation_type; // values from CONSTANT_MethodHandle_REF_*
public String content_method_key;

View File

@ -26,8 +26,6 @@ import org.jetbrains.java.decompiler.struct.StructClass;
import org.jetbrains.java.decompiler.struct.StructContext;
import org.jetbrains.java.decompiler.struct.lazy.LazyLoader;
import java.io.BufferedWriter;
import java.io.StringWriter;
import java.util.Map;
@ -81,9 +79,9 @@ public class Fernflower implements IDecompiledData {
public String getClassContent(StructClass cl) {
try {
StringWriter writer = new StringWriter();
classesProcessor.writeClass(cl, new BufferedWriter(writer));
return writer.toString();
StringBuilder buffer = new StringBuilder();
classesProcessor.writeClass(cl, buffer);
return buffer.toString();
}
catch (Throwable ex) {
DecompilerContext.getLogger().writeMessage("Class " + cl.qualifiedName + " couldn't be fully decompiled.", ex);

View File

@ -20,8 +20,6 @@ import org.jetbrains.java.decompiler.main.ClassesProcessor.ClassNode;
import org.jetbrains.java.decompiler.main.DecompilerContext;
import org.jetbrains.java.decompiler.struct.StructContext;
import java.io.BufferedWriter;
import java.io.IOException;
import java.util.*;
import java.util.Map.Entry;
@ -30,12 +28,9 @@ public class ImportCollector {
private static final String JAVA_LANG_PACKAGE = "java.lang";
private HashMap<String, String> mapSimpleNames = new HashMap<String, String>();
private HashSet<String> setNotImportedNames = new HashSet<String>();
private Map<String, String> mapSimpleNames = new HashMap<String, String>();
private Set<String> setNotImportedNames = new HashSet<String>();
private String currentPackageSlash = "";
private String currentPackagePoint = "";
public ImportCollector(ClassNode root) {
@ -77,7 +72,7 @@ public class ImportCollector {
return retname;
}
}
else if (node == null || !node.classStruct.isOwn()) {
else {
fullname = fullname.replace('$', '.');
}
@ -112,18 +107,20 @@ public class ImportCollector {
return retname == null ? nshort : retname;
}
public void writeImports(BufferedWriter writer) throws IOException {
public boolean writeImports(StringBuilder buffer) {
List<String> imports = packImports();
for (String s : packImports()) {
writer.write("import ");
writer.write(s);
writer.write(";");
writer.write(DecompilerContext.getNewLineSeparator());
for (String s : imports) {
buffer.append("import ");
buffer.append(s);
buffer.append(";");
buffer.append(DecompilerContext.getNewLineSeparator());
}
return imports.size() > 0;
}
private List<String> packImports() {
List<Entry<String, String>> lst = new ArrayList<Entry<String, String>>(mapSimpleNames.entrySet());
Collections.sort(lst, new Comparator<Entry<String, String>>() {
@ -138,12 +135,11 @@ public class ImportCollector {
List<String> res = new ArrayList<String>();
for (Entry<String, String> ent : lst) {
if (!setNotImportedNames.contains(ent.getKey()) // not the current class or one of the nested ones. Also not the empty package.
&& !JAVA_LANG_PACKAGE.equals(ent.getValue())
&& ent.getValue().length() > 0) {
String imp = ent.getValue() + "." + ent.getKey();
res.add(imp);
// exclude a current class or one of the nested ones, java.lang and empty packages
if (!setNotImportedNames.contains(ent.getKey()) &&
!JAVA_LANG_PACKAGE.equals(ent.getValue()) &&
!ent.getValue().isEmpty()) {
res.add(ent.getValue() + "." + ent.getKey());
}
}

View File

@ -28,9 +28,6 @@ import org.jetbrains.java.decompiler.struct.gen.VarType;
import org.jetbrains.java.decompiler.util.InterpreterUtil;
import org.jetbrains.java.decompiler.util.ListStack;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.StringWriter;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
@ -260,29 +257,16 @@ public class NewExprent extends Exprent {
buf.setLength(0);
}
StringWriter strwriter = new StringWriter();
BufferedWriter bufstrwriter = new BufferedWriter(strwriter);
ClassWriter clwriter = new ClassWriter();
try {
if (lambda) {
clwriter.classLambdaToJava(child, bufstrwriter, (constructor == null ? null : constructor.getInstance()), indent);
if (lambda) {
if (!DecompilerContext.getOption(IFernflowerPreferences.LAMBDA_TO_ANONYMOUS_CLASS)) {
buf.setLength(0); // remove the usual 'new <class>()', it will be replaced with lambda style '() ->'
}
else {
clwriter.classToJava(child, bufstrwriter, indent);
}
bufstrwriter.flush();
Exprent methodObject = constructor == null ? null : constructor.getInstance();
new ClassWriter().classLambdaToJava(child, buf, methodObject, indent);
}
catch (IOException ex) {
throw new RuntimeException(ex);
else {
new ClassWriter().classToJava(child, buf, indent);
}
if (lambda && !DecompilerContext.getOption(IFernflowerPreferences.LAMBDA_TO_ANONYMOUS_CLASS)) {
buf.setLength(0); // remove the usual 'new <class>()', it will
// be replaced with lambda style '() ->'
}
buf.append(strwriter.toString());
}
else if (directArrayInit) {
VarType leftType = newtype.copy();
@ -293,10 +277,7 @@ public class NewExprent extends Exprent {
if (i > 0) {
buf.append(", ");
}
StringBuilder buff = new StringBuilder();
ExprProcessor.getCastedExprent(lstArrayElements.get(i), leftType, buff, indent, false);
buf.append(buff);
ExprProcessor.getCastedExprent(lstArrayElements.get(i), leftType, buf, indent, false);
}
buf.append("}");
}

View File

@ -26,9 +26,6 @@ import org.jetbrains.java.decompiler.modules.decompiler.vars.VarVersionPaar;
import org.jetbrains.java.decompiler.struct.gen.VarType;
import org.jetbrains.java.decompiler.util.InterpreterUtil;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.StringWriter;
import java.util.ArrayList;
import java.util.List;
@ -84,24 +81,11 @@ public class VarExprent extends Exprent {
}
public String toJava(int indent) {
StringBuilder buffer = new StringBuilder();
if (classdef) {
ClassNode child = DecompilerContext.getClassProcessor().getMapRootClasses().get(vartype.value);
StringWriter strwriter = new StringWriter();
BufferedWriter bufstrwriter = new BufferedWriter(strwriter);
ClassWriter clwriter = new ClassWriter();
try {
clwriter.classToJava(child, bufstrwriter, indent);
bufstrwriter.flush();
}
catch (IOException ex) {
throw new RuntimeException(ex);
}
return strwriter.toString();
new ClassWriter().classToJava(child, buffer, indent);
}
else {
String name = null;
@ -109,18 +93,16 @@ public class VarExprent extends Exprent {
name = processor.getVarName(new VarVersionPaar(index, version));
}
StringBuilder buf = new StringBuilder();
if (definition) {
if (processor != null && processor.getVarFinal(new VarVersionPaar(index, version)) == VarTypeProcessor.VAR_FINALEXPLICIT) {
buf.append("final ");
buffer.append("final ");
}
buf.append(ExprProcessor.getCastTypeName(getVartype())).append(" ");
buffer.append(ExprProcessor.getCastTypeName(getVartype())).append(" ");
}
buf.append(name == null ? ("var" + index + (version == 0 ? "" : "_" + version)) : name);
return buf.toString();
buffer.append(name == null ? ("var" + index + (version == 0 ? "" : "_" + version)) : name);
}
return buffer.toString();
}
public boolean equals(Object o) {

View File

@ -60,14 +60,18 @@ public class InterpreterUtil {
}
public static String getIndentString(int length) {
String indent = (String)DecompilerContext.getProperty(IFernflowerPreferences.INDENT_STRING);
StringBuilder buf = new StringBuilder();
while (length-- > 0) {
buf.append(indent);
}
appendIndent(buf, length);
return buf.toString();
}
public static void appendIndent(StringBuilder buffer, int length) {
String indent = (String)DecompilerContext.getProperty(IFernflowerPreferences.INDENT_STRING);
while (length-- > 0) {
buffer.append(indent);
}
}
public static boolean equalSets(Collection<?> c1, Collection<?> c2) {
if (c1 == null) {
return c2 == null;

View File

@ -28,11 +28,17 @@ import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
public class SingleClassesTest {
private File testDataDir;
private File tempDir;
private ConsoleDecompiler decompiler;
@Before
public void setUp() throws IOException {
testDataDir = new File("testData");
if (!isTestDataDir(testDataDir)) testDataDir = new File("community/plugins/java-decompiler/engine/testData");
if (!isTestDataDir(testDataDir)) testDataDir = new File("plugins/java-decompiler/engine/testData");
assertTrue(isTestDataDir(testDataDir));
//noinspection SSBasedInspection
tempDir = File.createTempFile("decompiler_test_", "_dir");
assertTrue(tempDir.delete());
@ -52,6 +58,7 @@ public class SingleClassesTest {
decompiler = null;
delete(tempDir);
tempDir = null;
testDataDir = null;
}
@Test public void testClassFields() { doTest("TestClassFields"); }
@ -69,13 +76,9 @@ public class SingleClassesTest {
private void doTest(final String testName) {
try {
File testDataDir = new File("testData");
if (!isTestDataDir(testDataDir)) testDataDir = new File("community/plugins/java-decompiler/engine/testData");
if (!isTestDataDir(testDataDir)) testDataDir = new File("plugins/java-decompiler/engine/testData");
assertTrue(isTestDataDir(testDataDir));
File classFile = new File(testDataDir, "/classes/pkg/" + testName + ".class");
assertTrue(classFile.isFile());
decompiler.addSpace(classFile, true);
File[] innerClasses = classFile.getParentFile().listFiles(new FilenameFilter() {
@Override

View File

@ -1,12 +1,9 @@
package pkg;
public class TestClassFields {
private static int[] sizes;
private static String[] names = new String[]{"name1", "name2"};
static {
sizes = new int[names.length];
}

View File

@ -10,10 +10,8 @@ import java.util.function.Predicate;
import java.util.function.Supplier;
public class TestClassLambda {
public int field = 0;
public void testLambda() {
List var1 = Arrays.asList(new Integer[]{Integer.valueOf(1), Integer.valueOf(2), Integer.valueOf(3), Integer.valueOf(4), Integer.valueOf(5), Integer.valueOf(6), Integer.valueOf(7)});
int var2 = (int)Math.random();

View File

@ -1,8 +1,6 @@
package pkg;
public class TestClassLoop {
public static void testSimpleInfinite() {
while(true) {
System.out.println();

View File

@ -1,8 +1,6 @@
package pkg;
public class TestClassSwitch {
public void testCaseOrder(int var1) {
switch(var1) {
case 5:

View File

@ -4,7 +4,6 @@ import java.util.ArrayList;
import java.util.List;
public class TestClassTypes {
public void testBoolean() {
byte var1 = 0;
long var2 = System.currentTimeMillis();

View File

@ -1,12 +1,9 @@
package pkg;
public class TestClassVar {
private boolean field_boolean = Math.random() > 0.0D;
public int field_int = 0;
public void testFieldSSAU() {
for(int var1 = 0; var1 < 10; ++var1) {
try {

View File

@ -1,11 +1,8 @@
package pkg;
class TestCodeConstructs {
private int count = 0;
void expressions() {
(new String()).hashCode();
}

View File

@ -3,7 +3,6 @@ package pkg;
import java.util.Date;
public class TestConstants {
static final boolean T = true;
static final boolean F = false;
static final char C0 = '\n';
@ -28,7 +27,6 @@ public class TestConstants {
static final double DMin = 4.9E-324D;
static final double DMax = 1.7976931348623157E308D;
@TestConstants.A(byte.class)
void m1() {
}
@ -70,7 +68,6 @@ public class TestConstants {
}
@interface A {
Class<?> value();
}
}

View File

@ -1,15 +1,12 @@
package pkg;
public class TestDeprecations {
/** @deprecated */
public int byComment;
/** @deprecated */
@Deprecated
public int byAnno;
/** @deprecated */
public void byComment() {
}
@ -22,11 +19,9 @@ public class TestDeprecations {
/** @deprecated */
@Deprecated
public static class ByAnno {
}
/** @deprecated */
public static class ByComment {
}
}

View File

@ -1,8 +1,6 @@
package pkg;
public enum TestEnum {
E1,
E2 {
public void m() {
@ -13,8 +11,8 @@ public enum TestEnum {
public void m() {
}
};
private String s;
private String s;
public void m() {
}
@ -26,5 +24,4 @@ public enum TestEnum {
private TestEnum(@Deprecated String var3) {
this.s = var3;
}
}

View File

@ -1,8 +1,6 @@
package pkg;
public class TestExtendsList {
static <T extends Comparable<? super T>> T m1(T var0) {
return null;
}

View File

@ -1,8 +1,6 @@
package pkg;
public class TestMethodParameters {
TestMethodParameters(@Deprecated int var1) {
}
@ -14,7 +12,6 @@ public class TestMethodParameters {
void local() {
class Local {
Local(@Deprecated int var2) {
}
@ -25,7 +22,6 @@ public class TestMethodParameters {
}
static class C2 {
C2(@Deprecated int var1) {
}
@ -37,7 +33,6 @@ public class TestMethodParameters {
}
class C1 {
C1(@Deprecated int var2) {
}