package bytecode.stackmaptable;

import junit.framework.TestCase;
import org.apache.bcel.Repository;
import org.apache.bcel.classfile.*;
import org.apache.bcel.generic.ConstantPoolGen;
import org.apache.bcel.generic.MethodGen;
import org.apache.bcel.generic.StackMapTableGen;

import java.util.List;

public class StackMapTableGenTests extends TestCase {

    public static class StackMapTableTest {
        public void method1(){}

        Integer method2(Boolean b){
            if(b){
                return 1;
            }else{
                return 2;
            }
        }

        public static void staticMethod1(){
            int a = 1;
            int b = 2;
            while(true){
                a = b;
            }
        }

    }

    private MethodGen getMethod(Class<?> cls, String name) throws ClassNotFoundException {
        JavaClass jc = Repository.lookupClass(cls);
        ConstantPoolGen cp = new ConstantPoolGen(jc.getConstantPool());
        for (Method method : jc.getMethods()) {
            if (method.getName().equals(name)) {
                return new MethodGen(method, jc.getClassName(), cp);
            }
        }

        fail("Method " + name + " not found in class " + cls);
        return null;
    }

    public void testFrameSplittingTrivial() throws Exception{
        MethodGen mg = getMethod(StackMapTableTest.class, "method1");
        StackMapTableGen sg = new StackMapTableGen(mg,mg.getConstantPool());
        List blocks = sg.splitIntoBlocks(mg.getInstructionList(), mg.getConstantPool());
        assertTrue(blocks.size() == 1); //There is only one frame, because the method1 is empty
    }

    public void testStaticMethods() throws Exception{
        MethodGen mg = getMethod(StackMapTableTest.class, "staticMethod1");
        StackMapTableGen sg = new StackMapTableGen(mg,mg.getConstantPool());
        try{
            StackMap stackMap = sg.getStackMap();
            assertTrue(stackMap.getStackMap().length > 0);
        }catch(Exception e){
            e.printStackTrace();
        }
    }

}