Example usage for org.objectweb.asm.tree MethodNode MethodNode

List of usage examples for org.objectweb.asm.tree MethodNode MethodNode

Introduction

In this page you can find the example usage for org.objectweb.asm.tree MethodNode MethodNode.

Prototype

public MethodNode() 

Source Link

Document

Constructs an uninitialized MethodNode .

Usage

From source file:ca.weblite.mirah.ant.mirrors.ClassReader.java

/**
 * Generates the the mirah mirrors for a specific java source file.  This 
 * file must be a .java file.  It cannot be a directory.
 * //  ww  w  .j  a v a  2s .c o  m
 * @param javaSourceFile
 * @throws IOException 
 */
public void parse() throws IOException {

    File javaSourceFile = sourceFile;
    JavaCompiler compiler = JavacTool.create();
    MyFileObject[] fos = new MyFileObject[] { new MyFileObject(javaSourceFile) };

    JavacTask task = (JavacTask) compiler.getTask(null, null, null, null, null, Arrays.asList(fos));
    Iterable<? extends CompilationUnitTree> asts = task.parse();
    final Stack<Set<String>> typeParams = new Stack<Set<String>>();
    TreePathScanner scanner;
    scanner = new TreePathScanner() {

        private boolean isGenericType(String type) {
            Stack<Set> desk = new Stack<Set>();
            boolean found = false;
            while (!typeParams.empty()) {
                Set params = typeParams.pop();
                desk.push(params);
                if (params.contains(type)) {
                    found = true;

                    break;
                }

            }
            while (!desk.empty()) {
                typeParams.push(desk.pop());
            }
            return found;
        }

        String formatType(String type) {
            int pos = type.indexOf("<");
            if (pos >= 0) {
                type = type.substring(0, pos);
            }
            if (isGenericType(type)) {
                return "Object";
            }
            return type;
        }

        @Override
        public Object visitCompilationUnit(CompilationUnitTree cut, Object p) {
            PackageScope scope = new PackageScope(scopeStack.peek(), cut.getPackageName().toString());
            scope.addImport(scope.getPackageName() + ".*");
            scope.addImport("java.lang.*");
            scope.addImport("*");
            packageScope = scope;
            scopeStack.push(scope);
            return super.visitCompilationUnit(cut, p);

        }

        @Override
        public Object visitImport(ImportTree it, Object p) {

            String path = it.getQualifiedIdentifier().toString();
            packageScope.addImport(path);

            return super.visitImport(it, p);
        }

        private void decorateClassNode(ClassTree ct, ClassNode classNode) {
            int flags = getFlags(ct.getModifiers().getFlags());
            switch (ct.getKind()) {
            case INTERFACE:
                flags |= Opcodes.ACC_INTERFACE;
                break;

            case ENUM:
                flags |= Opcodes.ACC_ENUM;
                break;

            }
            classNode.access = flags;
            classNode.sourceFile = sourceFile.getPath();
            String extendsClause = "java.lang.Object";
            if (ct.getExtendsClause() != null) {
                extendsClause = ct.getExtendsClause().toString();
            }

            String superPath = scopeStack.peek().resolveName(extendsClause, false);

            ClassIndex.Node superNode = scopeStack.peek().getLoader().find(superPath);

            if (superNode == null) {
                throw new RuntimeException("Failed to find super class " + superPath);
            }

            classNode.superName = superNode.internalName;

            classNode.interfaces = new ArrayList<String>();
            String impl = ct.getImplementsClause().toString();
            if (!"".equals(impl)) {
                String[] interfaces = impl.split(",");
                for (String iface : interfaces) {
                    iface = iface.trim();
                    String ipath = scopeStack.peek().resolveName(iface, false);
                    ClassIndex.Node iNode = scopeStack.peek().getLoader().find(ipath);
                    if (iNode == null) {
                        throw new RuntimeException("Failed to load " + "interface " + ipath);
                    }

                    classNode.interfaces.add(iNode.internalName);
                }
            }
        }

        @Override
        public Object visitClass(ClassTree ct, Object p) {
            ClassScope clsScope = null;
            ClassNode currClassNode = null;
            if (scopeStack.peek() == packageScope) {
                String path = packageScope.getPackageName() + "." + ct.getSimpleName();
                ClassIndex.Node n = packageScope.getLoader().find(path);
                if (n == null) {
                    throw new RuntimeException("Failed to find class " + path);
                }
                node.name = n.internalName;
                currClassNode = node;
                decorateClassNode(ct, node);

                clsScope = new ClassScope(scopeStack.peek(), n);

            } else {
                // This must be an internal class
                ClassNode parentClass = classNodeStack.peek();
                if (parentClass.innerClasses == null) {
                    parentClass.innerClasses = new ArrayList<>();
                }
                String path = scopeStack.peek().resolveName(ct.getSimpleName().toString(), false);

                ClassIndex.Node n = packageScope.getLoader().find(path);
                if (n == null) {
                    throw new RuntimeException("Failed to find class " + path);
                }
                InnerClassNode innerNode = new InnerClassNode(n.internalName, parentClass.name, n.simpleName,
                        getFlags(ct.getModifiers().getFlags()));
                parentClass.innerClasses.add(innerNode);

                ClassNode cls = new ClassNode();
                cls.name = n.internalName;
                cls.outerClass = parentClass.name;

                decorateClassNode(ct, cls);
                clsScope = new ClassScope(scopeStack.peek(), n);
                currClassNode = cls;
            }

            scopeStack.push(clsScope);
            classNodeStack.push(currClassNode);
            Object out = super.visitClass(ct, p);
            classNodeStack.pop();
            scopeStack.pop();

            return out;

        }

        /**
         * Converts modifier flags from Javac Tree into int flags usable in 
         * TypeMirror
         * @param mods
         * @return 
         */
        int getFlags(Set<Modifier> mods) {
            int flags = 0;
            for (Modifier m : mods) {
                switch (m) {
                case ABSTRACT:
                    flags |= Opcodes.ACC_ABSTRACT;
                    break;
                case FINAL:
                    flags |= Opcodes.ACC_FINAL;
                    break;
                case PRIVATE:
                    flags |= Opcodes.ACC_PRIVATE;
                    break;
                case PROTECTED:
                    flags |= Opcodes.ACC_PROTECTED;
                    break;
                case PUBLIC:

                    flags |= Opcodes.ACC_PUBLIC;
                    break;
                case STATIC:
                    flags |= Opcodes.ACC_STATIC;
                    break;
                }
            }

            return flags;
        }

        @Override
        public Object visitVariable(final VariableTree vt, Object p) {
            String typeName = vt.getType().toString();
            String typePath = scopeStack.peek().resolveName(vt.getType().toString(), false);
            String typeDescriptor = scopeStack.peek().resolveName(vt.getType().toString(), true);
            String name = vt.getName().toString();
            int flags = getFlags(vt.getModifiers().getFlags());

            FieldNode fieldNode = new FieldNode(flags, name, typeDescriptor, null, null);

            ClassNode cls = classNodeStack.peek();
            if (cls.fields == null) {
                cls.fields = new ArrayList<FieldNode>();

            }
            cls.fields.add(fieldNode);

            return super.visitVariable(vt, p);
        }

        String generateMethodDescriptor(MethodTree mt) {
            StringBuilder sb = new StringBuilder();
            sb.append("(");
            for (VariableTree v : mt.getParameters()) {
                String type = scopeStack.peek().resolveName(v.getType().toString(), true);
                sb.append(type);

            }
            sb.append(")");
            String returnType = scopeStack.peek().resolveName(mt.getReturnType().toString(), true);
            sb.append(returnType);

            return sb.toString();
        }

        @Override
        public Object visitMethod(final MethodTree mt, Object p) {

            MethodNode m = new MethodNode();

            int flags = getFlags(mt.getModifiers().getFlags());
            m.access = flags;
            m.desc = generateMethodDescriptor(mt);
            m.name = mt.getName().toString();
            ClassNode cls = classNodeStack.peek();
            if (cls.methods == null) {
                cls.methods = new ArrayList<MethodNode>();
            }
            cls.methods.add(m);

            return mt;
        }
    };
    scanner.scan(asts, null);

}

From source file:cl.inria.stiq.instrumenter.BCIUtils.java

License:Open Source License

public static MethodNode cloneMethod(MethodNode aNode) {
    MethodNode theClone = new MethodNode();

    if (aNode.annotationDefault != null)
        throw new UnsupportedOperationException();

    theClone.name = aNode.name;//w w  w.  j a v a 2s.  c  o m
    theClone.signature = aNode.signature;
    theClone.access = aNode.access;
    theClone.desc = aNode.desc;
    theClone.exceptions = cloneList(aNode.exceptions);
    theClone.attrs = cloneList(aNode.attrs);
    theClone.maxLocals = aNode.maxLocals;
    theClone.maxStack = aNode.maxStack;

    ClonerMap theMap = new ClonerMap();
    theClone.instructions = cloneInstructions(theMap, aNode.instructions);
    theClone.localVariables = cloneLocalVariables(theMap, aNode.localVariables);
    theClone.tryCatchBlocks = cloneTryCatchBlocks(theMap, aNode.tryCatchBlocks);

    theClone.invisibleAnnotations = cloneList(aNode.invisibleAnnotations);
    theClone.invisibleParameterAnnotations = cloneAnnotations(aNode.invisibleParameterAnnotations);
    theClone.visibleAnnotations = cloneList(aNode.visibleAnnotations);
    theClone.visibleParameterAnnotations = cloneAnnotations(aNode.visibleParameterAnnotations);

    checkLabels(theClone);

    return theClone;
}

From source file:com.facebook.swift.codec.internal.compiler.byteCode.MethodDefinition.java

License:Apache License

public MethodNode getMethodNode() {
    MethodNode methodNode = new MethodNode();
    methodNode.access = toAccessModifier(access);
    methodNode.name = name;/*from  ww  w . j a va  2s  . c o  m*/
    methodNode.desc = methodDescription(returnType, parameters);

    // add generic signature if return type or any parameter is generic
    if (returnType.isGeneric() || any(parameters, ParameterizedType.isGenericType())) {
        methodNode.signature = genericMethodSignature(returnType, parameters);
    }

    methodNode.exceptions = new ArrayList<String>();
    for (ParameterizedType exception : exceptions) {
        methodNode.exceptions.add(exception.getClassName());
    }
    methodNode.instructions.add(instructionList);
    return methodNode;
}

From source file:com.google.template.soy.jbcsrc.BytecodeProducerTest.java

License:Apache License

public void testGenDoesntOverlapWithCompile() {
    BytecodeProducer producer = new BytecodeProducer() {
        @Override//from  ww  w. j av a2  s.  c o  m
        void doGen(CodeBuilder adapter) {
            BytecodeUtils.constant('c').gen(adapter);
        }
    };
    try {
        CodeBuilder adaterAdapter = new CodeBuilder(Opcodes.ACC_PUBLIC, BytecodeUtils.NULLARY_INIT,
                new MethodNode());
        producer.gen(adaterAdapter);
        fail();
    } catch (IllegalStateException e) {
        assertThat(e)
                .hasMessage("All bytecode producers should be created prior to code generation beginning.");
    }
}

From source file:com.google.template.soy.jbcsrc.restricted.BytecodeProducerTest.java

License:Apache License

@Test
public void testGenDoesntOverlapWithCompile() {
    BytecodeProducer producer = new BytecodeProducer() {
        @Override//from w w w.  ja v a  2 s .co  m
        protected void doGen(CodeBuilder adapter) {
            BytecodeUtils.constant('c').gen(adapter);
        }
    };
    try {
        CodeBuilder adaterAdapter = new CodeBuilder(Opcodes.ACC_PUBLIC, BytecodeUtils.NULLARY_INIT,
                new MethodNode());
        producer.gen(adaterAdapter);
        fail();
    } catch (IllegalStateException e) {
        assertThat(e).hasMessageThat()
                .contains("All bytecode producers should be constructed prior to code generation");
    }
}

From source file:com.googlecode.dex2jar.test.Issue71Test.java

License:Apache License

@Test
public void shortTest() {
    IrMethod irMethod = new IrMethod();
    irMethod.name = "test";
    irMethod.args = new Type[] {};
    irMethod.ret = Type.VOID_TYPE;
    Local a = nLocal("a");
    irMethod.locals.add(a);/*from w w  w.  j av a2  s . c  om*/

    irMethod.stmts.add(nAssign(a, nLong(0L)));
    irMethod.stmts.add(nAssign(a, nAdd(a, nLong(2))));

    Transformer[] tses = new Transformer[] { new ExceptionHandlerCurrectTransformer(), new LocalSplit(),
            new LocalRemove(), new LocalType(), new LocalCurrect() };
    Transformer endremove = new EndRemover();
    endremove.transform(irMethod);

    // indexLabelStmt4Debug(irMethod.stmts);

    for (Transformer ts : tses) {
        ts.transform(irMethod);
    }
    MethodNode node = new MethodNode();
    node.tryCatchBlocks = new ArrayList();
    new IrMethod2AsmMethod().convert(irMethod, node);
}

From source file:de.tuberlin.uebb.jbop.access.ConstructorBuilder.java

License:Open Source License

private static MethodNode createMethodNode(final ClassNode node) {
    final MethodNode constructor = new MethodNode();
    constructor.access = Opcodes.ACC_PUBLIC;
    constructor.name = "<init>";
    constructor.exceptions = Collections.emptyList();
    final InsnList list = new InsnList();
    // currently only call to noarg super constructor is supported
    final AbstractInsnNode nThis = new VarInsnNode(Opcodes.ALOAD, 0);
    final AbstractInsnNode nSuperConstructor = new MethodInsnNode(Opcodes.INVOKESPECIAL, node.superName,
            "<init>", "()V");
    list.add(nThis);/*ww w. j a  va2  s. co  m*/
    list.add(nSuperConstructor);
    constructor.instructions = list;
    return constructor;
}

From source file:de.tuberlin.uebb.jbop.optimizer.utils.predicates.OptimizablePredicateTest.java

License:Open Source License

/**
 * Tests that the Predicate returns false, if there aren't any annotations.
 *///from  w ww . j a va2  s .  c o  m
@Test
public void testEvaluateNullAnnotations() {
    // INIT

    // RUN
    final boolean isOptimizable = predicate.evaluate(new MethodNode());

    // ASSERT
    assertFalse(isOptimizable);
}

From source file:de.unisb.cs.st.javaslicer.tracer.instrumentation.TracingClassInstrumenter.java

License:Open Source License

protected void transformMethod(final ClassNode classNode, final MethodNode method,
        final ListIterator<MethodNode> methodIt) {
    final ReadMethod readMethod = new ReadMethod(this.readClass, method.access, method.name, method.desc,
            AbstractInstruction.getNextIndex());
    this.readClass.addMethod(readMethod);

    // do not instrument <clinit> methods (break (linear) control flow)
    // because these methods may call other methods, we have to pause tracing when they are entered
    if ("<clinit>".equals(method.name)) {
        new PauseTracingInstrumenter(null, this.tracer).transformMethod(method, methodIt,
                this.readClass.getName());
        return;//from   ww w. j a  va 2  s.c om
    }

    MethodNode oldMethod;
    // only copy the old method if it has more than 2000 instructions
    if (method.instructions.size() > 2000) {
        oldMethod = new MethodNode();
        copyMethod(method, oldMethod);
    } else {
        oldMethod = null;
    }

    new TracingMethodInstrumenter(this.tracer, readMethod, classNode, method).transform(methodIt);

    // test the size of the instrumented method
    final ClassWriter testCW = new ClassWriter(0);
    method.accept(testCW);
    final int byteCodeSize = testCW.toByteArray().length;
    if (byteCodeSize >= 1 << 16) {
        System.err.format(
                "WARNING: instrumented method \"%s.%s%s\" is larger than 64k bytes. undoing instrumentation.%n",
                this.readClass.getName(), readMethod.getName(), readMethod.getDesc());
        if (oldMethod == null) {
            System.err.println(
                    "ERROR: uninstrumented method had less than 2000 instructions, so we cannot roll back the instrumentation...");
        } else {
            System.err.format("#instructions old: %d; #instructions new: %d; size new: %d%n",
                    oldMethod.instructions.size(), method.instructions.size(), byteCodeSize);
            copyMethod(oldMethod, method);
        }
    }

    // reset the labels
    final Iterator<?> insnIt = method.instructions.iterator();
    while (insnIt.hasNext()) {
        final Object insn = insnIt.next();
        if (insn instanceof LabelNode)
            ((LabelNode) insn).resetLabel();
    }

}

From source file:io.airlift.drift.codec.internal.compiler.byteCode.MethodDefinition.java

License:Apache License

public MethodNode getMethodNode() {
    MethodNode methodNode = new MethodNode();
    methodNode.access = toAccessModifier(access);
    methodNode.name = name;/* w w w  . j a  v a  2s.co m*/
    methodNode.desc = methodDescription(returnType, parameters);

    // add generic signature if return type or any parameter is generic
    if (returnType.isGeneric() || parameters.stream().anyMatch(ParameterizedType::isGeneric)) {
        methodNode.signature = genericMethodSignature(returnType, parameters);
    }

    methodNode.exceptions = new ArrayList<String>();
    for (ParameterizedType exception : exceptions) {
        methodNode.exceptions.add(exception.getClassName());
    }
    methodNode.instructions.add(instructionList);
    return methodNode;
}