org.apache.bcel.generic.ClassGen - java examples

Here are the examples of the java api org.apache.bcel.generic.ClassGen taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.

51 Examples 7

19 View Complete Implementation : InstrumentorForCL.java
Copyright GNU General Public License v2.0
Author : OmniscientDebugger
public byte[] patchCL(byte[] b) {
    try {
        final ClreplacedGen cg = new ClreplacedGen(new ClreplacedParser(new ByteArrayInputStream(b), "<generated>").parse());
        final String clreplacedName = cg.getClreplacedName();
        final Method[] methods = cg.getMethods();
        final ConstantPoolGen cpg = cg.getConstantPool();
        final InstructionFactory factory = new InstructionFactory(cg);
        // for all methods, look for caller side "this.define0" calls
        for (int i = 0; i < methods.length; i++) {
            final MethodGen mg = new MethodGen(methods[i], clreplacedName, cpg);
            final InstructionList il = mg.getInstructionList();
            if (il == null)
                continue;
            InstructionHandle ih = il.getStart();
            String methodName = methods[i].getName();
            while (ih != null) {
                final Instruction ins = ih.getInstruction();
                if (ins instanceof INVOKESPECIAL || ins instanceof INVOKESTATIC || ins instanceof INVOKEVIRTUAL) {
                    final InvokeInstruction invokeInst = (InvokeInstruction) ins;
                    final String callerSideMethodClreplacedName = invokeInst.getClreplacedName(cpg);
                    final String callerSideMethodName = invokeInst.getMethodName(cpg);
                    if ("java.lang.ClreplacedLoader".equals(callerSideMethodClreplacedName) && "defineClreplaced0".equals(callerSideMethodName)) {
                        // replacedert compliant JRE
                        Type[] args = invokeInst.getArgumentTypes(cpg);
                        replacedertSupported(args);
                        // store former method args in local vars
                        InstructionHandle ihc = null;
                        if (args.length > 5) {
                            // IBM like JRE with extra args
                            ihc = il.append(ih.getPrev(), factory.createStore(args[args.length - 1], 2100 + args.length - 1));
                            for (int index = args.length - 2; index >= 5; index--) {
                                ihc = il.append(ihc, InstructionFactory.createStore(args[index], 2100 + index));
                            }
                            // protection domain
                            ihc = il.append(ihc, factory.createStore(Type.OBJECT, 2016));
                        } else {
                            // SUN regular JRE
                            // protection domain
                            ihc = il.append(ih.getPrev(), factory.createStore(Type.OBJECT, 2016));
                        }
                        // length
                        ihc = il.append(ihc, factory.createStore(Type.INT, 2015));
                        // index
                        ihc = il.append(ihc, factory.createStore(Type.INT, 2014));
                        // bytes
                        ihc = il.append(ihc, factory.createStore(Type.OBJECT, 2013));
                        // name
                        ihc = il.append(ihc, factory.createStore(Type.OBJECT, 2012));
                        // prepare method call stack
                        ihc = il.append(ihc, factory.createLoad(Type.OBJECT, 2012));
                        ihc = il.append(ihc, factory.createLoad(Type.OBJECT, 2013));
                        ihc = il.append(ihc, factory.createInvoke("com.lambda.Debugger.InstrumentorForCL", "debugify", new ArrayType(Type.BYTE, 1), new Type[] { Type.STRING, new ArrayType(Type.BYTE, 1) }, Constants.INVOKESTATIC));
                        // result bytes
                        ihc = il.append(ihc, factory.createStore(Type.OBJECT, 3018));
                        // rebuild former method call stack
                        // name
                        ihc = il.append(ihc, factory.createLoad(Type.OBJECT, 2012));
                        // bytes
                        ihc = il.append(ihc, factory.createLoad(Type.OBJECT, 3018));
                        ihc = il.append(ihc, new PUSH(cpg, 0));
                        // bytes
                        ihc = il.append(ihc, factory.createLoad(Type.OBJECT, 3018));
                        // .length
                        ihc = il.append(ihc, InstructionConstants.ARRAYLENGTH);
                        // protection domain
                        ihc = il.append(ihc, factory.createLoad(Type.OBJECT, 2016));
                        // extra args for IBM like JRE
                        if (args.length > 5) {
                            for (int index = 5; index < args.length; index++) {
                                ihc = il.append(ihc, factory.createLoad(args[index], 2100 + index));
                            }
                        }
                    }
                }
                ih = ih.getNext();
            }
            mg.setInstructionList(il);
            mg.setMaxLocals();
            mg.setMaxStack();
            methods[i] = mg.getMethod();
        }
        cg.setMethods(methods);
        return cg.getJavaClreplaced().getBytes();
    } catch (Exception e) {
        System.err.println("failed to patch ClreplacedLoader:");
        e.printStackTrace();
        return b;
    }
}

19 View Complete Implementation : BCELPerfTest.java
Copyright MIT License
Author : typetools
byte[] counterAdaptClreplaced(final InputStream is, final String name) throws Exception {
    JavaClreplaced jc = new ClreplacedParser(is, name + ".clreplaced").parse();
    ClreplacedGen cg = new ClreplacedGen(jc);
    ConstantPoolGen cp = cg.getConstantPool();
    if (!cg.isInterface()) {
        FieldGen fg = new FieldGen(ACC_PUBLIC, Type.getType("I"), "_counter", cp);
        cg.addField(fg.getField());
    }
    Method[] ms = cg.getMethods();
    for (int j = 0; j < ms.length; ++j) {
        MethodGen mg = new MethodGen(ms[j], cg.getClreplacedName(), cp);
        if (!mg.getName().equals("<init>") && !mg.isStatic() && !mg.isAbstract() && !mg.isNative()) {
            if (mg.getInstructionList() != null) {
                InstructionList il = new InstructionList();
                il.append(new ALOAD(0));
                il.append(new ALOAD(0));
                il.append(new GETFIELD(cp.addFieldref(name, "_counter", "I")));
                il.append(new ICONST(1));
                il.append(new IADD());
                il.append(new PUTFIELD(cp.addFieldref(name, "_counter", "I")));
                mg.getInstructionList().insert(il);
                mg.setMaxStack(Math.max(mg.getMaxStack(), 2));
                boolean lv = ms[j].getLocalVariableTable() == null;
                boolean ln = ms[j].getLineNumberTable() == null;
                if (lv) {
                    mg.removeLocalVariables();
                }
                if (ln) {
                    mg.removeLineNumbers();
                }
                cg.replaceMethod(ms[j], mg.getMethod());
            }
        }
    }
    return cg.getJavaClreplaced().getBytes();
}

19 View Complete Implementation : ElementValueGenTestCase.java
Copyright Apache License 2.0
Author : apache
public void testCreateByteElementValue() throws Exception {
    final ClreplacedGen cg = createClreplacedGen("HelloWorld");
    final ConstantPoolGen cp = cg.getConstantPool();
    final SimpleElementValueGen evg = new SimpleElementValueGen(ElementValueGen.PRIMITIVE_CHAR, cp, (byte) 'z');
    // Creation of an element like that should leave a new entry in the
    // cpool
    final int idx = cp.lookupInteger((byte) 'z');
    replacedertTrue("Should have the same index in the constantpool but " + evg.getIndex() + "!=" + idx, evg.getIndex() == idx);
    checkSerialize(evg, cp);
}

19 View Complete Implementation : ElementValueGenTestCase.java
Copyright Apache License 2.0
Author : apache
public void testCreateDoubleElementValue() throws Exception {
    final ClreplacedGen cg = createClreplacedGen("HelloWorld");
    final ConstantPoolGen cp = cg.getConstantPool();
    final SimpleElementValueGen evg = new SimpleElementValueGen(ElementValueGen.PRIMITIVE_DOUBLE, cp, 333.44);
    // Creation of an element like that should leave a new entry in the
    // cpool
    final int idx = cp.lookupDouble(333.44);
    replacedertTrue("Should have the same index in the constantpool but " + evg.getIndex() + "!=" + idx, evg.getIndex() == idx);
    checkSerialize(evg, cp);
}

19 View Complete Implementation : LDAPSSLSocketFactoryGenerator.java
Copyright Apache License 2.0
Author : apache
/**
 * Creates a static field _sslContext of type {@link SSLSocketFactory}.
 *
 * @param clreplacedGen
 * @param constantPoolGen
 */
private static void createSslContextStaticField(ClreplacedGen clreplacedGen, ConstantPoolGen constantPoolGen) {
    FieldGen fieldGen = new FieldGen(ACC_PRIVATE | ACC_STATIC, Type.getType(SSLSocketFactory.clreplaced), SSL_SOCKET_FACTORY_FIELD, constantPoolGen);
    clreplacedGen.addField(fieldGen.getField());
}

19 View Complete Implementation : ElementValueGenTestCase.java
Copyright Apache License 2.0
Author : apache
/**
 * Create primitive element values
 */
public void testCreateIntegerElementValue() throws Exception {
    final ClreplacedGen cg = createClreplacedGen("HelloWorld");
    final ConstantPoolGen cp = cg.getConstantPool();
    final SimpleElementValueGen evg = new SimpleElementValueGen(ElementValueGen.PRIMITIVE_INT, cp, 555);
    // Creation of an element like that should leave a new entry in the
    // cpool
    replacedertTrue("Should have the same index in the constantpool but " + evg.getIndex() + "!=" + cp.lookupInteger(555), evg.getIndex() == cp.lookupInteger(555));
    checkSerialize(evg, cp);
}

19 View Complete Implementation : VerbosePlugin.java
Copyright MIT License
Author : pragmatic-objects
@Override
public final void operateOn(final ClreplacedGen clreplacedGen, final JavaClreplaced clazz, final Repository repository) {
    System.out.println(plugin.getClreplaced().getName() + ": Transforming type " + clazz.getClreplacedName());
    plugin.operateOn(clreplacedGen, clazz, repository);
}

19 View Complete Implementation : ElementValueGenTestCase.java
Copyright Apache License 2.0
Author : apache
public void testCreateBooleanElementValue() throws Exception {
    final ClreplacedGen cg = createClreplacedGen("HelloWorld");
    final ConstantPoolGen cp = cg.getConstantPool();
    final SimpleElementValueGen evg = new SimpleElementValueGen(ElementValueGen.PRIMITIVE_BOOLEAN, cp, true);
    // Creation of an element like that should leave a new entry in the
    // cpool
    // 1 == true
    final int idx = cp.lookupInteger(1);
    replacedertTrue("Should have the same index in the constantpool but " + evg.getIndex() + "!=" + idx, evg.getIndex() == idx);
    checkSerialize(evg, cp);
}

19 View Complete Implementation : LDAPSSLSocketFactoryGenerator.java
Copyright Apache License 2.0
Author : apache
/**
 * Create a static method 'getDefault' returning {@link SocketFactory}
 * that creates a new instance of the sub-clreplaced and calls its no-argument
 * constructor, the newly created is returned to the caller.
 *
 * @param clreplacedGen
 * @param constantPoolGen
 * @param instructionFactory
 */
private static void createGetDefaultStaticMethod(ClreplacedGen clreplacedGen, ConstantPoolGen constantPoolGen, InstructionFactory instructionFactory) {
    InstructionList il = new InstructionList();
    String methodName = "getDefault";
    MethodGen mg = new // access flags
    MethodGen(// access flags
    ACC_STATIC | ACC_PUBLIC, // return type
    Type.getType(SSLSocketFactory.clreplaced), // argument types - no args
    new Type[0], // arg names - no args
    new String[0], methodName, // method, clreplaced
    clreplacedGen.getClreplacedName(), il, constantPoolGen);
    il.append(instructionFactory.createNew(clreplacedGen.getClreplacedName()));
    il.append(InstructionConst.DUP);
    il.append(instructionFactory.createInvoke(clreplacedGen.getClreplacedName(), "<init>", Type.VOID, new Type[] {}, INVOKESPECIAL));
    il.append(InstructionConst.ARETURN);
    mg.setMaxStack();
    clreplacedGen.addMethod(mg.getMethod());
    il.dispose();
}

19 View Complete Implementation : NopPlugin.java
Copyright MIT License
Author : pragmatic-objects
@Override
public final void operateOn(final ClreplacedGen clreplacedGen, final JavaClreplaced clazz, final Repository repository) {
// Do nothing
}

19 View Complete Implementation : ElementValueGenTestCase.java
Copyright Apache License 2.0
Author : apache
public void testCreateCharElementValue() throws Exception {
    final ClreplacedGen cg = createClreplacedGen("HelloWorld");
    final ConstantPoolGen cp = cg.getConstantPool();
    final SimpleElementValueGen evg = new SimpleElementValueGen(ElementValueGen.PRIMITIVE_CHAR, cp, 't');
    // Creation of an element like that should leave a new entry in the
    // cpool
    final int idx = cp.lookupInteger('t');
    replacedertTrue("Should have the same index in the constantpool but " + evg.getIndex() + "!=" + idx, evg.getIndex() == idx);
    checkSerialize(evg, cp);
}

19 View Complete Implementation : LDAPSSLSocketFactoryGenerator.java
Copyright Apache License 2.0
Author : apache
/**
 * Creates the LDAPSocketFactoryImpl clreplaced (subclreplaced of {@link AbstractLDAPSSLSocketFactory}.
 * A static method #getDefaulta, a static field _sslContent and no-arg constructor are added
 * to the clreplaced.
 *
 * @param clreplacedName
 *
 * @return byte code
 */
private static byte[] createSubClreplacedByteCode(final String clreplacedName) {
    ClreplacedGen clreplacedGen = new ClreplacedGen(clreplacedName, AbstractLDAPSSLSocketFactory.clreplaced.getName(), "<generated>", ACC_PUBLIC | ACC_SUPER, null);
    ConstantPoolGen constantPoolGen = clreplacedGen.getConstantPool();
    InstructionFactory factory = new InstructionFactory(clreplacedGen);
    createSslContextStaticField(clreplacedGen, constantPoolGen);
    createGetDefaultStaticMethod(clreplacedGen, constantPoolGen, factory);
    clreplacedGen.addEmptyConstructor(ACC_PROTECTED);
    JavaClreplaced javaClreplaced = clreplacedGen.getJavaClreplaced();
    ByteArrayOutputStream out = null;
    try {
        out = new ByteArrayOutputStream();
        javaClreplaced.dump(out);
        return out.toByteArray();
    } catch (IOException ioex) {
        throw new IllegalStateException("Could not write to a ByteArrayOutputStream - should not happen", ioex);
    } finally {
        closeSafely(out);
    }
}

19 View Complete Implementation : ElementValueGenTestCase.java
Copyright Apache License 2.0
Author : apache
public void testCreateFloatElementValue() throws Exception {
    final ClreplacedGen cg = createClreplacedGen("HelloWorld");
    final ConstantPoolGen cp = cg.getConstantPool();
    final SimpleElementValueGen evg = new SimpleElementValueGen(ElementValueGen.PRIMITIVE_FLOAT, cp, 111.222f);
    // Creation of an element like that should leave a new entry in the
    // cpool
    replacedertTrue("Should have the same index in the constantpool but " + evg.getIndex() + "!=" + cp.lookupFloat(111.222f), evg.getIndex() == cp.lookupFloat(111.222f));
    checkSerialize(evg, cp);
}

19 View Complete Implementation : ClassDumper.java
Copyright Apache License 2.0
Author : GoogleCloudPlatform
/**
 * Returns true if {@code sourceClreplacedName} has a method that has an exception handler for {@link
 * NoClreplacedDefFoundError}, {@link NoSuchMethodError} or {@link LinkageError}.
 */
boolean catchesLinkageError(String sourceClreplacedName) {
    try {
        JavaClreplaced sourceJavaClreplaced = loadJavaClreplaced(sourceClreplacedName);
        ClreplacedGen clreplacedGen = new ClreplacedGen(sourceJavaClreplaced);
        for (Method method : sourceJavaClreplaced.getMethods()) {
            MethodGen methodGen = new MethodGen(method, sourceClreplacedName, clreplacedGen.getConstantPool());
            CodeExceptionGen[] exceptionHandlers = methodGen.getExceptionHandlers();
            for (CodeExceptionGen codeExceptionGen : exceptionHandlers) {
                ObjectType catchType = codeExceptionGen.getCatchType();
                if (catchType == null) {
                    continue;
                }
                String caughtClreplacedName = catchType.getClreplacedName();
                if (ERRORS_CAUGHT_IN_SOURCE.contains(caughtClreplacedName)) {
                    // The source clreplaced catches an error and thus will not cause a runtime error
                    return true;
                }
            }
        }
        String outerClreplacedName = outerClreplacedName(sourceJavaClreplaced);
        if (outerClreplacedName != null) {
            try {
                return catchesLinkageError(outerClreplacedName);
            } catch (ClreplacedFormatException ex) {
                // When the outer clreplaced of an inner clreplaced does not exist in the clreplaced path, we cannot
                // say that the clreplacedes catch linkage errors.
                return false;
            }
        } else {
            // The source clreplaced does not have a method that catches NoClreplacedDefFoundError
            return false;
        }
    } catch (ClreplacedNotFoundException ex) {
        // Because the reference in the argument was extracted from the source clreplaced file,
        // the source clreplaced should be found.
        throw new ClreplacedFormatException("The source clreplaced in the reference is no longer available in the clreplaced path", ex);
    }
}

19 View Complete Implementation : ElementValueGenTestCase.java
Copyright Apache License 2.0
Author : apache
// //
// Create enum element value
public void testCreateEnumElementValue() throws Exception {
    final ClreplacedGen cg = createClreplacedGen("HelloWorld");
    final ConstantPoolGen cp = cg.getConstantPool();
    // Supports rainbow
    final ObjectType enumType = new ObjectType("SimpleEnum");
    // :)
    final EnumElementValueGen evg = new EnumElementValueGen(enumType, "Red", cp);
    // Creation of an element like that should leave a new entry in the
    // cpool
    replacedertTrue("The new ElementValue value index should match the contents of the constantpool but " + evg.getValueIndex() + "!=" + cp.lookupUtf8("Red"), evg.getValueIndex() == cp.lookupUtf8("Red"));
    // BCELBUG: Should the clreplaced signature or clreplaced name be in the constant
    // pool? (see note in ConstantPool)
    // replacedertTrue("The new ElementValue type index should match the contents
    // of the constantpool but "+
    // evg.getTypeIndex()+"!="+cp.lookupClreplaced(enumType.getSignature()),
    // evg.getTypeIndex()==cp.lookupClreplaced(enumType.getSignature()));
    checkSerialize(evg, cp);
}

19 View Complete Implementation : DebugAddressSpaceImpl.java
Copyright GNU General Public License v3.0
Author : kilograham
@Override
public ClreplacedGen modifyClreplaced(String clreplacedname, ClreplacedGen original) {
    return realAddressSpace.modifyClreplaced(clreplacedname, original);
}

19 View Complete Implementation : JPSXClassLoader.java
Copyright GNU General Public License v3.0
Author : kilograham
private Clreplaced makeClreplaced(final String name) throws ClreplacedNotFoundException {
    ClreplacedGen cgen = null;
    int genIndex = prefixIndex(generatorClreplacednamePrefixes, name);
    int modIndex = prefixIndex(modifierClreplacednamePrefixes, name);
    if (genIndex != -1) {
        // System.out.println("generating clreplaced "+name);
        cgen = generators.get(genIndex).generateClreplaced(name);
    } else {
        // make the ClreplacedGen from the raw data from our parent loader
        final URL url = getResource(getClreplacedFilename(name));
        if (url != null) {
            try {
                InputStream stream = url.openStream();
                if (modIndex == -1) {
                    // System.out.println("copying parent clreplaced "+name);
                    return getClreplacedFromStream(stream, name);
                } else {
                    cgen = new ClreplacedGen((new ClreplacedParser(stream, getClreplacedFilename(name))).parse());
                }
            } catch (IOException e) {
            // will cause a clreplaced not found exception later
            }
        }
    }
    if (cgen != null && modIndex != -1) {
        // System.out.println("modifying clreplaced "+name);
        // modify the clreplaced if needed
        cgen = modifiers.get(modIndex).modifyClreplaced(name, cgen);
    }
    if (cgen == null) {
        throw new ClreplacedNotFoundException(name);
    }
    JavaClreplaced jclreplaced = cgen.getJavaClreplaced();
    if (dumpClreplacedes) {
        try {
            jclreplaced.dump("modified_" + name + ".clreplaced");
        } catch (IOException e) {
        }
    }
    byte[] clreplacedData = jclreplaced.getBytes();
    return defineClreplaced(name, clreplacedData, 0, clreplacedData.length, null);
}

19 View Complete Implementation : BetterCFGBuilder2.java
Copyright GNU Lesser General Public License v2.1
Author : spotbugs
/**
 * Test driver.
 */
public static void main(String[] argv) throws Exception {
    if (argv.length != 1) {
        System.err.println("Usage: " + BetterCFGBuilder2.clreplaced.getName() + " <clreplaced file>");
        System.exit(1);
    }
    String methodName = SystemProperties.getProperty("cfgbuilder.method");
    JavaClreplaced jclreplaced = new ClreplacedParser(argv[0]).parse();
    ClreplacedGen clreplacedGen = new ClreplacedGen(jclreplaced);
    Method[] methodList = jclreplaced.getMethods();
    for (Method method : methodList) {
        if (method.isAbstract() || method.isNative()) {
            continue;
        }
        if (methodName != null && !method.getName().equals(methodName)) {
            continue;
        }
        MethodDescriptor descriptor = DescriptorFactory.instance().getMethodDescriptor(jclreplaced, method);
        MethodGen methodGen = new MethodGen(method, jclreplaced.getClreplacedName(), clreplacedGen.getConstantPool());
        CFGBuilder cfgBuilder = new BetterCFGBuilder2(descriptor, methodGen);
        cfgBuilder.build();
        CFG cfg = cfgBuilder.getCFG();
        CFGPrinter cfgPrinter = new CFGPrinter(cfg);
        System.out.println("---------------------------------------------------------------------");
        System.out.println("Method: " + SignatureConverter.convertMethodSignature(methodGen));
        System.out.println("---------------------------------------------------------------------");
        cfgPrinter.print(System.out);
    }
}

19 View Complete Implementation : ProxyCreator.java
Copyright Apache License 2.0
Author : apache
/**
 * Create JavaClreplaced object for a simple proxy for an java.awt.event.ActionListener
 * that just prints the preplaceded arguments, load and use it via the clreplaced loader
 * mechanism.
 */
public static void main(final String[] argv) throws Exception {
    final ClreplacedLoader loader = ProxyCreator.clreplaced.getClreplacedLoader();
    // instanceof won't work here ...
    // TODO this is broken; cannot ever be true now that ClreplacedLoader has been dropped
    if (loader.getClreplaced().toString().equals("clreplaced org.apache.bcel.util.ClreplacedLoader")) {
        // Real clreplaced name will be set by the clreplaced loader
        final ClreplacedGen cg = new ClreplacedGen("foo", "java.lang.Object", "", Constants.ACC_PUBLIC, new String[] { "java.awt.event.ActionListener" });
        // That's important, otherwise newInstance() won't work
        cg.addEmptyConstructor(Constants.ACC_PUBLIC);
        final InstructionList il = new InstructionList();
        final ConstantPoolGen cp = cg.getConstantPool();
        final InstructionFactory factory = new InstructionFactory(cg);
        final int out = cp.addFieldref("java.lang.System", "out", "Ljava/io/PrintStream;");
        final int println = cp.addMethodref("java.io.PrintStream", "println", "(Ljava/lang/Object;)V");
        final MethodGen mg = new MethodGen(Constants.ACC_PUBLIC, Type.VOID, new Type[] { new ObjectType("java.awt.event.ActionEvent") }, null, "actionPerformed", "foo", il, cp);
        // System.out.println("actionPerformed:" + event);
        il.append(new GETSTATIC(out));
        il.append(factory.createNew("java.lang.StringBuffer"));
        il.append(InstructionConstants.DUP);
        il.append(new PUSH(cp, "actionPerformed:"));
        il.append(factory.createInvoke("java.lang.StringBuffer", "<init>", Type.VOID, new Type[] { Type.STRING }, Constants.INVOKESPECIAL));
        il.append(new ALOAD(1));
        il.append(factory.createAppend(Type.OBJECT));
        il.append(new INVOKEVIRTUAL(println));
        il.append(InstructionConstants.RETURN);
        mg.stripAttributes(true);
        mg.setMaxStack();
        mg.setMaxLocals();
        cg.addMethod(mg.getMethod());
        final byte[] bytes = cg.getJavaClreplaced().getBytes();
        System.out.println("Uncompressed clreplaced: " + bytes.length);
        final String s = Utility.encode(bytes, true);
        System.out.println("Encoded clreplaced: " + s.length());
        System.out.print("Creating proxy ... ");
        final ActionListener a = (ActionListener) createProxy("foo.bar.", s);
        System.out.println("Done. Now calling actionPerformed()");
        a.actionPerformed(new ActionEvent(a, ActionEvent.ACTION_PERFORMED, "hello"));
    } else {
        System.err.println("Call me with java org.apache.bcel.util.JavaWrapper ProxyCreator");
    }
}

19 View Complete Implementation : BCELPerfTest.java
Copyright MIT License
Author : typetools
byte[] nullAdaptClreplaced(final InputStream is, final String name) throws Exception {
    JavaClreplaced jc = new ClreplacedParser(is, name + ".clreplaced").parse();
    ClreplacedGen cg = new ClreplacedGen(jc);
    ConstantPoolGen cp = cg.getConstantPool();
    Method[] ms = cg.getMethods();
    for (int j = 0; j < ms.length; ++j) {
        MethodGen mg = new MethodGen(ms[j], cg.getClreplacedName(), cp);
        boolean lv = ms[j].getLocalVariableTable() == null;
        boolean ln = ms[j].getLineNumberTable() == null;
        if (lv) {
            mg.removeLocalVariables();
        }
        if (ln) {
            mg.removeLineNumbers();
        }
        mg.stripAttributes(skipDebug);
        InstructionList il = mg.getInstructionList();
        if (il != null) {
            InstructionHandle ih = il.getStart();
            while (ih != null) {
                ih = ih.getNext();
            }
            if (compute) {
                mg.setMaxStack();
                mg.setMaxLocals();
            }
        }
        cg.replaceMethod(ms[j], mg.getMethod());
    }
    return cg.getJavaClreplaced().getBytes();
}

19 View Complete Implementation : ElementValueGenTestCase.java
Copyright Apache License 2.0
Author : apache
public void testCreateShortElementValue() throws Exception {
    final ClreplacedGen cg = createClreplacedGen("HelloWorld");
    final ConstantPoolGen cp = cg.getConstantPool();
    final SimpleElementValueGen evg = new SimpleElementValueGen(ElementValueGen.PRIMITIVE_SHORT, cp, (short) 42);
    // Creation of an element like that should leave a new entry in the
    // cpool
    final int idx = cp.lookupInteger(42);
    replacedertTrue("Should have the same index in the constantpool but " + evg.getIndex() + "!=" + idx, evg.getIndex() == idx);
    checkSerialize(evg, cp);
}

19 View Complete Implementation : ElementValueGenTestCase.java
Copyright Apache License 2.0
Author : apache
// //
// Create string element values
public void testCreateStringElementValue() throws Exception {
    // Create HelloWorld
    final ClreplacedGen cg = createClreplacedGen("HelloWorld");
    final ConstantPoolGen cp = cg.getConstantPool();
    final SimpleElementValueGen evg = new SimpleElementValueGen(ElementValueGen.STRING, cp, "hello");
    // Creation of an element like that should leave a new entry in the
    // cpool
    replacedertTrue("Should have the same index in the constantpool but " + evg.getIndex() + "!=" + cp.lookupUtf8("hello"), evg.getIndex() == cp.lookupUtf8("hello"));
    checkSerialize(evg, cp);
}

19 View Complete Implementation : ElementValueGenTestCase.java
Copyright Apache License 2.0
Author : apache
public void testCreateLongElementValue() throws Exception {
    final ClreplacedGen cg = createClreplacedGen("HelloWorld");
    final ConstantPoolGen cp = cg.getConstantPool();
    final SimpleElementValueGen evg = new SimpleElementValueGen(ElementValueGen.PRIMITIVE_LONG, cp, 3334455L);
    // Creation of an element like that should leave a new entry in the
    // cpool
    final int idx = cp.lookupLong(3334455L);
    replacedertTrue("Should have the same index in the constantpool but " + evg.getIndex() + "!=" + idx, evg.getIndex() == idx);
    checkSerialize(evg, cp);
}

19 View Complete Implementation : ClassDumper.java
Copyright Apache License 2.0
Author : GoogleCloudPlatform
/**
 * Returns true if the clreplaced symbol reference is unused in the source clreplaced file. It checks
 * following places for the usage in the source clreplaced:
 *
 * <ul>
 *   <li>Superclreplaced and interfaces
 *   <li>Type signatures of fields and methods
 *   <li>Constant pool entries that refer to a CONSTANT_Clreplaced_info structure
 *   <li>Java Virtual Machine instructions that takes a symbolic reference to a clreplaced
 *   <li>The exception table and exception handlers of methods
 * </ul>
 *
 * @see <a href="https://docs.oracle.com/javase/specs/jvms/se8/html/jvms-4.html#jvms-4.4.2">Java
 *     Virtual Machine Specification: The CONSTANT_Fieldref_info, CONSTANT_Methodref_info, and
 *     CONSTANT_InterfaceMethodref_info Structures</a>
 * @see <a href="https://docs.oracle.com/javase/specs/jvms/se8/html/jvms-6.html#jvms-6.5">Java
 *     Virtual Machine Specification: Instructions</a>
 * @see <a href="https://docs.oracle.com/javase/specs/jvms/se8/html/jvms-2.html#jvms-2.10">Java
 *     Virtual Machine Specification: Exceptions</a>
 */
boolean isUnusedClreplacedSymbolReference(String sourceClreplacedName, ClreplacedSymbol clreplacedSymbol) {
    if (clreplacedSymbol instanceof SuperClreplacedSymbol) {
        // The target clreplaced is used in clreplaced inheritance
        return false;
    }
    String targetClreplacedName = clreplacedSymbol.getClreplacedBinaryName();
    try {
        JavaClreplaced sourceJavaClreplaced = loadJavaClreplaced(sourceClreplacedName);
        for (String interfaceName : sourceJavaClreplaced.getInterfaceNames()) {
            if (interfaceName.equals(targetClreplacedName)) {
                // The target clreplaced is used in interfaces
                return false;
            }
        }
        ImmutableSet<Integer> targetConstantPoolIndices = constantPoolIndexForClreplaced(sourceJavaClreplaced, targetClreplacedName);
        Verify.verify(!targetConstantPoolIndices.isEmpty(), "When checking a clreplaced reference from %s to %s, the reference to the target clreplaced is no" + // This should not happen
        " longer found in the source clreplaced's constant pool.", sourceJavaClreplaced.getClreplacedName(), targetClreplacedName);
        ConstantPool sourceConstantPool = sourceJavaClreplaced.getConstantPool();
        Constant[] constantPoolEntries = sourceConstantPool.getConstantPool();
        for (Constant constant : constantPoolEntries) {
            if (constant == null) {
                continue;
            }
            switch(constant.getTag()) {
                case Const.CONSTANT_Methodref:
                case Const.CONSTANT_InterfaceMethodref:
                case Const.CONSTANT_Fieldref:
                    ConstantCP constantCp = (ConstantCP) constant;
                    int clreplacedIndex = constantCp.getClreplacedIndex();
                    if (targetConstantPoolIndices.contains(clreplacedIndex)) {
                        // The clreplaced reference is used in another constant pool
                        return false;
                    }
                    break;
            }
        }
        for (Field field : sourceJavaClreplaced.getFields()) {
            // Type.toString returns binary name (for example, io.grpc.MethodDescriptor)
            String fieldTypeSignature = field.getType().toString();
            if (targetClreplacedName.equals(fieldTypeSignature)) {
                return false;
            }
        }
        ClreplacedGen clreplacedGen = new ClreplacedGen(sourceJavaClreplaced);
        for (Method method : sourceJavaClreplaced.getMethods()) {
            if (targetClreplacedName.equals(method.getReturnType().toString())) {
                return false;
            }
            for (Type argumentType : method.getArgumentTypes()) {
                String argumentTypeSignature = argumentType.toString();
                if (targetClreplacedName.equals(argumentTypeSignature)) {
                    return false;
                }
            }
            MethodGen methodGen = new MethodGen(method, sourceClreplacedName, clreplacedGen.getConstantPool());
            InstructionList instructionList = methodGen.getInstructionList();
            if (instructionList != null) {
                for (InstructionHandle instructionHandle : instructionList) {
                    Instruction instruction = instructionHandle.getInstruction();
                    if (instruction instanceof CPInstruction) {
                        // Checking JVM instructions that take a symbolic reference to a clreplaced in
                        // JVM Instruction Set
                        // https://docs.oracle.com/javase/specs/jvms/se8/html/jvms-6.html#jvms-6.5
                        int clreplacedIndex = ((CPInstruction) instruction).getIndex();
                        if (targetConstantPoolIndices.contains(clreplacedIndex)) {
                            // The target clreplaced is used in a JVM instruction (including `new`).
                            return false;
                        }
                    }
                }
            }
            // Exception table
            ExceptionTable exceptionTable = method.getExceptionTable();
            if (exceptionTable != null) {
                int[] exceptionIndexTable = exceptionTable.getExceptionIndexTable();
                for (int exceptionIndexTableEntry : exceptionIndexTable) {
                    if (targetConstantPoolIndices.contains(exceptionIndexTableEntry)) {
                        // The target clreplaced is used in throws clause
                        return false;
                    }
                }
            }
            // Exception handlers
            CodeExceptionGen[] exceptionHandlers = methodGen.getExceptionHandlers();
            for (CodeExceptionGen codeExceptionGen : exceptionHandlers) {
                ObjectType catchType = codeExceptionGen.getCatchType();
                if (catchType == null) {
                    continue;
                }
                String caughtClreplacedName = catchType.getClreplacedName();
                if (caughtClreplacedName != null && caughtClreplacedName.equals(targetClreplacedName)) {
                    // The target clreplaced is used in catch clause
                    return false;
                }
            }
        }
    } catch (ClreplacedNotFoundException ex) {
        // Because the reference in the argument was extracted from the source clreplaced file,
        // the source clreplaced should be found.
        throw new ClreplacedFormatException("The source clreplaced in the reference is no longer available in the clreplaced path", ex);
    }
    // The target clreplaced is unused
    return true;
}

18 View Complete Implementation : TestArrayAccess03Creator.java
Copyright Apache License 2.0
Author : apache
public clreplaced TestArrayAccess03Creator extends TestCreator {

    private final InstructionFactory _factory;

    private final ConstantPoolGen _cp;

    private final ClreplacedGen _cg;

    public TestArrayAccess03Creator() {
        _cg = new ClreplacedGen(TEST_PACKAGE + ".TestArrayAccess03", "java.lang.Object", "TestArrayAccess03.java", Const.ACC_PUBLIC | Const.ACC_SUPER, new String[] {});
        _cp = _cg.getConstantPool();
        _factory = new InstructionFactory(_cg, _cp);
    }

    @Override
    public void create(final OutputStream out) throws IOException {
        createMethod_0();
        createMethod_1();
        _cg.getJavaClreplaced().dump(out);
    }

    private void createMethod_0() {
        final InstructionList il = new InstructionList();
        final MethodGen method = new MethodGen(Const.ACC_PUBLIC, Type.VOID, Type.NO_ARGS, new String[] {}, "<init>", TEST_PACKAGE + ".TestArrayAccess03", il, _cp);
        final InstructionHandle ih_0 = il.append(InstructionFactory.createLoad(Type.OBJECT, 0));
        // TODO why is this not used
        replacedert.replacedertNotNull(ih_0);
        il.append(_factory.createInvoke("java.lang.Object", "<init>", Type.VOID, Type.NO_ARGS, Const.INVOKESPECIAL));
        final InstructionHandle ih_4 = il.append(InstructionFactory.createReturn(Type.VOID));
        // TODO why is this not used
        replacedert.replacedertNotNull(ih_4);
        method.setMaxStack();
        method.setMaxLocals();
        _cg.addMethod(method.getMethod());
        il.dispose();
    }

    private void createMethod_1() {
        final InstructionList il = new InstructionList();
        final MethodGen method = new MethodGen(Const.ACC_PUBLIC | Const.ACC_STATIC, Type.VOID, new Type[] { Type.OBJECT }, new String[] { "arg0" }, "test", TEST_PACKAGE + ".TestArrayAccess03", il, _cp);
        final InstructionHandle ih_0 = il.append(new PUSH(_cp, 1));
        // TODO why is this not used
        replacedert.replacedertNotNull(ih_0);
        il.append(_factory.createNewArray(new ObjectType(TEST_PACKAGE + ".TestArrayAccess03"), (short) 1));
        il.append(InstructionFactory.createStore(Type.OBJECT, 1));
        final InstructionHandle ih_5 = il.append(InstructionFactory.createLoad(Type.OBJECT, 0));
        // TODO why is this not used
        replacedert.replacedertNotNull(ih_5);
        il.append(new PUSH(_cp, 0));
        il.append(_factory.createNew(TEST_PACKAGE + ".TestArrayAccess03"));
        il.append(InstructionConst.DUP);
        il.append(_factory.createInvoke(TEST_PACKAGE + ".TestArrayAccess03", "<init>", Type.VOID, Type.NO_ARGS, Const.INVOKESPECIAL));
        il.append(InstructionConst.AASTORE);
        final InstructionHandle ih_15 = il.append(InstructionFactory.createReturn(Type.VOID));
        // TODO why is this not used
        replacedert.replacedertNotNull(ih_15);
        method.setMaxStack();
        method.setMaxLocals();
        _cg.addMethod(method.getMethod());
        il.dispose();
    }
}

18 View Complete Implementation : TestArrayAccess04Creator.java
Copyright Apache License 2.0
Author : apache
public clreplaced TestArrayAccess04Creator extends TestCreator {

    private final InstructionFactory _factory;

    private final ConstantPoolGen _cp;

    private final ClreplacedGen _cg;

    public TestArrayAccess04Creator() {
        _cg = new ClreplacedGen(TEST_PACKAGE + ".TestArrayAccess04", "java.lang.Object", "TestArrayAccess04.java", Const.ACC_PUBLIC | Const.ACC_SUPER, new String[] {});
        _cp = _cg.getConstantPool();
        _factory = new InstructionFactory(_cg, _cp);
    }

    @Override
    public void create(final OutputStream out) throws IOException {
        createMethod_0();
        createMethod_1();
        _cg.getJavaClreplaced().dump(out);
    }

    private void createMethod_0() {
        final InstructionList il = new InstructionList();
        final MethodGen method = new MethodGen(Const.ACC_PUBLIC, Type.VOID, Type.NO_ARGS, new String[] {}, "<init>", TEST_PACKAGE + ".TestArrayAccess04", il, _cp);
        final InstructionHandle ih_0 = il.append(InstructionFactory.createLoad(Type.OBJECT, 0));
        // TODO why is this not used
        replacedert.replacedertNotNull(ih_0);
        il.append(_factory.createInvoke("java.lang.Object", "<init>", Type.VOID, Type.NO_ARGS, Const.INVOKESPECIAL));
        final InstructionHandle ih_4 = il.append(InstructionFactory.createReturn(Type.VOID));
        // TODO why is this not used
        replacedert.replacedertNotNull(ih_4);
        method.setMaxStack();
        method.setMaxLocals();
        _cg.addMethod(method.getMethod());
        il.dispose();
    }

    private void createMethod_1() {
        final InstructionList il = new InstructionList();
        final MethodGen method = new MethodGen(Const.ACC_PUBLIC | Const.ACC_STATIC, Type.VOID, new Type[] { Type.OBJECT }, new String[] { "arg0" }, "test", TEST_PACKAGE + ".TestArrayAccess04", il, _cp);
        final InstructionHandle ih_0 = il.append(new PUSH(_cp, 1));
        // TODO why is this not used
        replacedert.replacedertNotNull(ih_0);
        il.append(_factory.createNewArray(Type.OBJECT, (short) 1));
        il.append(InstructionFactory.createStore(Type.OBJECT, 1));
        final InstructionHandle ih_5 = il.append(new PUSH(_cp, 1));
        // TODO why is this not used
        replacedert.replacedertNotNull(ih_5);
        il.append(InstructionFactory.createStore(Type.INT, 2));
        final InstructionHandle ih_7 = il.append(InstructionFactory.createLoad(Type.OBJECT, 1));
        // TODO why is this not used
        replacedert.replacedertNotNull(ih_7);
        il.append(new PUSH(_cp, 0));
        il.append(InstructionFactory.createLoad(Type.INT, 2));
        il.append(InstructionConst.AASTORE);
        final InstructionHandle ih_11 = il.append(InstructionFactory.createReturn(Type.VOID));
        // TODO why is this not used
        replacedert.replacedertNotNull(ih_11);
        method.setMaxStack();
        method.setMaxLocals();
        _cg.addMethod(method.getMethod());
        il.dispose();
    }
}

18 View Complete Implementation : TestReturn01Creator.java
Copyright Apache License 2.0
Author : apache
public clreplaced TestReturn01Creator extends TestCreator {

    private final InstructionFactory _factory;

    private final ConstantPoolGen _cp;

    private final ClreplacedGen _cg;

    public TestReturn01Creator() {
        _cg = new ClreplacedGen(TEST_PACKAGE + ".TestReturn01", "java.lang.Object", "TestReturn01.java", Const.ACC_PUBLIC | Const.ACC_SUPER, new String[] {});
        _cp = _cg.getConstantPool();
        _factory = new InstructionFactory(_cg, _cp);
    }

    @Override
    public void create(final OutputStream out) throws IOException {
        createMethod_0();
        createMethod_1();
        _cg.getJavaClreplaced().dump(out);
    }

    private void createMethod_0() {
        final InstructionList il = new InstructionList();
        final MethodGen method = new MethodGen(Const.ACC_PUBLIC, Type.VOID, Type.NO_ARGS, new String[] {}, "<init>", TEST_PACKAGE + ".TestReturn01", il, _cp);
        final InstructionHandle ih_0 = il.append(InstructionFactory.createLoad(Type.OBJECT, 0));
        // TODO why is this not used
        replacedert.replacedertNotNull(ih_0);
        il.append(_factory.createInvoke("java.lang.Object", "<init>", Type.VOID, Type.NO_ARGS, Const.INVOKESPECIAL));
        final InstructionHandle ih_4 = il.append(InstructionFactory.createReturn(Type.VOID));
        // TODO why is this not used
        replacedert.replacedertNotNull(ih_4);
        method.setMaxStack();
        method.setMaxLocals();
        _cg.addMethod(method.getMethod());
        il.dispose();
    }

    private void createMethod_1() {
        final InstructionList il = new InstructionList();
        final MethodGen method = new MethodGen(Const.ACC_PUBLIC | Const.ACC_STATIC, Type.VOID, Type.NO_ARGS, new String[] {}, "foo", TEST_PACKAGE + ".TestReturn01", il, _cp);
        final InstructionHandle ih_0 = il.append(_factory.createNew("java.lang.Object"));
        // TODO why is this not used
        replacedert.replacedertNotNull(ih_0);
        il.append(InstructionConst.DUP);
        il.append(_factory.createInvoke("java.lang.Object", "<init>", Type.VOID, Type.NO_ARGS, Const.INVOKESPECIAL));
        il.append(InstructionConst.NOP);
        final InstructionHandle ih_8 = il.append(InstructionFactory.createReturn(Type.OBJECT));
        // TODO why is this not used
        replacedert.replacedertNotNull(ih_8);
        method.setMaxStack();
        method.setMaxLocals();
        _cg.addMethod(method.getMethod());
        il.dispose();
    }
}

18 View Complete Implementation : TestArrayAccess02Creator.java
Copyright Apache License 2.0
Author : apache
public clreplaced TestArrayAccess02Creator extends TestCreator {

    private final InstructionFactory _factory;

    private final ConstantPoolGen _cp;

    private final ClreplacedGen _cg;

    public TestArrayAccess02Creator() {
        _cg = new ClreplacedGen(TEST_PACKAGE + ".TestArrayAccess02", "java.lang.Object", "TestArrayAccess02.java", Const.ACC_PUBLIC | Const.ACC_SUPER, new String[] {});
        _cp = _cg.getConstantPool();
        _factory = new InstructionFactory(_cg, _cp);
    }

    @Override
    public void create(final OutputStream out) throws IOException {
        createMethod_0();
        createMethod_1();
        _cg.getJavaClreplaced().dump(out);
    }

    private void createMethod_0() {
        final InstructionList il = new InstructionList();
        final MethodGen method = new MethodGen(Const.ACC_PUBLIC, Type.VOID, Type.NO_ARGS, new String[] {}, "<init>", TEST_PACKAGE + ".TestArrayAccess02", il, _cp);
        final InstructionHandle ih_0 = il.append(InstructionFactory.createLoad(Type.OBJECT, 0));
        // TODO why is this not used
        replacedert.replacedertNotNull(ih_0);
        il.append(_factory.createInvoke("java.lang.Object", "<init>", Type.VOID, Type.NO_ARGS, Const.INVOKESPECIAL));
        final InstructionHandle ih_4 = il.append(InstructionFactory.createReturn(Type.VOID));
        // TODO why is this not used
        replacedert.replacedertNotNull(ih_4);
        method.setMaxStack();
        method.setMaxLocals();
        _cg.addMethod(method.getMethod());
        il.dispose();
    }

    private void createMethod_1() {
        final InstructionList il = new InstructionList();
        final MethodGen method = new MethodGen(Const.ACC_PUBLIC | Const.ACC_STATIC, Type.VOID, Type.NO_ARGS, new String[] {}, "test", TEST_PACKAGE + ".TestArrayAccess02", il, _cp);
        final InstructionHandle ih_0 = il.append(new PUSH(_cp, 1));
        // TODO why is this not used
        replacedert.replacedertNotNull(ih_0);
        il.append(_factory.createNewArray(new ObjectType(TEST_PACKAGE + ".TestArrayAccess02"), (short) 1));
        il.append(InstructionFactory.createStore(Type.OBJECT, 0));
        final InstructionHandle ih_5 = il.append(new PUSH(_cp, 1));
        // TODO why is this not used
        replacedert.replacedertNotNull(ih_5);
        il.append(_factory.createNewArray(Type.STRING, (short) 1));
        il.append(InstructionFactory.createStore(Type.OBJECT, 1));
        final InstructionHandle ih_10 = il.append(InstructionFactory.createLoad(Type.OBJECT, 1));
        // TODO why is this not used
        replacedert.replacedertNotNull(ih_10);
        il.append(new PUSH(_cp, 0));
        il.append(_factory.createNew(TEST_PACKAGE + ".TestArrayAccess02"));
        il.append(InstructionConst.DUP);
        il.append(_factory.createInvoke(TEST_PACKAGE + ".TestArrayAccess02", "<init>", Type.VOID, Type.NO_ARGS, Const.INVOKESPECIAL));
        il.append(InstructionConst.AASTORE);
        final InstructionHandle ih_20 = il.append(InstructionFactory.createReturn(Type.VOID));
        // TODO why is this not used
        replacedert.replacedertNotNull(ih_20);
        method.setMaxStack();
        method.setMaxLocals();
        _cg.addMethod(method.getMethod());
        il.dispose();
    }
}

18 View Complete Implementation : ComplexObjectCreator.java
Copyright Apache License 2.0
Author : betfair
public clreplaced ComplexObjectCreator implements Constants {

    public final String objectType;

    private InstructionFactory _factory;

    private ConstantPoolGen _cp;

    private ClreplacedGen _cg;

    public ComplexObjectCreator(String objectType) {
        _cg = new ClreplacedGen(objectType, "java.lang.Object", "ComplexObject.java", ACC_PUBLIC | ACC_SUPER, new String[] { "com.betfair.cougar.api.Result" });
        _cp = _cg.getConstantPool();
        _factory = new InstructionFactory(_cg, _cp);
        this.objectType = objectType;
    }

    public void create(OutputStream out, Pair<String, String>[] fieldDefs) throws IOException {
        createFields(fieldDefs);
        createMethod_0();
        _cg.getJavaClreplaced().dump(out);
    }

    private void createFields(Pair<String, String>[] fieldDefs) {
        FieldGen field;
        for (Pair<String, String> aField : fieldDefs) {
            field = new FieldGen(ACC_PUBLIC, new ObjectType(aField.first), aField.second, _cp);
            _cg.addField(field.getField());
        }
    }

    private void createMethod_0() {
        InstructionList il = new InstructionList();
        MethodGen method = new MethodGen(ACC_PUBLIC, Type.VOID, Type.NO_ARGS, new String[] {}, "<init>", objectType, il, _cp);
        InstructionHandle ih_0 = il.append(_factory.createLoad(Type.OBJECT, 0));
        il.append(_factory.createInvoke("java.lang.Object", "<init>", Type.VOID, Type.NO_ARGS, Constants.INVOKESPECIAL));
        InstructionHandle ih_4 = il.append(_factory.createReturn(Type.VOID));
        method.setMaxStack();
        method.setMaxLocals();
        _cg.addMethod(method.getMethod());
        il.dispose();
    }
}

18 View Complete Implementation : BCELifyPane.java
Copyright GNU General Public License v3.0
Author : contra
private void updateEditPanes() {
    internalFrame = (BrowserInternalFrame) services;
    ClreplacedFile clreplacedFile = services.getClreplacedFile();
    MethodInfo[] methods = clreplacedFile.getMethods();
    String contents;
    try {
        JavaClreplaced javaClreplaced = new ClreplacedParser(internalFrame.getFileName()).parse();
        ClreplacedGen cg = new ClreplacedGen(javaClreplaced);
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        BCELifier v = new BCELifier(javaClreplaced, out);
        v.start();
        contents = out.toString();
    } catch (Exception e) {
        contents = "Failed to load/bcelify file";
    }
    for (int i = 0; i < methods.length; i++) {
        String methodIndex = Integer.toString(i);
        addEditPane(contents, methodIndex);
    }
}

18 View Complete Implementation : JPSXClassLoader.java
Copyright GNU General Public License v3.0
Author : kilograham
public static MethodGen emptyMethod(ClreplacedGen cgen, Method m) {
    MethodGen mg = new MethodGen(m, cgen.getClreplacedName(), cgen.getConstantPool());
    return new MethodGen(mg.getAccessFlags(), mg.getReturnType(), mg.getArgumentTypes(), mg.getArgumentNames(), mg.getName(), mg.getClreplacedName(), new InstructionList(), mg.getConstantPool());
}

18 View Complete Implementation : TestReturn03Creator.java
Copyright Apache License 2.0
Author : apache
public clreplaced TestReturn03Creator extends TestCreator {

    private final InstructionFactory _factory;

    private final ConstantPoolGen _cp;

    private final ClreplacedGen _cg;

    public TestReturn03Creator() {
        _cg = new ClreplacedGen(TEST_PACKAGE + ".TestReturn03", "java.lang.Object", "TestReturn03.java", Const.ACC_PUBLIC | Const.ACC_SUPER, new String[] {});
        _cp = _cg.getConstantPool();
        _factory = new InstructionFactory(_cg, _cp);
    }

    @Override
    public void create(final OutputStream out) throws IOException {
        createMethod_0();
        createMethod_1();
        _cg.getJavaClreplaced().dump(out);
    }

    private void createMethod_0() {
        final InstructionList il = new InstructionList();
        final MethodGen method = new MethodGen(Const.ACC_PUBLIC, Type.VOID, Type.NO_ARGS, new String[] {}, "<init>", TEST_PACKAGE + ".TestReturn03", il, _cp);
        final InstructionHandle ih_0 = il.append(InstructionFactory.createLoad(Type.OBJECT, 0));
        // TODO why is this not used
        replacedert.replacedertNotNull(ih_0);
        il.append(_factory.createInvoke("java.lang.Object", "<init>", Type.VOID, Type.NO_ARGS, Const.INVOKESPECIAL));
        final InstructionHandle ih_4 = il.append(InstructionFactory.createReturn(Type.VOID));
        // TODO why is this not used
        replacedert.replacedertNotNull(ih_4);
        method.setMaxStack();
        method.setMaxLocals();
        _cg.addMethod(method.getMethod());
        il.dispose();
    }

    private void createMethod_1() {
        final InstructionList il = new InstructionList();
        final MethodGen method = new MethodGen(Const.ACC_PUBLIC | Const.ACC_STATIC, Type.INT, Type.NO_ARGS, new String[] {}, "test3", TEST_PACKAGE + ".TestReturn03", il, _cp);
        final InstructionHandle ih_0 = il.append(InstructionConst.ACONST_NULL);
        // TODO why is this not used
        replacedert.replacedertNotNull(ih_0);
        il.append(InstructionFactory.createReturn(Type.OBJECT));
        method.setMaxStack();
        method.setMaxLocals();
        _cg.addMethod(method.getMethod());
        il.dispose();
    }
}

18 View Complete Implementation : OverloadDispatcherGenerator.java
Copyright Apache License 2.0
Author : s4
public Clreplaced<Object> generate() {
    Random rand = new Random(System.currentTimeMillis());
    String dispatcherClreplacedName = "OverloadDispatcher" + (Math.abs(rand.nextInt() % 3256));
    String interfaceName = "org.apache.s4.processor.OverloadDispatcher";
    if (forSlot) {
        interfaceName = "org.apache.s4.processor.OverloadDispatcherSlot";
    }
    ClreplacedGen cg = new ClreplacedGen(dispatcherClreplacedName, "java.lang.Object", dispatcherClreplacedName + ".java", Constants.ACC_PUBLIC | Constants.ACC_SUPER, new String[] { interfaceName });
    ConstantPoolGen cp = cg.getConstantPool();
    InstructionFactory instFactory = new InstructionFactory(cg, cp);
    InstructionList il = new InstructionList();
    // build constructor method for new clreplaced
    MethodGen constructor = new MethodGen(Constants.ACC_PUBLIC, Type.VOID, Type.NO_ARGS, new String[] {}, "<init>", dispatcherClreplacedName, il, cp);
    il.append(InstructionFactory.createLoad(Type.OBJECT, 0));
    il.append(instFactory.createInvoke("java.lang.Object", "<init>", Type.VOID, Type.NO_ARGS, Constants.INVOKESPECIAL));
    il.append(InstructionFactory.createReturn(Type.VOID));
    constructor.setMaxStack();
    constructor.setMaxLocals();
    cg.addMethod(constructor.getMethod());
    il.dispose();
    // build dispatch method
    il = new InstructionList();
    Type[] dispatchArgumentTypes = null;
    String[] dispatchArgumentNames = null;
    int postArgumentVariableSlot = 3;
    if (forSlot) {
        dispatchArgumentTypes = new Type[] { ObjectType.OBJECT, ObjectType.OBJECT, ObjectType.LONG, abstractWindowingPEType };
        dispatchArgumentNames = new String[] { "slot", "event", "slotTime", "pe" };
        postArgumentVariableSlot = 6;
    } else {
        dispatchArgumentTypes = new Type[] { ObjectType.OBJECT, ObjectType.OBJECT };
        dispatchArgumentNames = new String[] { "pe", "event" };
    }
    MethodGen method = new MethodGen(Constants.ACC_PUBLIC, Type.VOID, dispatchArgumentTypes, dispatchArgumentNames, "dispatch", dispatcherClreplacedName, il, cp);
    List<InstructionHandle> targetInstructions = new ArrayList<InstructionHandle>();
    List<BranchInstruction> branchInstructions = new ArrayList<BranchInstruction>();
    List<BranchInstruction> gotoInstructions = new ArrayList<BranchInstruction>();
    ObjectType peType = new ObjectType(targetClreplaced.getName());
    il.append(InstructionFactory.createLoad(Type.OBJECT, 1));
    il.append(instFactory.createCheckCast(peType));
    il.append(InstructionFactory.createStore(peType, postArgumentVariableSlot));
    for (int i = 0; i < hierarchies.size(); i++) {
        Hierarchy hierarchy = hierarchies.get(i);
        ObjectType hierarchyTop = new ObjectType(hierarchy.getTop().getName());
        InstructionHandle ih = il.append(InstructionFactory.createLoad(Type.OBJECT, 2));
        if (i > 0) {
            targetInstructions.add(ih);
        }
        il.append(new INSTANCEOF(cp.addClreplaced(hierarchyTop)));
        BranchInstruction bi = InstructionFactory.createBranchInstruction(Constants.IFEQ, null);
        il.append(bi);
        branchInstructions.add(bi);
        il.append(InstructionFactory.createLoad(peType, postArgumentVariableSlot));
        il.append(InstructionFactory.createLoad(hierarchyTop, 2));
        il.append(instFactory.createCheckCast(hierarchyTop));
        if (forSlot) {
            il.append(InstructionFactory.createLoad(ObjectType.LONG, 3));
            il.append(InstructionFactory.createLoad(abstractWindowingPEType, 5));
        }
        Type[] argumentTypes = null;
        if (forSlot) {
            argumentTypes = new Type[] { hierarchyTop, ObjectType.LONG, abstractWindowingPEType };
        } else {
            argumentTypes = new Type[] { hierarchyTop };
        }
        il.append(instFactory.createInvoke(targetClreplaced.getName(), "processEvent", Type.VOID, argumentTypes, Constants.INVOKEVIRTUAL));
        // no branch needed for last check
        if (i < (hierarchies.size() - 1)) {
            bi = InstructionFactory.createBranchInstruction(Constants.GOTO, null);
            il.append(bi);
            gotoInstructions.add(bi);
        }
    }
    InstructionHandle returnInstruction = il.append(InstructionFactory.createReturn(Type.VOID));
    for (int i = 0; i < targetInstructions.size(); i++) {
        branchInstructions.get(i).setTarget(targetInstructions.get(i));
    }
    branchInstructions.get(branchInstructions.size() - 1).setTarget(returnInstruction);
    for (BranchInstruction gotoInstruction : gotoInstructions) {
        gotoInstruction.setTarget(returnInstruction);
    }
    method.setMaxStack();
    method.setMaxLocals();
    cg.addMethod(method.getMethod());
    il.dispose();
    JavaClreplaced jc = cg.getJavaClreplaced();
    OverloadDispatcherClreplacedLoader cl = new OverloadDispatcherClreplacedLoader();
    // debug
    if (clreplacedDumpFile != null) {
        FileOutputStream fos = null;
        try {
            fos = new FileOutputStream(clreplacedDumpFile);
            fos.write(jc.getBytes());
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (fos != null)
                try {
                    fos.close();
                } catch (Exception e) {
                }
        }
    }
    return cl.loadClreplacedFromBytes(dispatcherClreplacedName, jc.getBytes());
}

18 View Complete Implementation : ClonerGenerator.java
Copyright Apache License 2.0
Author : s4
public Clreplaced generate(Clreplaced clazz) {
    String clreplacedName = clazz.getName();
    Random rand = new Random(System.currentTimeMillis());
    String clonerClreplacedname = "Cloner" + (Math.abs(rand.nextInt() % 3256));
    ClreplacedGen cg = new ClreplacedGen(clonerClreplacedname, "java.lang.Object", clonerClreplacedname + ".java", Constants.ACC_PUBLIC | Constants.ACC_SUPER, new String[] { "org.apache.s4.util.Cloner" });
    ConstantPoolGen cp = cg.getConstantPool();
    InstructionFactory instFactory = new InstructionFactory(cg, cp);
    InstructionList il = new InstructionList();
    // build constructor method for new clreplaced
    MethodGen constructor = new MethodGen(Constants.ACC_PUBLIC, Type.VOID, Type.NO_ARGS, new String[] {}, "<init>", clonerClreplacedname, il, cp);
    il.append(InstructionFactory.createLoad(Type.OBJECT, 0));
    il.append(instFactory.createInvoke("java.lang.Object", "<init>", Type.VOID, Type.NO_ARGS, Constants.INVOKESPECIAL));
    il.append(InstructionFactory.createReturn(Type.VOID));
    constructor.setMaxStack();
    constructor.setMaxLocals();
    cg.addMethod(constructor.getMethod());
    il.dispose();
    // build clone method
    il = new InstructionList();
    MethodGen method = new MethodGen(Constants.ACC_PUBLIC, Type.OBJECT, new Type[] { Type.OBJECT }, new String[] { "arg0" }, "clone", clonerClreplacedname, il, cp);
    il.append(InstructionConstants.ACONST_NULL);
    il.append(InstructionFactory.createStore(Type.OBJECT, 2));
    il.append(InstructionFactory.createLoad(Type.OBJECT, 1));
    il.append(new INSTANCEOF(cp.addClreplaced(new ObjectType(clreplacedName))));
    BranchInstruction ifeq_6 = InstructionFactory.createBranchInstruction(Constants.IFEQ, null);
    il.append(ifeq_6);
    il.append(InstructionFactory.createLoad(Type.OBJECT, 1));
    il.append(instFactory.createCheckCast(new ObjectType(clreplacedName)));
    il.append(InstructionFactory.createStore(Type.OBJECT, 2));
    InstructionHandle ih_14 = il.append(InstructionFactory.createLoad(Type.OBJECT, 2));
    il.append(new INSTANCEOF(cp.addClreplaced(new ObjectType("java.lang.Cloneable"))));
    BranchInstruction ifne_18 = InstructionFactory.createBranchInstruction(Constants.IFNE, null);
    il.append(ifne_18);
    il.append(instFactory.createFieldAccess("java.lang.System", "out", new ObjectType("java.io.PrintStream"), Constants.GETSTATIC));
    il.append(new PUSH(cp, "Not cloneable!"));
    il.append(instFactory.createInvoke("java.io.PrintStream", "println", Type.VOID, new Type[] { Type.STRING }, Constants.INVOKEVIRTUAL));
    il.append(InstructionConstants.ACONST_NULL);
    il.append(InstructionFactory.createReturn(Type.OBJECT));
    InstructionHandle ih_31 = il.append(InstructionFactory.createLoad(Type.OBJECT, 2));
    il.append(instFactory.createInvoke(clreplacedName, "clone", Type.OBJECT, Type.NO_ARGS, Constants.INVOKEVIRTUAL));
    il.append(InstructionFactory.createReturn(Type.OBJECT));
    ifeq_6.setTarget(ih_14);
    ifne_18.setTarget(ih_31);
    method.setMaxStack();
    method.setMaxLocals();
    cg.addMethod(method.getMethod());
    il.dispose();
    JavaClreplaced jc = cg.getJavaClreplaced();
    ClonerClreplacedLoader cl = new ClonerClreplacedLoader();
    return cl.loadClreplacedFromBytes(clonerClreplacedname, jc.getBytes());
}

18 View Complete Implementation : ConstantPoolGenFactory.java
Copyright GNU Lesser General Public License v2.1
Author : spotbugs
/*
     * (non-Javadoc)
     *
     * @see
     * edu.umd.cs.findbugs.clreplacedfile.IreplacedysisEngine#replacedyze(edu.umd.cs.findbugs
     * .clreplacedfile.IreplacedysisCache, java.lang.Object)
     */
@Override
public ConstantPoolGen replacedyze(IreplacedysisCache replacedysisCache, ClreplacedDescriptor descriptor) throws CheckedreplacedysisException {
    ClreplacedGen clreplacedGen = new ClreplacedGen(replacedysisCache.getClreplacedreplacedysis(JavaClreplaced.clreplaced, descriptor));
    return clreplacedGen.getConstantPool();
}

18 View Complete Implementation : ThreadLocalGenerator.java
Copyright GNU General Public License v2.0
Author : velo
private static void instrumentThreadLocalToolkit(File mxmlcJar, File destination) throws IOException {
    String clreplacedfile = THREAD_LOCAL_TOOLKIT.replace('.', '/') + ".clreplaced";
    JavaClreplaced jc;
    ZipFile jar = null;
    InputStream source = null;
    try {
        jar = new ZipFile(mxmlcJar);
        ZipEntry entry = jar.getEntry(clreplacedfile);
        source = jar.getInputStream(entry);
        ClreplacedParser p = new ClreplacedParser(source, THREAD_LOCAL_TOOLKIT);
        jc = p.parse();
    } finally {
        IOUtil.close(source);
        if (jar != null) {
            jar.close();
        }
    }
    ClreplacedGen cg = new ClreplacedGen(jc);
    ConstantPoolGen cp = cg.getConstantPool();
    InstructionFactory _factory = new InstructionFactory(cg, cp);
    Method[] methods = cg.getMethods();
    for (Method method : methods) {
        Type[] types = method.getArgumentTypes();
        if (method.getName().equals("setLogger") && types.length == 1 && types[0].equals(Type.getType("Lflex2/compiler/Logger;"))) {
            InstructionList il = new InstructionList();
            MethodGen mg = new MethodGen(method.getAccessFlags(), method.getReturnType(), method.getArgumentTypes(), null, method.getName(), null, il, cp);
            il.append(InstructionFactory.createLoad(Type.OBJECT, 0));
            il.append(_factory.createInvoke(FLEXMOJOS_HELPER, "fixLogger", new ObjectType("flex2.compiler.Logger"), new Type[] { new ObjectType("flex2.compiler.Logger") }, Constants.INVOKESTATIC));
            il.append(InstructionFactory.createStore(Type.OBJECT, 0));
            il.append(_factory.createFieldAccess(THREAD_LOCAL_TOOLKIT, "logger", new ObjectType("java.lang.ThreadLocal"), Constants.GETSTATIC));
            il.append(InstructionFactory.createLoad(Type.OBJECT, 0));
            il.append(_factory.createInvoke("java.lang.ThreadLocal", "set", Type.VOID, new Type[] { Type.OBJECT }, Constants.INVOKEVIRTUAL));
            il.append(InstructionFactory.createLoad(Type.OBJECT, 0));
            BranchInstruction ifnull_13 = InstructionFactory.createBranchInstruction(Constants.IFNULL, null);
            il.append(ifnull_13);
            il.append(InstructionFactory.createLoad(Type.OBJECT, 0));
            il.append(_factory.createInvoke(THREAD_LOCAL_TOOLKIT, "getLocalizationManager", new ObjectType("flash.localization.LocalizationManager"), Type.NO_ARGS, Constants.INVOKESTATIC));
            il.append(_factory.createInvoke("flex2.compiler.Logger", "setLocalizationManager", Type.VOID, new Type[] { new ObjectType("flash.localization.LocalizationManager") }, Constants.INVOKEINTERFACE));
            InstructionHandle ih_25 = il.append(InstructionFactory.createReturn(Type.VOID));
            ifnull_13.setTarget(ih_25);
            mg.setMaxStack();
            mg.setMaxLocals();
            cg.removeMethod(method);
            cg.addMethod(mg.getMethod());
            il.dispose();
        } else if (method.getName().equals("setPathResolver") && types.length == 1 && types[0].equals(new ObjectType("flex2.compiler.common.PathResolver"))) {
            InstructionList il = new InstructionList();
            MethodGen mg = new MethodGen(method.getAccessFlags(), method.getReturnType(), method.getArgumentTypes(), null, method.getName(), null, il, cp);
            il.append(InstructionFactory.createLoad(Type.OBJECT, 0));
            il.append(_factory.createInvoke(FLEXMOJOS_HELPER, "fixPathResolver", new ObjectType("flex2.compiler.common.PathResolver"), new Type[] { new ObjectType("flex2.compiler.common.PathResolver") }, Constants.INVOKESTATIC));
            il.append(InstructionFactory.createStore(Type.OBJECT, 0));
            il.append(_factory.createFieldAccess(THREAD_LOCAL_TOOLKIT, "resolver", new ObjectType("java.lang.ThreadLocal"), Constants.GETSTATIC));
            il.append(InstructionFactory.createLoad(Type.OBJECT, 0));
            il.append(_factory.createInvoke("java.lang.ThreadLocal", "set", Type.VOID, new Type[] { Type.OBJECT }, Constants.INVOKEVIRTUAL));
            il.append(InstructionFactory.createReturn(Type.VOID));
            mg.setMaxStack();
            mg.setMaxLocals();
            cg.removeMethod(method);
            cg.addMethod(mg.getMethod());
            il.dispose();
        }
    }
    FieldGen replacedertor = new FieldGen(Constants.ACC_PUBLIC & Constants.ACC_STATIC, Type.STRING, "replacedertor", cp);
    cg.addField(replacedertor.getField());
    FileOutputStream output = null;
    try {
        File destFile = new File(destination, clreplacedfile);
        destFile.getParentFile().mkdirs();
        output = new FileOutputStream(destFile);
        cg.getJavaClreplaced().dump(output);
        output.flush();
    } finally {
        IOUtil.close(output);
    }
}

18 View Complete Implementation : HelloWorldBuilder.java
Copyright Apache License 2.0
Author : apache
public static void main(final String[] argv) {
    final ClreplacedGen cg = new ClreplacedGen("HelloWorld", "java.lang.Object", "<generated>", Const.ACC_PUBLIC | Const.ACC_SUPER, null);
    // cg creates constant pool
    final ConstantPoolGen cp = cg.getConstantPool();
    final InstructionList il = new InstructionList();
    final MethodGen mg = new MethodGen(Const.ACC_STATIC | // access flags
    Const.ACC_PUBLIC, // return type
    Type.VOID, new Type[] { // argument types
    new ArrayType(Type.STRING, 1) }, // arg names
    new String[] { "argv" }, // method, clreplaced
    "main", // method, clreplaced
    "HelloWorld", il, cp);
    final InstructionFactory factory = new InstructionFactory(cg);
    final ObjectType i_stream = new ObjectType("java.io.InputStream");
    final ObjectType p_stream = new ObjectType("java.io.PrintStream");
    // Create BufferedReader object and store it in local variable `in'.
    il.append(factory.createNew("java.io.BufferedReader"));
    // Use predefined constant, i.e. flyweight
    il.append(InstructionConst.DUP);
    il.append(factory.createNew("java.io.InputStreamReader"));
    il.append(InstructionConst.DUP);
    il.append(factory.createFieldAccess("java.lang.System", "in", i_stream, Const.GETSTATIC));
    // Call constructors, i.e. BufferedReader(InputStreamReader())
    il.append(factory.createInvoke("java.io.InputStreamReader", "<init>", Type.VOID, new Type[] { i_stream }, Const.INVOKESPECIAL));
    il.append(factory.createInvoke("java.io.BufferedReader", "<init>", Type.VOID, new Type[] { new ObjectType("java.io.Reader") }, Const.INVOKESPECIAL));
    // Create local variable `in'
    LocalVariableGen lg = mg.addLocalVariable("in", new ObjectType("java.io.BufferedReader"), null, null);
    final int in = lg.getIndex();
    // `i' valid from here
    lg.setStart(il.append(new ASTORE(in)));
    // Create local variable `name'
    lg = mg.addLocalVariable("name", Type.STRING, null, null);
    final int name = lg.getIndex();
    il.append(InstructionConst.ACONST_NULL);
    // `name' valid from here
    lg.setStart(il.append(new ASTORE(name)));
    // try { ...
    final InstructionHandle try_start = il.append(factory.createFieldAccess("java.lang.System", "out", p_stream, Const.GETSTATIC));
    il.append(new PUSH(cp, "Please enter your name> "));
    il.append(factory.createInvoke("java.io.PrintStream", "print", Type.VOID, new Type[] { Type.STRING }, Const.INVOKEVIRTUAL));
    il.append(new ALOAD(in));
    il.append(factory.createInvoke("java.io.BufferedReader", "readLine", Type.STRING, Type.NO_ARGS, Const.INVOKEVIRTUAL));
    il.append(new ASTORE(name));
    // Upon normal execution we jump behind exception handler, the target address is not known yet.
    final GOTO g = new GOTO(null);
    final InstructionHandle try_end = il.append(g);
    /* } catch() { ... }
         * Add exception handler: print exception and return from method
         */
    final InstructionHandle handler = il.append(factory.createFieldAccess("java.lang.System", "out", p_stream, Const.GETSTATIC));
    // Little trick in order not to save exception object temporarily
    il.append(InstructionConst.SWAP);
    il.append(factory.createInvoke("java.io.PrintStream", "println", Type.VOID, new Type[] { Type.OBJECT }, Const.INVOKEVIRTUAL));
    il.append(InstructionConst.RETURN);
    mg.addExceptionHandler(try_start, try_end, handler, new ObjectType("java.io.IOException"));
    // Normal code continues, now we can set the branch target of the GOTO that jumps over the handler code.
    final InstructionHandle ih = il.append(factory.createFieldAccess("java.lang.System", "out", p_stream, Const.GETSTATIC));
    g.setTarget(ih);
    // String concatenation compiles to StringBuffer operations.
    il.append(factory.createNew(Type.STRINGBUFFER));
    il.append(InstructionConst.DUP);
    il.append(new PUSH(cp, "Hello, "));
    il.append(factory.createInvoke("java.lang.StringBuffer", "<init>", Type.VOID, new Type[] { Type.STRING }, Const.INVOKESPECIAL));
    il.append(new ALOAD(name));
    // Concatenate strings using a StringBuffer and print them.
    il.append(factory.createInvoke("java.lang.StringBuffer", "append", Type.STRINGBUFFER, new Type[] { Type.STRING }, Const.INVOKEVIRTUAL));
    il.append(factory.createInvoke("java.lang.StringBuffer", "toString", Type.STRING, Type.NO_ARGS, Const.INVOKEVIRTUAL));
    il.append(factory.createInvoke("java.io.PrintStream", "println", Type.VOID, new Type[] { Type.STRING }, Const.INVOKEVIRTUAL));
    il.append(InstructionConst.RETURN);
    // Needed stack size
    mg.setMaxStack(5);
    cg.addMethod(mg.getMethod());
    // Reuse instruction handles
    il.dispose();
    // Add public <init> method, i.e. empty constructor
    cg.addEmptyConstructor(Const.ACC_PUBLIC);
    // Get JavaClreplaced object and dump it to file.
    try {
        cg.getJavaClreplaced().dump("HelloWorld.clreplaced");
    } catch (final IOException e) {
        System.err.println(e);
    }
}

18 View Complete Implementation : ASTFunDecl.java
Copyright Apache License 2.0
Author : apache
/**
 * Fifth preplaced, produce Java byte code.
 */
public void byte_code(final ClreplacedGen clreplaced_gen, final ConstantPoolGen cp) {
    MethodGen method = null;
    boolean main = false, ignore = false;
    final String clreplaced_name = clreplaced_gen.getClreplacedName();
    final String fname = name.getName();
    final InstructionList il = new InstructionList();
    // default for `main'
    Type[] args = { new ArrayType(Type.STRING, 1) };
    String[] arg_names = { "$argv" };
    if (fname.equals("main")) {
        method = new MethodGen(ACC_STATIC | ACC_PUBLIC, Type.VOID, args, arg_names, "main", clreplaced_name, il, cp);
        main = true;
    } else if (fname.equals("READ") || fname.equals("WRITE")) {
        // Do nothing
        ignore = true;
    } else {
        final int size = argv.length;
        arg_names = new String[size];
        args = new Type[size];
        for (int i = 0; i < size; i++) {
            args[i] = Type.INT;
            arg_names[i] = argv[i].getName();
        }
        method = new MethodGen(ACC_STATIC | ACC_PRIVATE | ACC_FINAL, Type.INT, args, arg_names, fname, clreplaced_name, il, cp);
        final LocalVariableGen[] lv = method.getLocalVariables();
        for (int i = 0; i < size; i++) {
            final Variable entry = (Variable) env.get(arg_names[i]);
            entry.setLocalVariable(lv[i]);
        }
        method.addException("java.io.IOException");
    }
    if (!ignore) {
        body.byte_code(il, method, cp);
        if (main) {
            final ObjectType e_type = new ObjectType("java.lang.Exception");
            final InstructionHandle start = il.getStart();
            InstructionHandle end, handler, end_handler;
            final LocalVariableGen exc = method.addLocalVariable("$e", e_type, null, null);
            final int slot = exc.getIndex();
            // Remove last element on stack
            il.append(InstructionConstants.POP);
            // Remove last element on stack
            pop();
            // Use instruction constants, if possible
            end = il.append(InstructionConstants.RETURN);
            // catch
            // save exception object
            handler = il.append(new ASTORE(slot));
            il.append(new GETSTATIC(cp.addFieldref("java.lang.System", "err", "Ljava/io/PrintStream;")));
            il.append(new ALOAD(slot));
            push(2);
            il.append(new INVOKEVIRTUAL(cp.addMethodref("java.io.PrintStream", "println", "(Ljava/lang/Object;)V")));
            pop(2);
            end_handler = il.append(InstructionConstants.RETURN);
            method.addExceptionHandler(start, end, handler, e_type);
            exc.setStart(handler);
            exc.setEnd(end_handler);
        } else {
            // Reuse object to save memory
            il.append(InstructionConstants.IRETURN);
        }
        // First optimization preplaced, provided by MethodGen
        method.removeNOPs();
        // Second optimization preplaced, application-specific
        optimizeIFs(il);
        method.setMaxStack(max_size);
        clreplaced_gen.addMethod(method.getMethod());
    }
    // Dispose instruction handles for better memory utilization
    il.dispose();
    reset();
}

18 View Complete Implementation : ElementValueGenTestCase.java
Copyright Apache License 2.0
Author : apache
// //
// Create clreplaced element value
public void testCreateClreplacedElementValue() throws Exception {
    final ClreplacedGen cg = createClreplacedGen("HelloWorld");
    final ConstantPoolGen cp = cg.getConstantPool();
    final ObjectType clreplacedType = new ObjectType("java.lang.Integer");
    final ClreplacedElementValueGen evg = new ClreplacedElementValueGen(clreplacedType, cp);
    replacedertTrue("Unexpected value for contained clreplaced: '" + evg.getClreplacedString() + "'", evg.getClreplacedString().contains("Integer"));
    checkSerialize(evg, cp);
}

18 View Complete Implementation : PLSETestCase.java
Copyright Apache License 2.0
Author : apache
/**
 * BCEL-295:
 */
public void testB295() throws Exception {
    final JavaClreplaced clazz = getTestClreplaced(PACKAGE_BASE_NAME + ".data.PLSETestClreplaced2");
    final ClreplacedGen cg = new ClreplacedGen(clazz);
    final ConstantPoolGen pool = cg.getConstantPool();
    // 'main'
    final Method m = cg.getMethodAt(1);
    final LocalVariableTable lvt = m.getLocalVariableTable();
    // 'i'
    final LocalVariable lv = lvt.getLocalVariable(2, 4);
    // System.out.println(lv);
    final MethodGen mg = new MethodGen(m, cg.getClreplacedName(), pool);
    final LocalVariableTable new_lvt = mg.getLocalVariableTable(mg.getConstantPool());
    // 'i'
    final LocalVariable new_lv = new_lvt.getLocalVariable(2, 4);
    // System.out.println(new_lv);
    replacedertEquals("live range length", lv.getLength(), new_lv.getLength());
}

18 View Complete Implementation : PLSETestCase.java
Copyright Apache License 2.0
Author : apache
/**
 * BCEL-208: A couple of methods in MethodGen.java need to test for
 * an empty instruction list.
 */
public void testB208() throws ClreplacedNotFoundException {
    final JavaClreplaced clazz = getTestClreplaced(PACKAGE_BASE_NAME + ".data.PLSETestClreplaced");
    final ClreplacedGen gen = new ClreplacedGen(clazz);
    final ConstantPoolGen pool = gen.getConstantPool();
    final Method m = gen.getMethodAt(1);
    final MethodGen mg = new MethodGen(m, gen.getClreplacedName(), pool);
    mg.setInstructionList(null);
    mg.addLocalVariable("local2", Type.INT, null, null);
    // currently, this will cause null pointer exception
    mg.getLocalVariableTable(pool);
}

18 View Complete Implementation : PLSETestCase.java
Copyright Apache License 2.0
Author : apache
/**
 * BCEL-79:
 */
public void testB79() throws ClreplacedNotFoundException {
    final JavaClreplaced clazz = getTestClreplaced(PACKAGE_BASE_NAME + ".data.PLSETestClreplaced");
    final ClreplacedGen gen = new ClreplacedGen(clazz);
    final ConstantPoolGen pool = gen.getConstantPool();
    final Method m = gen.getMethodAt(2);
    final LocalVariableTable lvt = m.getLocalVariableTable();
    // System.out.println(lvt);
    // System.out.println(lvt.getTableLength());
    final MethodGen mg = new MethodGen(m, gen.getClreplacedName(), pool);
    final LocalVariableTable new_lvt = mg.getLocalVariableTable(mg.getConstantPool());
    // System.out.println(new_lvt);
    replacedertEquals("number of locals", lvt.getTableLength(), new_lvt.getTableLength());
}

18 View Complete Implementation : PLSETestCase.java
Copyright Apache License 2.0
Author : apache
/**
 * BCEL-262:
 */
public void testB262() throws ClreplacedNotFoundException {
    final JavaClreplaced clazz = getTestClreplaced(PACKAGE_BASE_NAME + ".data.PLSETestEnum");
    final ClreplacedGen gen = new ClreplacedGen(clazz);
    final ConstantPoolGen pool = gen.getConstantPool();
    // get the values() method
    final Method m = gen.getMethodAt(0);
    final MethodGen mg = new MethodGen(m, gen.getClreplacedName(), pool);
    final InstructionList il = mg.getInstructionList();
    // get the invokevirtual instruction
    final InstructionHandle ih = il.findHandle(3);
    final InvokeInstruction ii = (InvokeInstruction) (ih.getInstruction());
    // without fix, the getClreplacedName() will throw:
    // java.lang.IllegalArgumentException: Cannot be used on an array type
    final String cn = ii.getClreplacedName(pool);
    replacedertEquals("[Lorg.apache.bcel.data.PLSETestEnum;", cn);
}

17 View Complete Implementation : id.java
Copyright Apache License 2.0
Author : apache
public static void main(final String[] argv) throws Exception {
    JavaClreplaced clazz;
    if ((clazz = Repository.lookupClreplaced(argv[0])) == null) {
        // May throw IOException
        clazz = new ClreplacedParser(argv[0]).parse();
    }
    final ClreplacedGen cg = new ClreplacedGen(clazz);
    for (final Method method : clazz.getMethods()) {
        final MethodGen mg = new MethodGen(method, cg.getClreplacedName(), cg.getConstantPool());
        cg.replaceMethod(method, mg.getMethod());
    }
    for (final Field field : clazz.getFields()) {
        final FieldGen fg = new FieldGen(field, cg.getConstantPool());
        cg.replaceField(field, fg.getField());
    }
    cg.getJavaClreplaced().dump(clazz.getClreplacedName() + ".clazz");
}

17 View Complete Implementation : ASTProgram.java
Copyright Apache License 2.0
Author : apache
/**
 * Fifth preplaced, produce Java byte code.
 */
public void byte_code(final ClreplacedGen clreplaced_gen, final ConstantPoolGen cp) {
    /* private static BufferedReader _in;
     */
    clreplaced_gen.addField(new Field(ACC_PRIVATE | ACC_STATIC, cp.addUtf8("_in"), cp.addUtf8("Ljava/io/BufferedReader;"), null, cp.getConstantPool()));
    MethodGen method;
    InstructionList il = new InstructionList();
    final String clreplaced_name = clreplaced_gen.getClreplacedName();
    /* Often used constant pool entries
     */
    final int _in = cp.addFieldref(clreplaced_name, "_in", "Ljava/io/BufferedReader;");
    final int out = cp.addFieldref("java.lang.System", "out", "Ljava/io/PrintStream;");
    il.append(new GETSTATIC(out));
    il.append(new PUSH(cp, "Please enter a number> "));
    il.append(new INVOKEVIRTUAL(cp.addMethodref("java.io.PrintStream", "print", "(Ljava/lang/String;)V")));
    il.append(new GETSTATIC(_in));
    il.append(new INVOKEVIRTUAL(cp.addMethodref("java.io.BufferedReader", "readLine", "()Ljava/lang/String;")));
    il.append(new INVOKESTATIC(cp.addMethodref("java.lang.Integer", "parseInt", "(Ljava/lang/String;)I")));
    il.append(InstructionConstants.IRETURN);
    /* private static int _readInt() throws IOException
     */
    method = new MethodGen(ACC_STATIC | ACC_PRIVATE | ACC_FINAL, Type.INT, Type.NO_ARGS, null, "_readInt", clreplaced_name, il, cp);
    method.addException("java.io.IOException");
    method.setMaxStack(2);
    clreplaced_gen.addMethod(method.getMethod());
    /* private static int _writeInt(int i) throws IOException
     */
    final Type[] args = { Type.INT };
    final String[] argv = { "i" };
    il = new InstructionList();
    il.append(new GETSTATIC(out));
    il.append(new NEW(cp.addClreplaced("java.lang.StringBuffer")));
    il.append(InstructionConstants.DUP);
    il.append(new PUSH(cp, "Result: "));
    il.append(new INVOKESPECIAL(cp.addMethodref("java.lang.StringBuffer", "<init>", "(Ljava/lang/String;)V")));
    il.append(new ILOAD(0));
    il.append(new INVOKEVIRTUAL(cp.addMethodref("java.lang.StringBuffer", "append", "(I)Ljava/lang/StringBuffer;")));
    il.append(new INVOKEVIRTUAL(cp.addMethodref("java.lang.StringBuffer", "toString", "()Ljava/lang/String;")));
    il.append(new INVOKEVIRTUAL(cp.addMethodref("java.io.PrintStream", "println", "(Ljava/lang/String;)V")));
    il.append(new PUSH(cp, 0));
    // Reuse objects, if possible
    il.append(InstructionConstants.IRETURN);
    method = new MethodGen(ACC_STATIC | ACC_PRIVATE | ACC_FINAL, Type.INT, args, argv, "_writeInt", clreplaced_name, il, cp);
    method.setMaxStack(4);
    clreplaced_gen.addMethod(method.getMethod());
    /* public <init> -- constructor
     */
    // Dispose instruction handles for better memory utilization
    il.dispose();
    il = new InstructionList();
    // Push `this'
    il.append(new ALOAD(0));
    il.append(new INVOKESPECIAL(cp.addMethodref("java.lang.Object", "<init>", "()V")));
    il.append(new RETURN());
    method = new MethodGen(ACC_PUBLIC, Type.VOID, Type.NO_ARGS, null, "<init>", clreplaced_name, il, cp);
    method.setMaxStack(1);
    clreplaced_gen.addMethod(method.getMethod());
    /* clreplaced initializer
     */
    // Dispose instruction handles for better memory utilization
    il.dispose();
    il = new InstructionList();
    il.append(new NEW(cp.addClreplaced("java.io.BufferedReader")));
    il.append(InstructionConstants.DUP);
    il.append(new NEW(cp.addClreplaced("java.io.InputStreamReader")));
    il.append(InstructionConstants.DUP);
    il.append(new GETSTATIC(cp.addFieldref("java.lang.System", "in", "Ljava/io/InputStream;")));
    il.append(new INVOKESPECIAL(cp.addMethodref("java.io.InputStreamReader", "<init>", "(Ljava/io/InputStream;)V")));
    il.append(new INVOKESPECIAL(cp.addMethodref("java.io.BufferedReader", "<init>", "(Ljava/io/Reader;)V")));
    il.append(new PUTSTATIC(_in));
    // Reuse instruction constants
    il.append(InstructionConstants.RETURN);
    method = new MethodGen(ACC_STATIC, Type.VOID, Type.NO_ARGS, null, "<clinit>", clreplaced_name, il, cp);
    method.setMaxStack(5);
    clreplaced_gen.addMethod(method.getMethod());
    for (int i = 0; i < fun_decls.length; i++) {
        fun_decls[i].byte_code(clreplaced_gen, cp);
    }
}

17 View Complete Implementation : StackFixer.java
Copyright MIT License
Author : contra
public void fixStack() {
    for (ClreplacedGen cg : cgs.values()) {
        for (Method method : cg.getMethods()) {
            MethodGen mg = new MethodGen(method, cg.getClreplacedName(), cg.getConstantPool());
            mg.removeNOPs();
            mg.setMaxLocals();
            mg.setMaxStack();
            cg.replaceMethod(method, mg.getMethod());
            logger.debug(String.format("Reset MaxStack and MaxLocals in %s.%s", cg.getClreplacedName(), mg.getName()));
        }
    }
}

17 View Complete Implementation : JavaBuilder.java
Copyright zlib License
Author : hagish
public clreplaced JavaBuilder {

    private static final String STR_VARARGS = Varargs.clreplaced.getName();

    private static final String STR_LUAVALUE = LuaValue.clreplaced.getName();

    private static final String STR_LUASTRING = LuaString.clreplaced.getName();

    private static final String STR_LUAINTEGER = LuaInteger.clreplaced.getName();

    private static final String STR_LUADOUBLE = LuaDouble.clreplaced.getName();

    private static final String STR_LUANUMBER = LuaNumber.clreplaced.getName();

    private static final String STR_LUABOOLEAN = LuaBoolean.clreplaced.getName();

    private static final String STR_LUATABLE = LuaTable.clreplaced.getName();

    private static final String STR_BUFFER = Buffer.clreplaced.getName();

    private static final String STR_STRING = String.clreplaced.getName();

    private static final ObjectType TYPE_VARARGS = new ObjectType(STR_VARARGS);

    private static final ObjectType TYPE_LUAVALUE = new ObjectType(STR_LUAVALUE);

    private static final ObjectType TYPE_LUASTRING = new ObjectType(STR_LUASTRING);

    private static final ObjectType TYPE_LUAINTEGER = new ObjectType(STR_LUAINTEGER);

    private static final ObjectType TYPE_LUADOUBLE = new ObjectType(STR_LUADOUBLE);

    private static final ObjectType TYPE_LUANUMBER = new ObjectType(STR_LUANUMBER);

    private static final ObjectType TYPE_LUABOOLEAN = new ObjectType(STR_LUABOOLEAN);

    private static final ObjectType TYPE_LUATABLE = new ObjectType(STR_LUATABLE);

    private static final ObjectType TYPE_BUFFER = new ObjectType(STR_BUFFER);

    private static final ArrayType TYPE_LOCALUPVALUE = new ArrayType(TYPE_LUAVALUE, 1);

    private static final ArrayType TYPE_CHARARRAY = new ArrayType(Type.CHAR, 1);

    private static final Clreplaced[] NO_INNER_CLreplacedES = {};

    private static final String STR_FUNCV = VarArgFunction.clreplaced.getName();

    private static final String STR_FUNC0 = ZeroArgFunction.clreplaced.getName();

    private static final String STR_FUNC1 = OneArgFunction.clreplaced.getName();

    private static final String STR_FUNC2 = TwoArgFunction.clreplaced.getName();

    private static final String STR_FUNC3 = ThreeArgFunction.clreplaced.getName();

    // argument list types
    private static final Type[] ARG_TYPES_NONE = {};

    private static final Type[] ARG_TYPES_INT = { Type.INT };

    private static final Type[] ARG_TYPES_DOUBLE = { Type.DOUBLE };

    private static final Type[] ARG_TYPES_STRING = { Type.STRING };

    private static final Type[] ARG_TYPES_CHARARRAY = { TYPE_CHARARRAY };

    private static final Type[] ARG_TYPES_VARARGS_INT = { TYPE_VARARGS, Type.INT };

    private static final Type[] ARG_TYPES_INT_LUAVALUE = { Type.INT, TYPE_LUAVALUE };

    private static final Type[] ARG_TYPES_INT_VARARGS = { Type.INT, TYPE_VARARGS };

    private static final Type[] ARG_TYPES_LUAVALUE_VARARGS = { TYPE_LUAVALUE, TYPE_VARARGS };

    private static final Type[] ARG_TYPES_LUAVALUE_LUAVALUE_VARARGS = { TYPE_LUAVALUE, TYPE_LUAVALUE, TYPE_VARARGS };

    private static final Type[] ARG_TYPES_LUAVALUEARRAY = { new ArrayType(TYPE_LUAVALUE, 1) };

    private static final Type[] ARG_TYPES_LUAVALUEARRAY_VARARGS = { new ArrayType(TYPE_LUAVALUE, 1), TYPE_VARARGS };

    private static final Type[] ARG_TYPES_LUAVALUE_LUAVALUE_LUAVALUE = { TYPE_LUAVALUE, TYPE_LUAVALUE, TYPE_LUAVALUE };

    private static final Type[] ARG_TYPES_VARARGS = { TYPE_VARARGS };

    private static final Type[] ARG_TYPES_LUAVALUE_LUAVALUE = { TYPE_LUAVALUE, TYPE_LUAVALUE };

    private static final Type[] ARG_TYPES_INT_INT = { Type.INT, Type.INT };

    private static final Type[] ARG_TYPES_LUAVALUE = { TYPE_LUAVALUE };

    private static final Type[] ARG_TYPES_BUFFER = { TYPE_BUFFER };

    // names, arg types for main prototype clreplacedes
    private static final String[] SUPER_NAME_N = { STR_FUNC0, STR_FUNC1, STR_FUNC2, STR_FUNC3, STR_FUNCV };

    private static final ObjectType[] RETURN_TYPE_N = { TYPE_LUAVALUE, TYPE_LUAVALUE, TYPE_LUAVALUE, TYPE_LUAVALUE, TYPE_VARARGS };

    private static final Type[][] ARG_TYPES_N = { ARG_TYPES_NONE, ARG_TYPES_LUAVALUE, ARG_TYPES_LUAVALUE_LUAVALUE, ARG_TYPES_LUAVALUE_LUAVALUE_LUAVALUE, ARG_TYPES_VARARGS };

    private static final String[][] ARG_NAMES_N = { {}, { "arg" }, { "arg1", "arg2" }, { "arg1", "arg2", "arg3" }, { "args" } };

    private static final String[] METH_NAME_N = { "call", "call", "call", "call", "onInvoke" };

    // varable naming
    private static final String PREFIX_CONSTANT = "k";

    private static final String PREFIX_UPVALUE = "u";

    private static final String PREFIX_PLAIN_SLOT = "s";

    private static final String PREFIX_UPVALUE_SLOT = "a";

    private static final String NAME_VARRESULT = "v";

    // basic info
    private final ProtoInfo pi;

    private final Prototype p;

    private final String clreplacedname;

    // bcel variables
    private final ClreplacedGen cg;

    private final ConstantPoolGen cp;

    private final InstructionFactory factory;

    // main instruction list for the main function of this clreplaced
    private final InstructionList init;

    private final InstructionList main;

    private final MethodGen mg;

    // the superclreplaced arg count, 0-3 args, 4=varargs
    private int superclreplacedType;

    private static int SUPERTYPE_VARARGS = 4;

    // storage for goto locations
    private final int[] targets;

    private final BranchInstruction[] branches;

    private final InstructionHandle[] branchDestHandles;

    private InstructionHandle beginningOfLuaInstruction;

    // hold vararg result
    private LocalVariableGen varresult = null;

    public JavaBuilder(ProtoInfo pi, String clreplacedname, String filename) {
        this.pi = pi;
        this.p = pi.prototype;
        this.clreplacedname = clreplacedname;
        // what clreplaced to inherit from
        superclreplacedType = p.numparams;
        if (p.is_vararg != 0 || superclreplacedType >= SUPERTYPE_VARARGS)
            superclreplacedType = SUPERTYPE_VARARGS;
        for (int i = 0, n = p.code.length; i < n; i++) {
            int inst = p.code[i];
            int o = Lua.GET_OPCODE(inst);
            if ((o == Lua.OP_TAILCALL) || ((o == Lua.OP_RETURN) && (Lua.GETARG_B(inst) < 1 || Lua.GETARG_B(inst) > 2))) {
                superclreplacedType = SUPERTYPE_VARARGS;
                break;
            }
        }
        // create clreplaced generator
        cg = new ClreplacedGen(clreplacedname, SUPER_NAME_N[superclreplacedType], filename, Constants.ACC_PUBLIC | Constants.ACC_SUPER, null);
        // cg creates constant pool
        cp = cg.getConstantPool();
        // main instruction lists
        factory = new InstructionFactory(cg);
        init = new InstructionList();
        main = new InstructionList();
        // create the fields
        for (int i = 0; i < p.nups; i++) {
            boolean isrw = pi.isReadWriteUpvalue(pi.upvals[i]);
            Type uptype = isrw ? (Type) TYPE_LOCALUPVALUE : (Type) TYPE_LUAVALUE;
            FieldGen fg = new FieldGen(0, uptype, upvalueName(i), cp);
            cg.addField(fg.getField());
        }
        // create the method
        mg = new // access flags
        MethodGen(// access flags
        Constants.ACC_PUBLIC | Constants.ACC_FINAL, // return type
        RETURN_TYPE_N[superclreplacedType], // argument types
        ARG_TYPES_N[superclreplacedType], // arg names
        ARG_NAMES_N[superclreplacedType], METH_NAME_N[superclreplacedType], // method, defining clreplaced
        STR_LUAVALUE, main, cp);
        // initialize the values in the slots
        initializeSlots();
        // initialize branching
        int nc = p.code.length;
        targets = new int[nc];
        branches = new BranchInstruction[nc];
        branchDestHandles = new InstructionHandle[nc];
    }

    public void initializeSlots() {
        int slot = 0;
        createUpvalues(-1, 0, p.maxstacksize);
        if (superclreplacedType == SUPERTYPE_VARARGS) {
            for (slot = 0; slot < p.numparams; slot++) {
                if (pi.isInitialValueUsed(slot)) {
                    append(new ALOAD(1));
                    append(new PUSH(cp, slot + 1));
                    append(factory.createInvoke(STR_VARARGS, "arg", TYPE_LUAVALUE, ARG_TYPES_INT, Constants.INVOKEVIRTUAL));
                    storeLocal(-1, slot);
                }
            }
            boolean needsarg = ((p.is_vararg & Lua.VARARG_NEEDSARG) != 0);
            if (needsarg) {
                append(new ALOAD(1));
                append(new PUSH(cp, 1 + p.numparams));
                append(factory.createInvoke(STR_LUAVALUE, "tableOf", TYPE_LUATABLE, ARG_TYPES_VARARGS_INT, Constants.INVOKESTATIC));
                storeLocal(-1, slot++);
            } else if (p.numparams > 0) {
                append(new ALOAD(1));
                append(new PUSH(cp, 1 + p.numparams));
                append(factory.createInvoke(STR_VARARGS, "subargs", TYPE_VARARGS, ARG_TYPES_INT, Constants.INVOKEVIRTUAL));
                append(new ASTORE(1));
            }
        } else {
            // fixed arg function between 0 and 3 arguments
            for (slot = 0; slot < p.numparams; slot++) {
                this.plainSlotVars.put(Integer.valueOf(slot), Integer.valueOf(1 + slot));
                if (pi.isUpvalueCreate(-1, slot)) {
                    append(new ALOAD(1 + slot));
                    storeLocal(-1, slot);
                }
            }
        }
        // nil parameters
        for (; slot < p.maxstacksize; slot++) {
            if (pi.isInitialValueUsed(slot)) {
                loadNil();
                storeLocal(-1, slot);
            }
        }
    }

    public byte[] completeClreplaced() {
        // add clreplaced initializer
        if (!init.isEmpty()) {
            MethodGen mg = new MethodGen(Constants.ACC_STATIC, Type.VOID, ARG_TYPES_NONE, new String[] {}, "<clinit>", cg.getClreplacedName(), init, cg.getConstantPool());
            init.append(InstructionConstants.RETURN);
            mg.setMaxStack();
            cg.addMethod(mg.getMethod());
            init.dispose();
        }
        // add default constructor
        cg.addEmptyConstructor(Constants.ACC_PUBLIC);
        // gen method
        resolveBranches();
        mg.setMaxStack();
        cg.addMethod(mg.getMethod());
        main.dispose();
        // convert to clreplaced bytes
        try {
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            cg.getJavaClreplaced().dump(baos);
            return baos.toByteArray();
        } catch (IOException ioe) {
            throw new RuntimeException("JavaClreplaced.dump() threw " + ioe);
        }
    }

    public void dup() {
        append(InstructionConstants.DUP);
    }

    public void pop() {
        append(InstructionConstants.POP);
    }

    public void loadNil() {
        append(factory.createFieldAccess(STR_LUAVALUE, "NIL", TYPE_LUAVALUE, Constants.GETSTATIC));
    }

    public void loadNone() {
        append(factory.createFieldAccess(STR_LUAVALUE, "NONE", TYPE_LUAVALUE, Constants.GETSTATIC));
    }

    public void loadBoolean(boolean b) {
        String field = (b ? "TRUE" : "FALSE");
        append(factory.createFieldAccess(STR_LUAVALUE, field, TYPE_LUABOOLEAN, Constants.GETSTATIC));
    }

    private Map<Integer, Integer> plainSlotVars = new HashMap<Integer, Integer>();

    private Map<Integer, Integer> upvalueSlotVars = new HashMap<Integer, Integer>();

    private int findSlot(int slot, Map<Integer, Integer> map, String prefix, Type type) {
        Integer islot = Integer.valueOf(slot);
        if (map.containsKey(islot))
            return ((Integer) map.get(islot)).intValue();
        String name = prefix + slot;
        LocalVariableGen local = mg.addLocalVariable(name, type, null, null);
        int index = local.getIndex();
        map.put(islot, Integer.valueOf(index));
        return index;
    }

    private int findSlotIndex(int slot, boolean isupvalue) {
        return isupvalue ? findSlot(slot, upvalueSlotVars, PREFIX_UPVALUE_SLOT, TYPE_LOCALUPVALUE) : findSlot(slot, plainSlotVars, PREFIX_PLAIN_SLOT, TYPE_LUAVALUE);
    }

    public void loadLocal(int pc, int slot) {
        boolean isupval = pi.isUpvalueRefer(pc, slot);
        int index = findSlotIndex(slot, isupval);
        append(new ALOAD(index));
        if (isupval) {
            append(new PUSH(cp, 0));
            append(InstructionConstants.AALOAD);
        }
    }

    public void storeLocal(int pc, int slot) {
        boolean isupval = pi.isUpvaluereplacedign(pc, slot);
        int index = findSlotIndex(slot, isupval);
        if (isupval) {
            boolean isupcreate = pi.isUpvalueCreate(pc, slot);
            if (isupcreate) {
                append(factory.createInvoke(clreplacedname, "newupe", TYPE_LOCALUPVALUE, ARG_TYPES_NONE, Constants.INVOKESTATIC));
                append(InstructionConstants.DUP);
                append(new ASTORE(index));
            } else {
                append(new ALOAD(index));
            }
            append(InstructionConstants.SWAP);
            append(new PUSH(cp, 0));
            append(InstructionConstants.SWAP);
            append(InstructionConstants.AASTORE);
        } else {
            append(new ASTORE(index));
        }
    }

    public void createUpvalues(int pc, int firstslot, int numslots) {
        for (int i = 0; i < numslots; i++) {
            int slot = firstslot + i;
            boolean isupcreate = pi.isUpvalueCreate(pc, slot);
            if (isupcreate) {
                int index = findSlotIndex(slot, true);
                append(factory.createInvoke(clreplacedname, "newupn", TYPE_LOCALUPVALUE, ARG_TYPES_NONE, Constants.INVOKESTATIC));
                append(new ASTORE(index));
            }
        }
    }

    public void convertToUpvalue(int pc, int slot) {
        boolean isupreplacedign = pi.isUpvaluereplacedign(pc, slot);
        if (isupreplacedign) {
            int index = findSlotIndex(slot, false);
            append(new ALOAD(index));
            append(factory.createInvoke(clreplacedname, "newupl", TYPE_LOCALUPVALUE, ARG_TYPES_LUAVALUE, Constants.INVOKESTATIC));
            int upindex = findSlotIndex(slot, true);
            append(new ASTORE(upindex));
        }
    }

    private static String upvalueName(int upindex) {
        return PREFIX_UPVALUE + upindex;
    }

    public void loadUpvalue(int upindex) {
        boolean isrw = pi.isReadWriteUpvalue(pi.upvals[upindex]);
        append(InstructionConstants.THIS);
        if (isrw) {
            append(factory.createFieldAccess(clreplacedname, upvalueName(upindex), TYPE_LOCALUPVALUE, Constants.GETFIELD));
            append(new PUSH(cp, 0));
            append(InstructionConstants.AALOAD);
        } else {
            append(factory.createFieldAccess(clreplacedname, upvalueName(upindex), TYPE_LUAVALUE, Constants.GETFIELD));
        }
    }

    public void storeUpvalue(int pc, int upindex, int slot) {
        boolean isrw = pi.isReadWriteUpvalue(pi.upvals[upindex]);
        append(InstructionConstants.THIS);
        if (isrw) {
            append(factory.createFieldAccess(clreplacedname, upvalueName(upindex), TYPE_LOCALUPVALUE, Constants.GETFIELD));
            append(new PUSH(cp, 0));
            loadLocal(pc, slot);
            append(InstructionConstants.AASTORE);
        } else {
            loadLocal(pc, slot);
            append(factory.createFieldAccess(clreplacedname, upvalueName(upindex), TYPE_LUAVALUE, Constants.PUTFIELD));
        }
    }

    public void newTable(int b, int c) {
        append(new PUSH(cp, b));
        append(new PUSH(cp, c));
        append(factory.createInvoke(STR_LUAVALUE, "tableOf", TYPE_LUATABLE, ARG_TYPES_INT_INT, Constants.INVOKESTATIC));
    }

    public void loadEnv() {
        append(InstructionConstants.THIS);
        append(factory.createFieldAccess(clreplacedname, "env", TYPE_LUAVALUE, Constants.GETFIELD));
    }

    public void loadVarargs() {
        append(new ALOAD(1));
    }

    public void loadVarargs(int argindex) {
        loadVarargs();
        arg(argindex);
    }

    public void arg(int argindex) {
        if (argindex == 1) {
            append(factory.createInvoke(STR_VARARGS, "arg1", TYPE_LUAVALUE, ARG_TYPES_NONE, Constants.INVOKEVIRTUAL));
        } else {
            append(new PUSH(cp, argindex));
            append(factory.createInvoke(STR_VARARGS, "arg", TYPE_LUAVALUE, ARG_TYPES_INT, Constants.INVOKEVIRTUAL));
        }
    }

    private int getVarresultIndex() {
        if (varresult == null)
            varresult = mg.addLocalVariable(NAME_VARRESULT, TYPE_VARARGS, null, null);
        return varresult.getIndex();
    }

    public void loadVarresult() {
        append(new ALOAD(getVarresultIndex()));
    }

    public void storeVarresult() {
        append(new ASTORE(getVarresultIndex()));
    }

    public void subargs(int firstarg) {
        append(new PUSH(cp, firstarg));
        append(factory.createInvoke(STR_VARARGS, "subargs", TYPE_VARARGS, ARG_TYPES_INT, Constants.INVOKEVIRTUAL));
    }

    public void getTable() {
        append(factory.createInvoke(STR_LUAVALUE, "get", TYPE_LUAVALUE, ARG_TYPES_LUAVALUE, Constants.INVOKEVIRTUAL));
    }

    public void setTable() {
        append(factory.createInvoke(STR_LUAVALUE, "set", Type.VOID, ARG_TYPES_LUAVALUE_LUAVALUE, Constants.INVOKEVIRTUAL));
    }

    public void unaryop(int o) {
        String op;
        switch(o) {
            default:
            case Lua.OP_UNM:
                op = "neg";
                break;
            case Lua.OP_NOT:
                op = "not";
                break;
            case Lua.OP_LEN:
                op = "len";
                break;
        }
        append(factory.createInvoke(STR_LUAVALUE, op, TYPE_LUAVALUE, Type.NO_ARGS, Constants.INVOKEVIRTUAL));
    }

    public void binaryop(int o) {
        String op;
        switch(o) {
            default:
            case Lua.OP_ADD:
                op = "add";
                break;
            case Lua.OP_SUB:
                op = "sub";
                break;
            case Lua.OP_MUL:
                op = "mul";
                break;
            case Lua.OP_DIV:
                op = "div";
                break;
            case Lua.OP_MOD:
                op = "mod";
                break;
            case Lua.OP_POW:
                op = "pow";
                break;
        }
        append(factory.createInvoke(STR_LUAVALUE, op, TYPE_LUAVALUE, ARG_TYPES_LUAVALUE, Constants.INVOKEVIRTUAL));
    }

    public void compareop(int o) {
        String op;
        switch(o) {
            default:
            case Lua.OP_EQ:
                op = "eq_b";
                break;
            case Lua.OP_LT:
                op = "lt_b";
                break;
            case Lua.OP_LE:
                op = "lteq_b";
                break;
        }
        append(factory.createInvoke(STR_LUAVALUE, op, Type.BOOLEAN, ARG_TYPES_LUAVALUE, Constants.INVOKEVIRTUAL));
    }

    public void areturn() {
        append(InstructionConstants.ARETURN);
    }

    public void toBoolean() {
        append(factory.createInvoke(STR_LUAVALUE, "toboolean", Type.BOOLEAN, Type.NO_ARGS, Constants.INVOKEVIRTUAL));
    }

    public void tostring() {
        append(factory.createInvoke(STR_BUFFER, "tostring", TYPE_LUASTRING, Type.NO_ARGS, Constants.INVOKEVIRTUAL));
    }

    public void isNil() {
        append(factory.createInvoke(STR_LUAVALUE, "isnil", Type.BOOLEAN, Type.NO_ARGS, Constants.INVOKEVIRTUAL));
    }

    public void testForLoop() {
        append(factory.createInvoke(STR_LUAVALUE, "testfor_b", Type.BOOLEAN, ARG_TYPES_LUAVALUE_LUAVALUE, Constants.INVOKEVIRTUAL));
    }

    public void loadArrayArgs(int pc, int firstslot, int nargs) {
        append(new PUSH(cp, nargs));
        append(new ANEWARRAY(cp.addClreplaced(STR_LUAVALUE)));
        for (int i = 0; i < nargs; i++) {
            append(InstructionConstants.DUP);
            append(new PUSH(cp, i));
            loadLocal(pc, firstslot++);
            append(new AASTORE());
        }
    }

    public void newVarargs(int pc, int firstslot, int nargs) {
        switch(nargs) {
            case 0:
                loadNone();
                break;
            case 1:
                loadLocal(pc, firstslot);
                break;
            case 2:
                loadLocal(pc, firstslot);
                loadLocal(pc, firstslot + 1);
                append(factory.createInvoke(STR_LUAVALUE, "varargsOf", TYPE_VARARGS, ARG_TYPES_LUAVALUE_VARARGS, Constants.INVOKESTATIC));
                break;
            case 3:
                loadLocal(pc, firstslot);
                loadLocal(pc, firstslot + 1);
                loadLocal(pc, firstslot + 2);
                append(factory.createInvoke(STR_LUAVALUE, "varargsOf", TYPE_VARARGS, ARG_TYPES_LUAVALUE_LUAVALUE_VARARGS, Constants.INVOKESTATIC));
                break;
            default:
                loadArrayArgs(pc, firstslot, nargs);
                append(factory.createInvoke(STR_LUAVALUE, "varargsOf", TYPE_VARARGS, ARG_TYPES_LUAVALUEARRAY, Constants.INVOKESTATIC));
                break;
        }
    }

    public void newVarargsVarresult(int pc, int firstslot, int nslots) {
        loadArrayArgs(pc, firstslot, nslots);
        loadVarresult();
        append(factory.createInvoke(STR_LUAVALUE, "varargsOf", TYPE_VARARGS, ARG_TYPES_LUAVALUEARRAY_VARARGS, Constants.INVOKESTATIC));
    }

    public void call(int nargs) {
        switch(nargs) {
            case 0:
                append(factory.createInvoke(STR_LUAVALUE, "call", TYPE_LUAVALUE, ARG_TYPES_NONE, Constants.INVOKEVIRTUAL));
                break;
            case 1:
                append(factory.createInvoke(STR_LUAVALUE, "call", TYPE_LUAVALUE, ARG_TYPES_LUAVALUE, Constants.INVOKEVIRTUAL));
                break;
            case 2:
                append(factory.createInvoke(STR_LUAVALUE, "call", TYPE_LUAVALUE, ARG_TYPES_LUAVALUE_LUAVALUE, Constants.INVOKEVIRTUAL));
                break;
            case 3:
                append(factory.createInvoke(STR_LUAVALUE, "call", TYPE_LUAVALUE, ARG_TYPES_LUAVALUE_LUAVALUE_LUAVALUE, Constants.INVOKEVIRTUAL));
                break;
            default:
                throw new IllegalArgumentException("can't call with " + nargs + " args");
        }
    }

    public void newTailcallVarargs() {
        append(factory.createInvoke(STR_LUAVALUE, "tailcallOf", TYPE_VARARGS, ARG_TYPES_LUAVALUE_VARARGS, Constants.INVOKESTATIC));
    }

    public void invoke(int nargs) {
        switch(nargs) {
            case -1:
                append(factory.createInvoke(STR_LUAVALUE, "invoke", TYPE_VARARGS, ARG_TYPES_VARARGS, Constants.INVOKEVIRTUAL));
                break;
            case 0:
                append(factory.createInvoke(STR_LUAVALUE, "invoke", TYPE_VARARGS, ARG_TYPES_NONE, Constants.INVOKEVIRTUAL));
                break;
            case 1:
                append(factory.createInvoke(STR_LUAVALUE, "invoke", TYPE_VARARGS, ARG_TYPES_VARARGS, Constants.INVOKEVIRTUAL));
                break;
            case 2:
                append(factory.createInvoke(STR_LUAVALUE, "invoke", TYPE_VARARGS, ARG_TYPES_LUAVALUE_VARARGS, Constants.INVOKEVIRTUAL));
                break;
            case 3:
                append(factory.createInvoke(STR_LUAVALUE, "invoke", TYPE_VARARGS, ARG_TYPES_LUAVALUE_LUAVALUE_VARARGS, Constants.INVOKEVIRTUAL));
                break;
            default:
                throw new IllegalArgumentException("can't invoke with " + nargs + " args");
        }
    }

    // ------------------------ closures ------------------------
    public void closureCreate(String protoname) {
        append(factory.createNew(new ObjectType(protoname)));
        append(InstructionConstants.DUP);
        append(factory.createInvoke(protoname, "<init>", Type.VOID, Type.NO_ARGS, Constants.INVOKESPECIAL));
        append(InstructionConstants.DUP);
        loadEnv();
        append(factory.createInvoke(STR_LUAVALUE, "setfenv", Type.VOID, ARG_TYPES_LUAVALUE, Constants.INVOKEVIRTUAL));
    }

    public void closureInitUpvalueFromUpvalue(String protoname, int newup, int upindex) {
        boolean isrw = pi.isReadWriteUpvalue(pi.upvals[upindex]);
        Type uptype = isrw ? (Type) TYPE_LOCALUPVALUE : (Type) TYPE_LUAVALUE;
        String srcname = upvalueName(upindex);
        String destname = upvalueName(newup);
        append(InstructionConstants.THIS);
        append(factory.createFieldAccess(clreplacedname, srcname, uptype, Constants.GETFIELD));
        append(factory.createFieldAccess(protoname, destname, uptype, Constants.PUTFIELD));
    }

    public void closureInitUpvalueFromLocal(String protoname, int newup, int pc, int srcslot) {
        boolean isrw = pi.isReadWriteUpvalue(pi.vars[srcslot][pc].upvalue);
        Type uptype = isrw ? (Type) TYPE_LOCALUPVALUE : (Type) TYPE_LUAVALUE;
        String destname = upvalueName(newup);
        int index = findSlotIndex(srcslot, isrw);
        append(new ALOAD(index));
        append(factory.createFieldAccess(protoname, destname, uptype, Constants.PUTFIELD));
    }

    private Map<LuaValue, String> constants = new HashMap<LuaValue, String>();

    public void loadConstant(LuaValue value) {
        switch(value.type()) {
            case LuaValue.TNIL:
                loadNil();
                break;
            case LuaValue.TBOOLEAN:
                loadBoolean(value.toboolean());
                break;
            case LuaValue.TNUMBER:
            case LuaValue.TSTRING:
                String name = (String) constants.get(value);
                if (name == null) {
                    name = value.type() == LuaValue.TNUMBER ? value.isinttype() ? createLuaIntegerField(value.checkint()) : createLuaDoubleField(value.checkdouble()) : createLuaStringField(value.checkstring());
                    constants.put(value, name);
                }
                append(factory.createGetStatic(clreplacedname, name, TYPE_LUAVALUE));
                break;
            default:
                throw new IllegalArgumentException("bad constant type: " + value.type());
        }
    }

    private String createLuaIntegerField(int value) {
        String name = PREFIX_CONSTANT + constants.size();
        FieldGen fg = new FieldGen(Constants.ACC_STATIC | Constants.ACC_FINAL, TYPE_LUAVALUE, name, cp);
        cg.addField(fg.getField());
        init.append(new PUSH(cp, value));
        init.append(factory.createInvoke(STR_LUAVALUE, "valueOf", TYPE_LUAINTEGER, ARG_TYPES_INT, Constants.INVOKESTATIC));
        init.append(factory.createPutStatic(clreplacedname, name, TYPE_LUAVALUE));
        return name;
    }

    private String createLuaDoubleField(double value) {
        String name = PREFIX_CONSTANT + constants.size();
        FieldGen fg = new FieldGen(Constants.ACC_STATIC | Constants.ACC_FINAL, TYPE_LUAVALUE, name, cp);
        cg.addField(fg.getField());
        init.append(new PUSH(cp, value));
        init.append(factory.createInvoke(STR_LUAVALUE, "valueOf", TYPE_LUANUMBER, ARG_TYPES_DOUBLE, Constants.INVOKESTATIC));
        init.append(factory.createPutStatic(clreplacedname, name, TYPE_LUAVALUE));
        return name;
    }

    private String createLuaStringField(LuaString value) {
        String name = PREFIX_CONSTANT + constants.size();
        FieldGen fg = new FieldGen(Constants.ACC_STATIC | Constants.ACC_FINAL, TYPE_LUAVALUE, name, cp);
        cg.addField(fg.getField());
        LuaString ls = value.checkstring();
        if (ls.isValidUtf8()) {
            init.append(new PUSH(cp, value.tojstring()));
            init.append(factory.createInvoke(STR_LUASTRING, "valueOf", TYPE_LUASTRING, ARG_TYPES_STRING, Constants.INVOKESTATIC));
        } else {
            char[] c = new char[ls.m_length];
            for (int j = 0; j < ls.m_length; j++) c[j] = (char) (0xff & (int) (ls.m_bytes[ls.m_offset + j]));
            init.append(new PUSH(cp, new String(c)));
            init.append(factory.createInvoke(STR_STRING, "toCharArray", TYPE_CHARARRAY, Type.NO_ARGS, Constants.INVOKEVIRTUAL));
            init.append(factory.createInvoke(STR_LUASTRING, "valueOf", TYPE_LUASTRING, ARG_TYPES_CHARARRAY, Constants.INVOKESTATIC));
        }
        init.append(factory.createPutStatic(clreplacedname, name, TYPE_LUAVALUE));
        return name;
    }

    // --------------------- branching support -------------------------
    public static final int BRANCH_GOTO = 1;

    public static final int BRANCH_IFNE = 2;

    public static final int BRANCH_IFEQ = 3;

    public void addBranch(int pc, int branchType, int targetpc) {
        switch(branchType) {
            default:
            case BRANCH_GOTO:
                branches[pc] = new GOTO(null);
                break;
            case BRANCH_IFNE:
                branches[pc] = new IFNE(null);
                break;
            case BRANCH_IFEQ:
                branches[pc] = new IFEQ(null);
                break;
        }
        targets[pc] = targetpc;
        append(branches[pc]);
    }

    private void append(Instruction i) {
        conditionalSetBeginningOfLua(main.append(i));
    }

    private void append(CompoundInstruction i) {
        conditionalSetBeginningOfLua(main.append(i));
    }

    private void append(BranchInstruction i) {
        conditionalSetBeginningOfLua(main.append(i));
    }

    private void conditionalSetBeginningOfLua(InstructionHandle ih) {
        if (beginningOfLuaInstruction == null)
            beginningOfLuaInstruction = ih;
    }

    public void onEndOfLuaInstruction(int pc) {
        branchDestHandles[pc] = beginningOfLuaInstruction;
        beginningOfLuaInstruction = null;
    }

    private void resolveBranches() {
        int nc = p.code.length;
        for (int pc = 0; pc < nc; pc++) {
            if (branches[pc] != null) {
                int t = targets[pc];
                while (t < branchDestHandles.length && branchDestHandles[t] == null) t++;
                if (t >= branchDestHandles.length)
                    throw new IllegalArgumentException("no target at or after " + targets[pc] + " op=" + Lua.GET_OPCODE(p.code[targets[pc]]));
                branches[pc].setTarget(branchDestHandles[t]);
            }
        }
    }

    public void setlistStack(int pc, int a0, int index0, int nvals) {
        for (int i = 0; i < nvals; i++) {
            dup();
            append(new PUSH(cp, index0 + i));
            loadLocal(pc, a0 + i);
            append(factory.createInvoke(STR_LUAVALUE, "rawset", Type.VOID, ARG_TYPES_INT_LUAVALUE, Constants.INVOKEVIRTUAL));
        }
    }

    public void setlistVarargs(int index0, int vresultbase) {
        append(new PUSH(cp, index0));
        loadVarresult();
        append(factory.createInvoke(STR_LUAVALUE, "rawsetlist", Type.VOID, ARG_TYPES_INT_VARARGS, Constants.INVOKEVIRTUAL));
    }

    public void concatvalue() {
        append(factory.createInvoke(STR_LUAVALUE, "concat", TYPE_LUAVALUE, ARG_TYPES_LUAVALUE, Constants.INVOKEVIRTUAL));
    }

    public void concatbuffer() {
        append(factory.createInvoke(STR_LUAVALUE, "concat", TYPE_BUFFER, ARG_TYPES_BUFFER, Constants.INVOKEVIRTUAL));
    }

    public void tobuffer() {
        append(factory.createInvoke(STR_LUAVALUE, "buffer", TYPE_BUFFER, Type.NO_ARGS, Constants.INVOKEVIRTUAL));
    }

    public void tovalue() {
        append(factory.createInvoke(STR_BUFFER, "value", TYPE_LUAVALUE, Type.NO_ARGS, Constants.INVOKEVIRTUAL));
    }
}

17 View Complete Implementation : BcelStage.java
Copyright MIT License
Author : pragmatic-objects
@Override
public final void apply(final ClreplacedPath clreplacedPath, final ClreplacedNames clreplacedNames, final Path workingDirectory) {
    final String cpString = clreplacedPath.paths().map(Object::toString).reduce((s1, s2) -> s1 + ":" + s2);
    final ClreplacedPathRepository clreplacedPathRepository = new ClreplacedPathRepository(new org.apache.bcel.util.ClreplacedPath(cpString));
    try {
        for (String clreplacedName : clreplacedNames.clreplacedNames()) {
            final JavaClreplaced javaClreplaced = clreplacedPathRepository.loadClreplaced(clreplacedName);
            final ClreplacedGen clreplacedGen = new ClreplacedGen(javaClreplaced);
            plugin.operateOn(clreplacedGen, javaClreplaced, clreplacedPathRepository);
        }
    } catch (Exception ex) {
        throw new RuntimeException(ex);
    }
}

16 View Complete Implementation : MiniC.java
Copyright Apache License 2.0
Author : apache
public static void main(final String[] argv) {
    final String[] file_name = new String[argv.length];
    int files = 0;
    MiniParser parser = null;
    String base_name = null;
    boolean byte_code = true;
    try {
        /* Parse command line arguments.
       */
        for (int i = 0; i < argv.length; i++) {
            if (argv[i].charAt(0) == '-') {
                // command line switch
                if (argv[i].equals("-java")) {
                    byte_code = false;
                } else if (argv[i].equals("-bytecode")) {
                    byte_code = true;
                } else {
                    throw new Exception("Unknown option: " + argv[i]);
                }
            } else {
                // add file name to list
                file_name[files++] = argv[i];
            }
        }
        if (files == 0) {
            System.err.println("Nothing to compile.");
        }
        for (int j = 0; j < files; j++) {
            errors = new Vector<>();
            warnings = new Vector<>();
            preplaced = 0;
            if (j == 0) {
                parser = new MiniParser(new java.io.FileInputStream(file_name[0]));
            } else {
                MiniParser.ReInit(new java.io.FileInputStream(file_name[j]));
            }
            int index = file_name[j].lastIndexOf('.');
            if (index > 0) {
                base_name = file_name[j].substring(0, index);
            } else {
                base_name = file_name[j];
            }
            if ((index = base_name.lastIndexOf(File.separatorChar)) > 0) {
                base_name = base_name.substring(index + 1);
            }
            file = file_name[j];
            System.out.println("Parsing ...");
            MiniParser.Program();
            ASTProgram program = (ASTProgram) MiniParser.jjtree.rootNode();
            System.out.println("Preplaced 1: Optimizing parse tree ...");
            preplaced = 1;
            program = program.traverse();
            // program.dump(">");
            if (errors.size() == 0) {
                System.out.println("Preplaced 2: Type checking (I) ...");
                program.eval(preplaced = 2);
            }
            if (errors.size() == 0) {
                System.out.println("Preplaced 3: Type checking (II) ...");
                program.eval(preplaced = 3);
            }
            for (int i = 0; i < errors.size(); i++) {
                System.out.println(errors.elementAt(i));
            }
            for (int i = 0; i < warnings.size(); i++) {
                System.out.println(warnings.elementAt(i));
            }
            if (errors.size() == 0) {
                if (byte_code) {
                    System.out.println("Preplaced 5: Generating byte code ...");
                    final ClreplacedGen clreplaced_gen = new ClreplacedGen(base_name, "java.lang.Object", file_name[j], ACC_PUBLIC | ACC_FINAL | ACC_SUPER, null);
                    final ConstantPoolGen cp = clreplaced_gen.getConstantPool();
                    program.byte_code(clreplaced_gen, cp);
                    final JavaClreplaced clazz = clreplaced_gen.getJavaClreplaced();
                    clazz.dump(base_name + ".clreplaced");
                } else {
                    System.out.println("Preplaced 5: Generating Java code ...");
                    final PrintWriter out = new PrintWriter(new FileOutputStream(base_name + ".java"));
                    program.code(out, base_name);
                    out.close();
                    System.out.println("Preplaced 6: Compiling Java code ...");
                    final String[] args = { "javac", base_name + ".java" };
                    // sun.tools.javac.Main compiler = new sun.tools.javac.Main(System.err, "javac");
                    try {
                        final Process p = Runtime.getRuntime().exec(args);
                        p.waitFor();
                    } catch (final Exception e) {
                        System.out.println(e);
                    }
                // compiler.compile(args);
                }
            }
            if ((errors.size() > 0) || (warnings.size() > 0)) {
                System.out.println(errors.size() + " errors and " + warnings.size() + " warnings.");
            }
        }
    } catch (final Exception e) {
        e.printStackTrace();
    }
}

16 View Complete Implementation : BCELBenchmark.java
Copyright Apache License 2.0
Author : apache
@Benchmark
public void generator(Blackhole bh) throws IOException {
    JarFile jar = getJarFile();
    for (JarEntry entry : getClreplacedes(jar)) {
        byte[] bytes = IOUtils.toByteArray(jar.getInputStream(entry));
        JavaClreplaced clazz = new ClreplacedParser(new ByteArrayInputStream(bytes), entry.getName()).parse();
        ClreplacedGen cg = new ClreplacedGen(clazz);
        for (Method m : cg.getMethods()) {
            MethodGen mg = new MethodGen(m, cg.getClreplacedName(), cg.getConstantPool());
            InstructionList il = mg.getInstructionList();
            if (il != null) {
                mg.getInstructionList().setPositions();
                mg.setMaxLocals();
                mg.setMaxStack();
            }
            cg.replaceMethod(m, mg.getMethod());
        }
        bh.consume(cg.getJavaClreplaced().getBytes());
    }
    jar.close();
}