Example usage for org.objectweb.asm.tree TypeInsnNode getOpcode

List of usage examples for org.objectweb.asm.tree TypeInsnNode getOpcode

Introduction

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

Prototype

public int getOpcode() 

Source Link

Document

Returns the opcode of this instruction.

Usage

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

License:Open Source License

private void transformTypeInsn(final TypeInsnNode insn) {
    if (insn.getOpcode() == ANEWARRAY) {
        int newObjectIdSeqIndex = this.tracer.newLongTraceSequence();
        transformArrayAllocation(new TypeInstruction(this.readMethod, insn.getOpcode(), this.currentLine,
                insn.desc, newObjectIdSeqIndex), newObjectIdSeqIndex);
    } else if (insn.getOpcode() == NEW) {
        // after a NEW, we store the sequence number in the ThreadTracer object.
        // after the constructor has been called (which is guaranteed), its
        // id is written to the stored sequence number
        final int newObjectIdSeqIndex = this.tracer.newLongTraceSequence();
        final AbstractInstruction instruction = new TypeInstruction(this.readMethod, insn.getOpcode(),
                this.currentLine, insn.desc, newObjectIdSeqIndex);
        if (!this.instructionIterator.hasNext()) {
            if (this.tracer.debug)
                Transformer.printMethod(System.err, this.methodNode);
            throw new TracerException("Bytecode of method " + this.classNode.name + "." + this.methodNode.name
                    + " has unsupported form (constructor call does not immediately follow NEW instruction). "
                    + "Maybe it was compiled for JRE < 1.5?");
        } else if (this.instructionIterator.next().getOpcode() != DUP) {
            // this code handles a special kind of object initialization, which is sometimes used
            // in a catch block which throws a new exceptions which encapsulates the old one.
            // the bytecode of this construct looks like this:
            //   NEW <newExceptionType>
            //   DUP_X1
            //   SWAP
            //   INVOKESPECIAL <newExceptionType>.<init> (Ljava/lang/Throwable;)V
            //   ATHROW
            this.instructionIterator.previous();
            AbstractInsnNode dup_x1 = this.instructionIterator.next();

            boolean matches = false;
            if (dup_x1.getOpcode() == DUP_X1 && this.instructionIterator.hasNext()) {
                AbstractInsnNode swap = this.instructionIterator.next();
                if (swap.getOpcode() == SWAP && this.instructionIterator.hasNext()) {
                    matches = true;/*from   www  .  ja va2s . c o  m*/
                }
            }

            if (matches) {
                // add another DUP_X1 before the existing one
                this.instructionIterator.previous();
                this.instructionIterator.previous();
                this.instructionIterator.add(new InsnNode(DUP_X1));
                //if (this.tracer.debug) {
                //    System.err.println("Added DUP_X1 at position " + this.instructionIterator.previousIndex() + "!");
                //    Transformer.printMethod(System.err, this.methodNode);
                //}
            } else {
                if (this.tracer.debug)
                    Transformer.printMethod(System.err, this.methodNode);
                throw new TracerException("Bytecode of method " + this.classNode.name + "."
                        + this.methodNode.name
                        + " has unsupported form (constructor call does not immediately follow NEW instruction). "
                        + "Maybe it was compiled for JRE < 1.5?");
            }
        } else {
            this.instructionIterator.previous();
            this.instructionIterator.add(new InsnNode(DUP));
        }
        ++this.outstandingInitializations;
        // modified code of registerInstruction():
        this.readMethod.addInstruction(instruction);
        this.instructionIterator.previous();
        this.instructionIterator.add(new VarInsnNode(ALOAD, this.tracerLocalVarIndex));
        this.instructionIterator.add(getIntConstInsn(instruction.getIndex()));
        this.instructionIterator.add(getIntConstInsn(newObjectIdSeqIndex));
        this.instructionIterator.add(new MethodInsnNode(INVOKEINTERFACE,
                Type.getInternalName(ThreadTracer.class), "objectAllocated", "(II)V", true));
        this.instructionIterator.next();
        ++TracingMethodInstrumenter.statsInstructions;
    } else {
        registerInstruction(
                new TypeInstruction(this.readMethod, insn.getOpcode(), this.currentLine, insn.desc, -1),
                InstructionType.UNSAFE);
    }
}

From source file:edu.mit.streamjit.util.bytecode.MethodResolver.java

License:Open Source License

private void interpret(TypeInsnNode insn, FrameState frame, BBInfo block) {
    Klass k = getKlassByInternalName(insn.desc);
    ReferenceType t = typeFactory.getReferenceType(k);
    switch (insn.getOpcode()) {
    case Opcodes.NEW:
        UninitializedValue newValue = newValues.get(insn);
        assert newValue != null;
        assert newValue.getType().equals(t);
        frame.stack.push(newValue);/*from w w  w  .j a v  a  2  s .  c  o m*/
        break;
    case Opcodes.CHECKCAST:
        CastInst c = new CastInst(t, frame.stack.pop());
        block.block.instructions().add(c);
        frame.stack.push(c);
        break;
    case Opcodes.INSTANCEOF:
        InstanceofInst ioi = new InstanceofInst(t, frame.stack.pop());
        block.block.instructions().add(ioi);
        frame.stack.push(ioi);
        break;
    case Opcodes.ANEWARRAY:
        ArrayType at = typeFactory.getArrayType(module.getArrayKlass(k, 1));
        NewArrayInst nai = new NewArrayInst(at, frame.stack.pop());
        block.block.instructions().add(nai);
        frame.stack.push(nai);
        break;
    default:
        throw new UnsupportedOperationException("" + insn.getOpcode());
    }
}

From source file:nova.core.wrapper.mc.forge.v17.asm.lib.InsnListPrinter.java

License:Open Source License

private void _visitInsn(AbstractInsnNode insn) {
    switch (insn.getType()) {
    case 0://from  w  w  w .  j a va2 s  . c  o m
        visitInsn(insn.getOpcode());
        break;
    case 1:
        IntInsnNode iinsn = (IntInsnNode) insn;
        visitIntInsn(iinsn.getOpcode(), iinsn.operand);
        break;
    case 2:
        VarInsnNode vinsn = (VarInsnNode) insn;
        visitVarInsn(vinsn.getOpcode(), vinsn.var);
        break;
    case 3:
        TypeInsnNode tinsn = (TypeInsnNode) insn;
        visitTypeInsn(tinsn.getOpcode(), tinsn.desc);
        break;
    case 4:
        FieldInsnNode finsn = (FieldInsnNode) insn;
        visitFieldInsn(finsn.getOpcode(), finsn.owner, finsn.name, finsn.desc);
        break;
    case 5:
        MethodInsnNode minsn = (MethodInsnNode) insn;
        visitMethodInsn(minsn.getOpcode(), minsn.owner, minsn.name, minsn.desc);
        break;
    case 6:
        InvokeDynamicInsnNode idinsn = (InvokeDynamicInsnNode) insn;
        visitInvokeDynamicInsn(idinsn.name, idinsn.desc, idinsn.bsm, idinsn.bsmArgs);
        break;
    case 7:
        JumpInsnNode jinsn = (JumpInsnNode) insn;
        visitJumpInsn(jinsn.getOpcode(), jinsn.label.getLabel());
        break;
    case 8:
        LabelNode linsn = (LabelNode) insn;
        visitLabel(linsn.getLabel());
        break;
    case 9:
        LdcInsnNode ldcinsn = (LdcInsnNode) insn;
        visitLdcInsn(ldcinsn.cst);
        break;
    case 10:
        IincInsnNode iiinsn = (IincInsnNode) insn;
        visitIincInsn(iiinsn.var, iiinsn.incr);
        break;
    case 11:
        TableSwitchInsnNode tsinsn = (TableSwitchInsnNode) insn;
        Label[] tslables = new Label[tsinsn.labels.size()];
        for (int i = 0; i < tslables.length; i++) {
            tslables[i] = tsinsn.labels.get(i).getLabel();
        }
        visitTableSwitchInsn(tsinsn.min, tsinsn.max, tsinsn.dflt.getLabel(), tslables);
        break;
    case 12:
        LookupSwitchInsnNode lsinsn = (LookupSwitchInsnNode) insn;
        Label[] lslables = new Label[lsinsn.labels.size()];
        for (int i = 0; i < lslables.length; i++) {
            lslables[i] = lsinsn.labels.get(i).getLabel();
        }
        int[] lskeys = new int[lsinsn.keys.size()];
        for (int i = 0; i < lskeys.length; i++) {
            lskeys[i] = lsinsn.keys.get(i);
        }
        visitLookupSwitchInsn(lsinsn.dflt.getLabel(), lskeys, lslables);
        break;
    case 13:
        MultiANewArrayInsnNode ainsn = (MultiANewArrayInsnNode) insn;
        visitMultiANewArrayInsn(ainsn.desc, ainsn.dims);
        break;
    case 14:
        FrameNode fnode = (FrameNode) insn;
        switch (fnode.type) {
        case -1:
        case 0:
            visitFrame(fnode.type, fnode.local.size(), fnode.local.toArray(), fnode.stack.size(),
                    fnode.stack.toArray());
            break;
        case 1:
            visitFrame(fnode.type, fnode.local.size(), fnode.local.toArray(), 0, null);
            break;
        case 2:
            visitFrame(fnode.type, fnode.local.size(), null, 0, null);
            break;
        case 3:
            visitFrame(fnode.type, 0, null, 0, null);
            break;
        case 4:
            visitFrame(fnode.type, 0, null, 1, fnode.stack.toArray());
        }
        break;
    case 15:
        LineNumberNode lnode = (LineNumberNode) insn;
        visitLineNumber(lnode.line, lnode.start.getLabel());
        break;
    }
}

From source file:org.evosuite.instrumentation.testability.transformer.BooleanArrayIndexTransformer.java

License:Open Source License

@Override
protected AbstractInsnNode transformTypeInsnNode(MethodNode mn, TypeInsnNode typeNode) {
    if (frames == null)
        return typeNode;

    if (typeNode.getOpcode() == Opcodes.CHECKCAST) {
        Frame current = frames[mn.instructions.indexOf(typeNode)];
        int size = current.getStackSize();
        if (current.getStack(size - 1) == BooleanArrayInterpreter.INT_ARRAY) {
            BooleanTestabilityTransformation.logger.info("Array is of boolean type, changing CHECKCAST to [I");
            TypeInsnNode replacement = new TypeInsnNode(Opcodes.CHECKCAST, "[I");
            mn.instructions.insertBefore(typeNode, replacement);
            mn.instructions.remove(typeNode);
            return replacement;
        }/*w ww . ja  v a2 s. c o m*/
    }
    return typeNode;
}

From source file:org.evosuite.instrumentation.testability.transformer.InstanceOfTransformer.java

License:Open Source License

@Override
protected AbstractInsnNode transformTypeInsnNode(MethodNode mn, TypeInsnNode typeNode) {
    if (typeNode.getOpcode() == Opcodes.INSTANCEOF) {
        TransformationStatistics.transformInstanceOf();

        // Depending on the class version we need a String or a Class
        // TODO: This needs to be class version of the class that's loaded, not cn!
        //ClassReader reader;
        int version = 48;
        /*/*from  www . j  av  a 2  s  .c  o  m*/
        String name = typeNode.desc.replace('/', '.');
        try {
           reader = new ClassReader(name);
           ClassNode parent = new ClassNode();
           reader.accept(parent, ClassReader.SKIP_CODE);
           version = parent.version;
        } catch (IOException e) {
           TestabilityTransformation.logger.info("Error reading class " + name);
        }
        */
        if (version >= 49) {
            if (!typeNode.desc.startsWith("[")) {
                LdcInsnNode lin = new LdcInsnNode(Type.getType("L" + typeNode.desc + ";"));
                mn.instructions.insertBefore(typeNode, lin);
            } else {
                LdcInsnNode lin = new LdcInsnNode(Type.getType(typeNode.desc + ";"));
                mn.instructions.insertBefore(typeNode, lin);
            }
        } else {
            LdcInsnNode lin = new LdcInsnNode(typeNode.desc.replace('/', '.'));
            mn.instructions.insertBefore(typeNode, lin);
            MethodInsnNode n = new MethodInsnNode(Opcodes.INVOKESTATIC, Type.getInternalName(Class.class),
                    "forName", Type.getMethodDescriptor(Type.getType(Class.class),
                            new Type[] { Type.getType(String.class) }));
            mn.instructions.insertBefore(typeNode, n);
        }
        MethodInsnNode n = new MethodInsnNode(Opcodes.INVOKESTATIC, Type.getInternalName(BooleanHelper.class),
                "instanceOf", Type.getMethodDescriptor(Type.INT_TYPE,
                        new Type[] { Type.getType(Object.class), Type.getType(Class.class) }));
        mn.instructions.insertBefore(typeNode, n);
        mn.instructions.remove(typeNode);
        return n;
    }
    return typeNode;
}

From source file:org.evosuite.testcarver.instrument.Instrumenter.java

License:Open Source License

@SuppressWarnings("unchecked")
private void addFieldRegistryRegisterCall(final MethodNode methodNode) {
    AbstractInsnNode ins = null;//from w ww .j av a  2 s .c  om
    ListIterator<AbstractInsnNode> iter = methodNode.instructions.iterator();

    int numInvokeSpecials = 0; // number of invokespecial calls before actual constructor call

    while (iter.hasNext()) {
        ins = iter.next();

        if (ins instanceof MethodInsnNode) {
            MethodInsnNode mins = (MethodInsnNode) ins;
            if (ins.getOpcode() == Opcodes.INVOKESPECIAL) {
                if (mins.name.startsWith("<init>")) {
                    if (numInvokeSpecials == 0) {
                        break;
                    } else {
                        numInvokeSpecials--;
                    }
                }
            }
        } else if (ins instanceof TypeInsnNode) {
            TypeInsnNode typeIns = (TypeInsnNode) ins;
            if (typeIns.getOpcode() == Opcodes.NEW || typeIns.getOpcode() == Opcodes.NEWARRAY) {
                numInvokeSpecials++;
            }
        }
    }

    final InsnList instructions = new InsnList();

    instructions.add(new VarInsnNode(Opcodes.ALOAD, 0));
    instructions.add(new MethodInsnNode(Opcodes.INVOKESTATIC, PackageInfo.getNameWithSlash(FieldRegistry.class),
            "register", "(Ljava/lang/Object;)V"));

    methodNode.instructions.insert(ins, instructions);
}

From source file:org.evosuite.testcarver.instrument.Instrumenter.java

License:Open Source License

/**
 *    public int myMethod(int i)// w  w w . j av  a  2  s .c o  m
   {
 try
 {
    return _sw_prototype_original_myMethod(i)
 }
 finally
 {
    Capturer.enable();
 }
   }
        
 * @param classNode
 * @param className
 * @param methodNode
 */
@SuppressWarnings("unchecked")
private MethodNode wrapMethod(final ClassNode classNode, final String className, final MethodNode methodNode) {
    methodNode.maxStack += 4;

    // create wrapper for original method
    final MethodNode wrappingMethodNode = new MethodNode(methodNode.access, methodNode.name, methodNode.desc,
            methodNode.signature,
            (String[]) methodNode.exceptions.toArray(new String[methodNode.exceptions.size()]));
    wrappingMethodNode.maxStack = methodNode.maxStack;

    // assign annotations to wrapping method
    wrappingMethodNode.visibleAnnotations = methodNode.visibleAnnotations;
    wrappingMethodNode.visibleParameterAnnotations = methodNode.visibleParameterAnnotations;

    // remove annotations from wrapped method to avoid wrong behavior controlled by annotations
    methodNode.visibleAnnotations = null;
    methodNode.visibleParameterAnnotations = null;

    // rename original method
    methodNode.access = TransformerUtil.modifyVisibility(methodNode.access, Opcodes.ACC_PRIVATE);

    final LabelNode l0 = new LabelNode();
    final LabelNode l1 = new LabelNode();
    final LabelNode l2 = new LabelNode();

    final InsnList wInstructions = wrappingMethodNode.instructions;

    if ("<init>".equals(methodNode.name)) {
        // wrap a constructor 

        methodNode.name = WRAP_NAME_PREFIX + "init" + WRAP_NAME_PREFIX;

        // move call to other constructors to new method
        AbstractInsnNode ins = null;
        ListIterator<AbstractInsnNode> iter = methodNode.instructions.iterator();

        int numInvokeSpecials = 0; // number of invokespecial calls before actual constructor call

        while (iter.hasNext()) {
            ins = iter.next();
            iter.remove();
            wInstructions.add(ins);

            if (ins instanceof MethodInsnNode) {
                MethodInsnNode mins = (MethodInsnNode) ins;
                if (ins.getOpcode() == Opcodes.INVOKESPECIAL) {
                    if (mins.name.startsWith("<init>")) {
                        if (numInvokeSpecials == 0) {
                            break;
                        } else {
                            numInvokeSpecials--;
                        }
                    }
                }
            } else if (ins instanceof TypeInsnNode) {
                TypeInsnNode typeIns = (TypeInsnNode) ins;
                if (typeIns.getOpcode() == Opcodes.NEW || typeIns.getOpcode() == Opcodes.NEWARRAY) {
                    numInvokeSpecials++;
                }
            }
        }
    } else {
        methodNode.name = WRAP_NAME_PREFIX + methodNode.name;
    }

    int varReturnValue = 0;

    final Type returnType = Type.getReturnType(methodNode.desc);

    if (returnType.equals(Type.VOID_TYPE)) {
        wrappingMethodNode.tryCatchBlocks.add(new TryCatchBlockNode(l0, l1, l1, "java/lang/Throwable"));

    } else {

        wrappingMethodNode.tryCatchBlocks.add(new TryCatchBlockNode(l0, l1, l2, "java/lang/Throwable"));

        //--- create "Object returnValue = null;"

        if (!TransformerUtil.isStatic(methodNode.access)) {
            // load "this"
            varReturnValue++;
        }

        // consider method arguments to find right variable index
        final Type[] argTypes = Type.getArgumentTypes(methodNode.desc);
        for (int i = 0; i < argTypes.length; i++) {
            varReturnValue++;

            // long/double take two registers
            if (argTypes[i].equals(Type.LONG_TYPE) || argTypes[i].equals(Type.DOUBLE_TYPE)) {
                varReturnValue++;
            }
        }

        // push NULL on the stack and initialize variable for return value for it
        wInstructions.add(new InsnNode(Opcodes.ACONST_NULL));
        wInstructions.add(new VarInsnNode(Opcodes.ASTORE, varReturnValue));
    }

    int var = 0;

    // --- L0
    wInstructions.add(l0);

    wInstructions.add(this.addCaptureCall(TransformerUtil.isStatic(methodNode.access), className,
            wrappingMethodNode.name, wrappingMethodNode.desc, Type.getArgumentTypes(methodNode.desc)));

    // --- construct call to wrapped methode

    if (!TransformerUtil.isStatic(methodNode.access)) {
        // load "this" to call method
        wInstructions.add(new VarInsnNode(Opcodes.ALOAD, 0));
        var++;
    }

    final Type[] argTypes = Type.getArgumentTypes(methodNode.desc);
    for (int i = 0; i < argTypes.length; i++) {
        this.addLoadInsn(wInstructions, argTypes[i], var++);

        // long/double take two registers
        if (argTypes[i].equals(Type.LONG_TYPE) || argTypes[i].equals(Type.DOUBLE_TYPE)) {
            var++;
        }
    }

    if (TransformerUtil.isStatic(methodNode.access)) {
        wInstructions.add(
                new MethodInsnNode(Opcodes.INVOKESTATIC, classNode.name, methodNode.name, methodNode.desc));
    } else {
        wInstructions.add(
                new MethodInsnNode(Opcodes.INVOKEVIRTUAL, classNode.name, methodNode.name, methodNode.desc));
    }

    var++;

    if (returnType.equals(Type.VOID_TYPE)) {
        wInstructions.add(new JumpInsnNode(Opcodes.GOTO, l2));

        // --- L1

        wInstructions.add(l1);

        wInstructions.add(new FrameNode(Opcodes.F_SAME1, 0, null, 1, new Object[] { "java/lang/Throwable" }));

        wInstructions.add(new VarInsnNode(Opcodes.ASTORE, --var));

        this.addCaptureEnableStatement(className, methodNode, wInstructions, -1);

        wInstructions.add(new VarInsnNode(Opcodes.ALOAD, var));
        wInstructions.add(new InsnNode(Opcodes.ATHROW));

        // FIXME <--- DUPLICATE CODE

        // --- L2

        wInstructions.add(l2);
        wInstructions.add(new FrameNode(Opcodes.F_SAME, 0, null, 0, null));

        this.addCaptureEnableStatement(className, methodNode, wInstructions, -1);

        wInstructions.add(new InsnNode(Opcodes.RETURN));
    } else {
        // construct store of the wrapped method call's result

        this.addBoxingStmt(wInstructions, returnType);

        wInstructions.add(new VarInsnNode(Opcodes.ASTORE, varReturnValue));
        wInstructions.add(new VarInsnNode(Opcodes.ALOAD, varReturnValue));

        this.addUnBoxingStmt(wInstructions, returnType);

        final int storeOpcode = returnType.getOpcode(Opcodes.ISTORE);
        wInstructions.add(new VarInsnNode(storeOpcode, ++var)); // might be only var

        // --- L1

        wInstructions.add(l1);

        this.addCaptureEnableStatement(className, methodNode, wInstructions, varReturnValue);

        // construct load of the wrapped method call's result
        int loadOpcode = returnType.getOpcode(Opcodes.ILOAD);
        wInstructions.add(new VarInsnNode(loadOpcode, var));

        // construct return of the wrapped method call's result
        this.addReturnInsn(wInstructions, returnType);

        //---- L2

        wInstructions.add(l2);

        wInstructions.add(
                new FrameNode(Opcodes.F_FULL, 2, new Object[] { className, this.getInternalName(returnType) },
                        1, new Object[] { "java/lang/Throwable" }));
        wInstructions.add(new VarInsnNode(Opcodes.ASTORE, --var));

        this.addCaptureEnableStatement(className, methodNode, wInstructions, varReturnValue);

        wInstructions.add(new VarInsnNode(Opcodes.ALOAD, var));
        wInstructions.add(new InsnNode(Opcodes.ATHROW));
    }
    transformWrapperCalls(methodNode);
    return wrappingMethodNode;
}

From source file:org.jacoco.core.internal.instr.CondyProbeArrayStrategyTest.java

License:Open Source License

@Test
public void should_store_instance_using_condy_and_checkcast() {
    final MethodNode m = new MethodNode();
    final int maxStack = strategy.storeInstance(m, false, 1);

    assertEquals(1, maxStack);/*  w w  w. j a va  2 s .com*/

    final ConstantDynamic constantDynamic = (ConstantDynamic) ((LdcInsnNode) m.instructions.get(0)).cst;
    assertEquals("$jacocoData", constantDynamic.getName());
    assertEquals("Ljava/lang/Object;", constantDynamic.getDescriptor());

    final Handle bootstrapMethod = constantDynamic.getBootstrapMethod();
    assertEquals(Opcodes.H_INVOKESTATIC, bootstrapMethod.getTag());
    assertEquals("ClassName", bootstrapMethod.getOwner());
    assertEquals("$jacocoInit", bootstrapMethod.getName());
    assertEquals("(Ljava/lang/invoke/MethodHandles$Lookup;Ljava/lang/String;Ljava/lang/Class;)[Z",
            bootstrapMethod.getDesc());
    assertTrue(bootstrapMethod.isInterface());

    final TypeInsnNode castInstruction = (TypeInsnNode) m.instructions.get(1);
    assertEquals(Opcodes.CHECKCAST, castInstruction.getOpcode());
    assertEquals("[Z", castInstruction.desc);

    final VarInsnNode storeInstruction = (VarInsnNode) m.instructions.get(2);
    assertEquals(Opcodes.ASTORE, storeInstruction.getOpcode());
    assertEquals(1, storeInstruction.var);

    assertEquals(3, m.instructions.size());
}

From source file:org.jooby.internal.apitool.BytecodeRouteParser.java

License:Apache License

private java.lang.reflect.Type parameterType(final ClassLoader loader, final AbstractInsnNode n) {
    if (n instanceof MethodInsnNode) {
        MethodInsnNode node = (MethodInsnNode) n;
        if (mutantValue().test(node)) {
            /** value(); intValue(); booleanValue(); */
            return TypeDescriptorParser.parse(loader, node.desc);
        } else if (mutantToSomething().test(node) || getOrCreateKotlinClass().test(node)) {
            /** to(String.class); toOptional; toList(); */
            String owner = Type.getReturnType(node.desc).getClassName();
            AbstractInsnNode prev = node.getPrevious();
            if (prev instanceof FieldInsnNode && ((MethodInsnNode) n).name.equals("toEnum")) {
                /** toEnum(Letter.A); */
                return loadType(loader, ((FieldInsnNode) prev).owner);
            }//from  www.  j a va  2s  .co  m
            java.lang.reflect.Type toType = String.class;
            if (prev instanceof LdcInsnNode) {
                /** to(Foo.class); */
                Object cst = ((LdcInsnNode) prev).cst;
                if (cst instanceof Type) {
                    toType = loadType(loader, ((Type) cst).getClassName());
                }
            } else if (prev instanceof FieldInsnNode) {
                toType = loadType(loader, ((FieldInsnNode) prev).owner);
            }
            // JoobyKt.toOptional
            AbstractInsnNode next = node.getNext();
            if (next instanceof MethodInsnNode) {
                String joobyKt = ((MethodInsnNode) next).owner;
                String methodName = ((MethodInsnNode) next).name;
                if ("toOptional".equals(methodName) && "org/jooby/JoobyKt".equals(joobyKt)) {
                    owner = Optional.class.getName();
                }
            }

            Set<String> skipOwners = ImmutableSet.of(Object.class.getName(), Enum.class.getName(),
                    "kotlin.reflect.KClass");
            if (skipOwners.contains(owner)) {
                return toType;
            }

            /** toList(Foo.class); */
            return Types.newParameterizedType(loadType(loader, owner), toType);
        }
    } else if (n instanceof VarInsnNode) {
        return new Insn<>(null, n).prev().filter(is(MethodInsnNode.class)).findFirst()
                .map(MethodInsnNode.class::cast).filter(file()).map(m -> {
                    return m.name.equals("files") ? Types.newParameterizedType(List.class, File.class)
                            : File.class;
                }).orElse(Object.class);
    } else if (n instanceof TypeInsnNode) {
        TypeInsnNode typeInsn = (TypeInsnNode) n;
        if (typeInsn.getOpcode() == Opcodes.CHECKCAST) {
            return loadType(loader, typeInsn.desc);
        }
    } else if (n != null && Opcodes.DUP == n.getOpcode()) {
        // Kotlin 1.2.x
        // mv.visitInsn(DUP);
        // mv.visitLdcInsn("req.param(\"p1\")");
        // mv.visitMethodInsn(INVOKESTATIC, "kotlin/jvm/internal/Intrinsics", "checkExpressionValueIsNotNull", "(Ljava/lang/Object;Ljava/lang/String;)V", false);
        // mv.visitMethodInsn(INVOKESTATIC, "org/jooby/JoobyKt", "getValue", "(Lorg/jooby/Mutant;)Ljava/lang/String;", false);
        AbstractInsnNode next = new Insn<>(null, n).next().filter(MethodInsnNode.class::isInstance).skip(1)
                .findFirst().orElse(null);
        java.lang.reflect.Type result = parameterType(loader, next);
        if (result == Object.class) {
            next = new Insn<>(null, n).next().filter(TypeInsnNode.class::isInstance).findFirst().orElse(null);
            result = parameterType(loader, next);
        }
        return result;
    } else if (n instanceof FieldInsnNode) {
        AbstractInsnNode next = n.getNext();
        if (next instanceof MethodInsnNode) {
            if (((MethodInsnNode) next).name.equals("toOptional")) {
                return Types.newParameterizedType(Optional.class, loadType(loader, ((FieldInsnNode) n).owner));
            } else if (((MethodInsnNode) next).name.equals("getOrCreateKotlinClass")) {
                return loadType(loader, ((FieldInsnNode) n).owner);
            }
        }
    }
    return Object.class;
}

From source file:org.lambdamatic.analyzer.ast.LambdaExpressionReader.java

License:Open Source License

/**
 * Reads the given {@link TypeInsnNode} instruction.
 * //  w  w  w. j a v a  2  s  .c om
 * @param typeInsnNode the instruction to read
 * @param expressionStack the expression stack to put on or pop from.
 * @param localVariables the local variables
 */
private static void readTypeInstruction(final TypeInsnNode typeInsnNode,
        final Stack<Expression> expressionStack, final LocalVariables localVariables) {
    switch (typeInsnNode.getOpcode()) {
    case Opcodes.NEW:
        final Type instanceType = Type.getObjectType(typeInsnNode.desc);
        final ObjectInstanciation objectVariable = new ObjectInstanciation(getType(instanceType));
        expressionStack.push(objectVariable);
        break;
    case Opcodes.ANEWARRAY:
        final Type parameterType = Type.getObjectType(typeInsnNode.desc);
        final NumberLiteral arrayLength = (NumberLiteral) expressionStack.pop();
        final ArrayVariable arrayVariable = new ArrayVariable(getArrayType(parameterType),
                arrayLength.getValue().intValue());
        expressionStack.push(arrayVariable);
        break;
    default:
        LOGGER.warn("TypeInsnNode with OpCode {} was ignored.", typeInsnNode.getOpcode());
    }
}