Example usage for org.objectweb.asm MethodVisitor visitJumpInsn

List of usage examples for org.objectweb.asm MethodVisitor visitJumpInsn

Introduction

In this page you can find the example usage for org.objectweb.asm MethodVisitor visitJumpInsn.

Prototype

public void visitJumpInsn(final int opcode, final Label label) 

Source Link

Document

Visits a jump instruction.

Usage

From source file:org.spongepowered.api.util.generator.event.factory.ClassGenerator.java

License:MIT License

private void generateConstructor(ClassWriter classWriter, String internalName, Class<?> parentType,
        ImmutableSet<? extends Property<Class<?>, Method>> properties) {
    MethodVisitor mv = classWriter.visitMethod(ACC_PUBLIC, "<init>", "(Ljava/util/Map;)V",
            "(Ljava/util/Map<Ljava/lang/String;Ljava/lang/Object;>;)V", null);
    mv.visitCode();/*from  ww w  . j a  v a  2 s.c  om*/

    // super()
    mv.visitVarInsn(ALOAD, 0);
    mv.visitMethodInsn(INVOKESPECIAL, Type.getInternalName(parentType), "<init>", "()V", false);

    for (Property<Class<?>, Method> property : properties) {
        if (!property.isLeastSpecificType()) {
            continue;
        }

        // Object value = map.get("key")
        mv.visitVarInsn(ALOAD, 1);
        mv.visitLdcInsn(property.getName());
        mv.visitMethodInsn(INVOKEINTERFACE, "java/util/Map", "remove", "(Ljava/lang/Object;)Ljava/lang/Object;",
                true);
        mv.visitVarInsn(ASTORE, 2);

        // Only if we have a null policy:
        // if (value == null) throw new NullPointerException(...)
        if (this.nullPolicy != NullPolicy.DISABLE_PRECONDITIONS) {
            boolean useNullTest = (((this.nullPolicy == NullPolicy.NON_NULL_BY_DEFAULT
                    && !this.hasNullable(property.getAccessor()))
                    || (this.nullPolicy == NullPolicy.NULL_BY_DEFAULT
                            && this.hasNonnull(property.getAccessor())))
                    && isRequired(property));

            if (useNullTest) {
                Label afterNullTest = new Label();
                mv.visitVarInsn(ALOAD, 2);
                mv.visitJumpInsn(IFNONNULL, afterNullTest);
                mv.visitTypeInsn(NEW, "java/lang/NullPointerException");
                mv.visitInsn(DUP);
                mv.visitLdcInsn("The property '" + property.getName() + "' was not provided!");
                mv.visitMethodInsn(INVOKESPECIAL, "java/lang/NullPointerException", "<init>",
                        "(Ljava/lang/String;)V", false);
                mv.visitInsn(ATHROW);
                mv.visitLabel(afterNullTest);
            }
        }

        final boolean hasUseField = getUseField(parentType, property.getName()) != null;

        Label afterPut = new Label();

        // if (value != null) {
        mv.visitVarInsn(ALOAD, 2);
        mv.visitJumpInsn(IFNULL, afterPut);

        // stack: -> this
        mv.visitVarInsn(ALOAD, 0);

        // ProperObject newValue = (ProperObject) value
        mv.visitVarInsn(ALOAD, 2);
        visitUnboxingMethod(mv, Type.getType(property.getType()));

        // this.field = newValue
        if (hasUseField) {
            mv.visitFieldInsn(PUTFIELD, Type.getInternalName(parentType), property.getName(),
                    Type.getDescriptor(property.getType()));
        } else {
            mv.visitFieldInsn(PUTFIELD, internalName, property.getName(),
                    Type.getDescriptor(property.getType()));
        }
        // }

        mv.visitLabel(afterPut);
    }

    // if (!map.isEmpty()) throw new IllegalArgumentException(...)
    {
        Label afterException = new Label();

        mv.visitVarInsn(ALOAD, 1);
        mv.visitMethodInsn(INVOKEINTERFACE, "java/util/Map", "isEmpty", "()Z", true);
        mv.visitJumpInsn(IFNE, afterException);

        mv.visitTypeInsn(NEW, "java/lang/IllegalArgumentException");
        mv.visitInsn(DUP);
        mv.visitTypeInsn(NEW, "java/lang/StringBuilder");
        mv.visitInsn(DUP);
        mv.visitMethodInsn(INVOKESPECIAL, "java/lang/StringBuilder", "<init>", "()V", false);
        mv.visitLdcInsn("Some parameters are unused: ");
        mv.visitMethodInsn(INVOKEVIRTUAL, "java/lang/StringBuilder", "append",
                "(Ljava/lang/String;)Ljava/lang/StringBuilder;", false);
        mv.visitVarInsn(ALOAD, 1);
        mv.visitMethodInsn(INVOKEINTERFACE, "java/util/Map", "keySet", "()Ljava/util/Set;", true);
        mv.visitMethodInsn(INVOKEVIRTUAL, "java/lang/StringBuilder", "append",
                "(Ljava/lang/Object;)Ljava/lang/StringBuilder;", false);
        mv.visitMethodInsn(INVOKEVIRTUAL, "java/lang/StringBuilder", "toString", "()Ljava/lang/String;", false);
        mv.visitMethodInsn(INVOKESPECIAL, "java/lang/IllegalArgumentException", "<init>",
                "(Ljava/lang/String;)V", false);
        mv.visitInsn(ATHROW);

        mv.visitLabel(afterException);
    }

    // super.init();
    if (hasDeclaredMethod(parentType, "init")) {
        mv.visitVarInsn(ALOAD, 0);
        mv.visitMethodInsn(INVOKESPECIAL, Type.getInternalName(parentType), "init", "()V", false);
    }

    mv.visitInsn(RETURN);
    mv.visitMaxs(0, 0);
    mv.visitEnd();
}

From source file:org.spongepowered.api.util.generator.event.factory.ClassGenerator.java

License:MIT License

/**
 * Generates a standard mutator method.//ww w . j a v  a  2s.  co  m
 *
 * <p>This method assumes that a standard field has been generated for the
 * provided {@link Property}</p>
 *
 * @param cw The {@link ClassWriter} to generate the mutator in
 * @param type The {@link Class} of the event that's having an
 *        implementation generated
 * @param internalName The internal name (slashes instead of periods in the
 *        package) of the new class being generated
 * @param fieldName The name of the field to mutate
 * @param fieldType The type of the field to mutate
 * @param property The {@link Property} containing the mutator method to
 *        generate for
 */
public static void generateMutator(ClassWriter cw, Class<?> type, String internalName, String fieldName,
        Class<?> fieldType, Property<Class<?>, Method> property) {
    Method mutator = property.getMutator().get();

    MethodVisitor mv = cw.visitMethod(ACC_PUBLIC, mutator.getName(), Type.getMethodDescriptor(mutator), null,
            null);
    mv.visitCode();
    mv.visitVarInsn(ALOAD, 0);
    mv.visitVarInsn(Type.getType(property.getType()).getOpcode(ILOAD), 1);

    if (property.getAccessor().getReturnType().equals(Optional.class)) {
        mv.visitMethodInsn(INVOKESTATIC, "java/util/Optional", "ofNullable",
                "(Ljava/lang/Object;)Ljava/util/Optional;", false);
    }

    if (!property.getType().isPrimitive()) {
        Class<?> mostSpecificReturn;
        try {
            mostSpecificReturn = type
                    .getMethod(property.getAccessor().getName(), property.getAccessor().getParameterTypes())
                    .getReturnType();
        } catch (NoSuchMethodException e) {
            throw new RuntimeException("If you're seeing this, than something's REALLY wrong");
        }
        Label afterException = new Label();
        mv.visitInsn(DUP);
        mv.visitJumpInsn(IFNULL, afterException);
        mv.visitInsn(DUP);
        mv.visitTypeInsn(INSTANCEOF, Type.getInternalName(mostSpecificReturn));

        mv.visitJumpInsn(IFNE, afterException);

        mv.visitTypeInsn(NEW, "java/lang/RuntimeException");
        mv.visitInsn(DUP);

        mv.visitTypeInsn(NEW, "java/lang/StringBuilder");
        mv.visitInsn(DUP);
        mv.visitMethodInsn(INVOKESPECIAL, "java/lang/StringBuilder", "<init>", "()V", false);

        mv.visitLdcInsn(
                "You've attempted to call the method '" + mutator.getName() + "' with an object of type ");
        mv.visitMethodInsn(INVOKEVIRTUAL, "java/lang/StringBuilder", "append",
                "(Ljava/lang/Object;)Ljava/lang/StringBuilder;", false);

        mv.visitVarInsn(Type.getType(property.getType()).getOpcode(ILOAD), 1);
        mv.visitMethodInsn(INVOKEVIRTUAL, "java/lang/Object", "getClass", "()Ljava/lang/Class;", false);
        mv.visitMethodInsn(INVOKEVIRTUAL, "java/lang/Class", "getName", "()Ljava/lang/String;", false);
        mv.visitMethodInsn(INVOKEVIRTUAL, "java/lang/StringBuilder", "append",
                "(Ljava/lang/Object;)Ljava/lang/StringBuilder;", false);

        mv.visitLdcInsn(", instead of " + mostSpecificReturn.getName()
                + ". Though you may have been listening for a supertype of this " + "event, it's actually a "
                + type.getName() + ". You need to ensure that the type of the event is what you think"
                + " it is, before calling the method (e.g TileEntityChangeEvent#setNewData");
        mv.visitMethodInsn(INVOKEVIRTUAL, "java/lang/StringBuilder", "append",
                "(Ljava/lang/Object;)Ljava/lang/StringBuilder;", false);
        mv.visitMethodInsn(INVOKEVIRTUAL, "java/lang/StringBuilder", "toString", "()Ljava/lang/String;", false);

        mv.visitMethodInsn(INVOKESPECIAL, "java/lang/RuntimeException", "<init>", "(Ljava/lang/String;)V",
                false);
        mv.visitInsn(ATHROW);

        mv.visitLabel(afterException);
    }

    mv.visitFieldInsn(PUTFIELD, internalName, property.getName(), Type.getDescriptor(property.getType()));
    mv.visitInsn(RETURN);
    mv.visitMaxs(0, 0);
    mv.visitEnd();
}

From source file:org.spongepowered.common.event.ClassEventListenerFactory.java

License:MIT License

private static byte[] generateClass(String name, Class<?> handle, Method method, Class<?> eventClass,
        Class<? extends EventFilter> filter) {
    name = name.replace('.', '/');
    final String handleName = Type.getInternalName(handle);
    final String handleDescriptor = Type.getDescriptor(handle);
    final String filterName = Type.getInternalName(filter);
    String eventDescriptor = "(";
    for (int i = 0; i < method.getParameterCount(); i++) {
        eventDescriptor += Type.getDescriptor(method.getParameterTypes()[i]);
    }//from w  w w .  j  a  va 2 s  .  c o  m
    eventDescriptor += ")V";

    ClassWriter cw = new ClassWriter(0);
    MethodVisitor mv;
    FieldVisitor fv;

    cw.visit(V1_6, ACC_PUBLIC + ACC_FINAL + ACC_SUPER, name, null, BASE_HANDLER, null);
    {
        fv = cw.visitField(ACC_PRIVATE + ACC_STATIC, "FILTER", "L" + filterName + ";", null, null);
        fv.visitEnd();
    }
    {
        mv = cw.visitMethod(ACC_STATIC, "<clinit>", "()V", null, null);
        mv.visitCode();
        Label l0 = new Label();
        Label l1 = new Label();
        Label l2 = new Label();
        mv.visitTryCatchBlock(l0, l1, l2, "java/lang/Exception");
        mv.visitLabel(l0);
        mv.visitLdcInsn(Type.getType(filter));
        mv.visitMethodInsn(INVOKEVIRTUAL, "java/lang/Class", "newInstance", "()Ljava/lang/Object;", false);
        mv.visitTypeInsn(CHECKCAST, filterName);
        mv.visitFieldInsn(PUTSTATIC, name, "FILTER", "L" + filterName + ";");
        mv.visitLabel(l1);
        Label l3 = new Label();
        mv.visitJumpInsn(GOTO, l3);
        mv.visitLabel(l2);
        mv.visitFrame(F_SAME1, 0, null, 1, new Object[] { "java/lang/Exception" });
        mv.visitVarInsn(ASTORE, 0);
        mv.visitMethodInsn(INVOKESTATIC, Type.getInternalName(SpongeImpl.class), "getLogger",
                "()" + Type.getDescriptor(Logger.class), false);
        mv.visitLdcInsn("Error initializing event filter");
        mv.visitVarInsn(ALOAD, 0);
        mv.visitMethodInsn(INVOKEINTERFACE, Type.getInternalName(Logger.class), "error",
                "(Ljava/lang/String;Ljava/lang/Throwable;)V", true);
        Label l5 = new Label();
        mv.visitLabel(l5);
        mv.visitLineNumber(220, l5);
        mv.visitInsn(ACONST_NULL);
        mv.visitFieldInsn(PUTSTATIC, name, "FILTER", "L" + filterName + ";");
        mv.visitLabel(l3);
        mv.visitFrame(F_SAME, 0, null, 0, null);
        mv.visitInsn(RETURN);
        mv.visitMaxs(3, 1);
        mv.visitEnd();
    }
    {
        mv = cw.visitMethod(ACC_PUBLIC, "<init>", '(' + handleDescriptor + ")V", null, null);
        mv.visitCode();
        mv.visitVarInsn(ALOAD, 0);
        mv.visitVarInsn(ALOAD, 1);
        mv.visitMethodInsn(INVOKESPECIAL, BASE_HANDLER, "<init>", "(Ljava/lang/Object;)V", false);
        mv.visitInsn(RETURN);
        mv.visitMaxs(2, 2);
        mv.visitEnd();
    }
    {
        mv = cw.visitMethod(ACC_PUBLIC, "handle", HANDLE_METHOD_DESCRIPTOR, null,
                new String[] { "java/lang/Exception" });
        mv.visitCode();
        mv.visitFieldInsn(GETSTATIC, name, "FILTER", "L" + filterName + ";");
        mv.visitVarInsn(ALOAD, 1);
        mv.visitMethodInsn(INVOKEINTERFACE, Type.getInternalName(EventFilter.class), "filter",
                FILTER_DESCRIPTOR, true);
        mv.visitVarInsn(ASTORE, 2);
        mv.visitVarInsn(ALOAD, 2);
        Label l2 = new Label();
        mv.visitJumpInsn(IFNULL, l2);
        mv.visitVarInsn(ALOAD, 0);
        mv.visitFieldInsn(GETFIELD, name, "handle", "Ljava/lang/Object;");
        mv.visitTypeInsn(CHECKCAST, handleName);
        for (int i = 0; i < method.getParameterCount(); i++) {
            mv.visitVarInsn(ALOAD, 2);
            mv.visitIntInsn(BIPUSH, i);
            mv.visitInsn(AALOAD);
            mv.visitTypeInsn(CHECKCAST, Type.getInternalName(method.getParameterTypes()[i]));
        }
        mv.visitMethodInsn(INVOKEVIRTUAL, handleName, method.getName(), eventDescriptor, false);
        mv.visitLabel(l2);
        mv.visitFrame(F_APPEND, 1, new Object[] { "[Ljava/lang/Object;" }, 0, null);
        mv.visitInsn(RETURN);
        mv.visitMaxs(4, 3);
        mv.visitEnd();
    }
    cw.visitEnd();

    return cw.toByteArray();
}

From source file:org.spongepowered.common.event.filter.delegate.CancellationEventFilterDelegate.java

License:MIT License

@Override
public int write(String name, ClassWriter cw, MethodVisitor mv, Method method, int locals) {
    if (!Cancellable.class.isAssignableFrom(method.getParameters()[0].getType())) {
        throw new IllegalStateException(
                "Attempted to filter a non-cancellable event type by its cancellation status");
    }/* w  ww . j  ava 2s. c o m*/
    if (this.anno.value() == Tristate.UNDEFINED) {
        return locals;
    }
    mv.visitVarInsn(ALOAD, 1);
    mv.visitTypeInsn(CHECKCAST, Type.getInternalName(Cancellable.class));
    mv.visitMethodInsn(INVOKEINTERFACE, Type.getInternalName(Cancellable.class), "isCancelled", "()Z", true);
    Label success = new Label();
    if (this.anno.value() == Tristate.TRUE) {
        mv.visitJumpInsn(IFNE, success);
    } else {
        mv.visitJumpInsn(IFEQ, success);
    }
    mv.visitInsn(ACONST_NULL);
    mv.visitInsn(ARETURN);
    mv.visitLabel(success);
    return locals;
}

From source file:org.spongepowered.common.event.filter.delegate.GetterFilterSourceDelegate.java

License:MIT License

@Override
public Tuple<Integer, Integer> write(ClassWriter cw, MethodVisitor mv, Method method, Parameter param,
        int local) {
    Class<?> targetType = param.getType();
    Class<?> eventClass = method.getParameterTypes()[0];
    String targetMethod = this.anno.value();
    Method targetMethodObj = null;

    try {/*from  ww w.ja  v  a2s  .  c om*/
        targetMethodObj = eventClass.getMethod(targetMethod);
    } catch (NoSuchMethodException e) {
        throw new IllegalArgumentException(
                String.format("Method %s specified by getter annotation was not found in type %s", targetMethod,
                        eventClass.getName()));
    }

    if (targetMethodObj.getParameterCount() != 0) {
        throw new IllegalArgumentException("Method " + targetMethodObj.toGenericString()
                + " specified by getter annotation has non-zero parameter count");
    }
    if (!targetMethodObj.getReturnType().equals(Optional.class)
            && !targetMethodObj.getReturnType().isAssignableFrom(targetType)) {
        throw new IllegalArgumentException(
                "Method " + targetMethodObj.toGenericString() + " does not return the correct type. Expected: "
                        + targetType.getName() + " Found: " + targetMethodObj.getReturnType().getName());
    }

    Type returnType = Type.getReturnType(targetMethodObj);
    Class<?> declaringClass = targetMethodObj.getDeclaringClass();
    mv.visitVarInsn(ALOAD, 1);
    mv.visitTypeInsn(CHECKCAST, Type.getInternalName(declaringClass));
    int op = declaringClass.isInterface() ? INVOKEINTERFACE : INVOKEVIRTUAL;
    mv.visitMethodInsn(op, Type.getInternalName(declaringClass), targetMethod,
            "()" + returnType.getDescriptor(), declaringClass.isInterface());
    int paramLocal = local++;
    mv.visitVarInsn(returnType.getOpcode(ISTORE), paramLocal);
    if (!targetMethodObj.getReturnType().isPrimitive()) {
        Label failure = new Label();
        Label success = new Label();
        if (Optional.class.equals(targetMethodObj.getReturnType()) && !Optional.class.equals(targetType)) {
            // Unwrap the optional
            mv.visitVarInsn(ALOAD, paramLocal);

            mv.visitMethodInsn(INVOKEVIRTUAL, "java/util/Optional", "isPresent", "()Z", false);
            mv.visitJumpInsn(IFEQ, failure);

            mv.visitVarInsn(ALOAD, paramLocal);
            mv.visitMethodInsn(INVOKEVIRTUAL, "java/util/Optional", "get", "()Ljava/lang/Object;", false);
            mv.visitInsn(DUP);
            mv.visitVarInsn(ASTORE, paramLocal);
        } else {
            mv.visitVarInsn(returnType.getOpcode(ILOAD), paramLocal);
        }
        mv.visitTypeInsn(INSTANCEOF, Type.getInternalName(targetType));
        mv.visitJumpInsn(IFNE, success);
        mv.visitLabel(failure);
        mv.visitInsn(ACONST_NULL);
        mv.visitInsn(ARETURN);
        mv.visitLabel(success);
    }

    return new Tuple<>(local, paramLocal);
}

From source file:org.spongepowered.common.event.filter.delegate.SubtypeFilterDelegate.java

License:MIT License

@Override
public int write(String name, ClassWriter cw, MethodVisitor mv, Method method, int locals) {

    mv.visitVarInsn(ALOAD, 0);//from   w w  w  .  j  a  va2s  . com
    mv.visitFieldInsn(GETFIELD, name, "classes", "Ljava/util/Set;");
    mv.visitVarInsn(ALOAD, 1);
    mv.visitMethodInsn(INVOKEVIRTUAL, "java/lang/Object", "getClass", "()Ljava/lang/Class;", false);
    mv.visitMethodInsn(INVOKEINTERFACE, "java/util/Set", "contains", "(Ljava/lang/Object;)Z", true);
    Label success = new Label();
    mv.visitJumpInsn(getJumpOp(), success);
    mv.visitInsn(ACONST_NULL);
    mv.visitInsn(ARETURN);
    mv.visitLabel(success);
    return locals;
}

From source file:org.spongepowered.despector.emitter.bytecode.statement.BytecodeIfEmitter.java

License:Open Source License

private void emitInverse(BytecodeEmitterContext ctx, Condition cond) {
    MethodVisitor mv = ctx.getMethodVisitor();
    if (cond instanceof CompareCondition) {
        CompareCondition cmp = (CompareCondition) cond;
        ctx.emitInstruction(cmp.getLeft(), null);
        ctx.emitInstruction(cmp.getRight(), null);
        switch (cmp.getOperator()) {
        case NOT_EQUAL:
            mv.visitJumpInsn(Opcodes.IF_ACMPEQ, this.end);
            break;
        case EQUAL:
            mv.visitJumpInsn(Opcodes.IF_ACMPNE, this.end);
            break;
        default:/*from  w ww.  j ava  2s  .c  o  m*/
            throw new IllegalStateException("Unsupported compare operator: " + cmp.getOperator().name());
        }
    } else if (cond instanceof BooleanCondition) {
        BooleanCondition bool = (BooleanCondition) cond;
        ctx.emitInstruction(bool.getConditionValue(), null);
        if (bool.isInverse()) {
            mv.visitJumpInsn(Opcodes.IFNE, this.end);
        } else {
            mv.visitJumpInsn(Opcodes.IFEQ, this.end);
        }
    } else {
        throw new IllegalStateException();
    }
}

From source file:org.spongepowered.eventimplgen.factory.ClassGenerator.java

License:MIT License

private void generateConstructor(ClassWriter classWriter, String internalName, CtTypeReference<?> parentType,
        List<Property> properties) {

    List<? extends Property> requiredProperties = getRequiredProperties(properties);

    StringBuilder builder = new StringBuilder();
    builder.append("(");
    for (Property property : requiredProperties) {
        builder.append(getTypeDescriptor(property.getType()));
    }//from  w w  w .  ja v  a2s  . com
    builder.append(")V");

    String methodDesc = builder.toString();

    MethodVisitor mv = classWriter.visitMethod(0, "<init>", methodDesc, null, null);
    mv.visitCode();

    // super()
    mv.visitVarInsn(ALOAD, 0);
    mv.visitMethodInsn(INVOKESPECIAL, ClassGenerator.getInternalName(parentType.getQualifiedName()), "<init>",
            "()V", false);

    // 0 is 'this', parameters start at 1
    for (int i = 0, paramIndex = 1; i < requiredProperties.size(); i++, paramIndex++) {
        Property property = requiredProperties.get(i);

        Type type = Type.getType(getTypeDescriptor(property.getType()));
        int loadOpcode = type.getOpcode(Opcodes.ILOAD);

        boolean isPrimitive = property.getType().isPrimitive();

        // Only if we have a null policy:
        // if (value == null) throw new NullPointerException(...)
        if (this.nullPolicy != NullPolicy.DISABLE_PRECONDITIONS) {
            boolean useNullTest = !isPrimitive && (((this.nullPolicy == NullPolicy.NON_NULL_BY_DEFAULT
                    && !this.hasNullable(property.getAccessor()))
                    || (this.nullPolicy == NullPolicy.NULL_BY_DEFAULT
                            && this.hasNonnull(property.getAccessor())))
                    && isRequired(property));

            if (useNullTest) {
                Label afterNullTest = new Label();
                mv.visitVarInsn(loadOpcode, paramIndex);
                mv.visitJumpInsn(IFNONNULL, afterNullTest);
                mv.visitTypeInsn(NEW, "java/lang/NullPointerException");
                mv.visitInsn(DUP);
                mv.visitLdcInsn("The property '" + property.getName() + "' was not provided!");
                mv.visitMethodInsn(INVOKESPECIAL, "java/lang/NullPointerException", "<init>",
                        "(Ljava/lang/String;)V", false);
                mv.visitInsn(ATHROW);
                mv.visitLabel(afterNullTest);
            }
        }

        final boolean hasUseField = getUseField(parentType, property.getName()) != null;

        // stack: -> this
        mv.visitVarInsn(ALOAD, 0);

        // ProperObject newValue = (ProperObject) value
        mv.visitVarInsn(loadOpcode, paramIndex);
        //visitUnboxingMethod(mv, Type.getType(property.getType()));

        // this.field = newValue

        String desc = getTypeDescriptor(property.getLeastSpecificType());

        if (hasUseField) {
            mv.visitFieldInsn(PUTFIELD, getInternalName(parentType.getQualifiedName()), property.getName(),
                    desc);
        } else {
            mv.visitFieldInsn(PUTFIELD, internalName, property.getName(), desc);
        }
        // }

        if (type.equals(Type.LONG_TYPE) || type.equals(Type.DOUBLE_TYPE)) {
            paramIndex++; // Skip empty slot
        }
    }

    // super.init();
    if (hasDeclaredMethod(parentType, "init")) {
        mv.visitVarInsn(ALOAD, 0);
        mv.visitMethodInsn(INVOKESPECIAL, getInternalName(parentType.getQualifiedName()), "init", "()V", false);
    }

    mv.visitInsn(RETURN);
    mv.visitMaxs(0, 0);
    mv.visitEnd();
}

From source file:org.spongepowered.eventimplgen.factory.ClassGenerator.java

License:MIT License

/**
 * Generates a standard mutator method.// ww  w.  j a  va 2s.c o  m
 *
 * <p>This method assumes that a standard field has been generated for the
 * provided {@link Property}</p>
 *
 * @param cw The {@link ClassWriter} to generate the mutator in
 * @param type The {@link Class} of the event that's having an
 *        implementation generated
 * @param internalName The internal name (slashes instead of periods in the
 *        package) of the new class being generated
 * @param fieldName The name of the field to mutate
 * @param fieldType The type of the field to mutate
 * @param property The {@link Property} containing the mutator method to
 *        generate for
 */
public static void generateMutator(ClassWriter cw, CtType<?> type, String internalName, String fieldName,
        CtType<?> fieldType, Property property) {
    CtMethod<?> mutator = property.getMutator().get();

    MethodVisitor mv = cw.visitMethod(ACC_PUBLIC, mutator.getSimpleName(), getDescriptor(mutator), null, null);
    mv.visitCode();
    mv.visitVarInsn(ALOAD, 0);
    mv.visitVarInsn(Type.getType(getTypeDescriptor(property.getType())).getOpcode(ILOAD), 1);

    if (property.getAccessor().getType().getQualifiedName().equals(Optional.class.getName())) {
        mv.visitMethodInsn(INVOKESTATIC, "java/util/Optional", "ofNullable",
                "(Ljava/lang/Object;)Ljava/util/Optional;", false);
    }

    if (!property.getType().isPrimitive() && !property.getMostSpecificType().getQualifiedName()
            .equals(property.getLeastSpecificType().getQualifiedName())) {
        CtTypeReference<?> mostSpecificReturn = property.getMostSpecificType();
        //CtMethod<?> specific =  type.getMethod(property.getAccessor().getSimpleName(), getParameterTypes(property.getAccessor()));

        Label afterException = new Label();
        mv.visitInsn(DUP);
        mv.visitJumpInsn(IFNULL, afterException);
        mv.visitInsn(DUP);
        mv.visitTypeInsn(INSTANCEOF, getInternalName(mostSpecificReturn.getQualifiedName()));

        mv.visitJumpInsn(IFNE, afterException);

        mv.visitTypeInsn(NEW, "java/lang/RuntimeException");
        mv.visitInsn(DUP);

        mv.visitTypeInsn(NEW, "java/lang/StringBuilder");
        mv.visitInsn(DUP);
        mv.visitMethodInsn(INVOKESPECIAL, "java/lang/StringBuilder", "<init>", "()V", false);

        mv.visitLdcInsn("You've attempted to call the method '" + mutator.getSimpleName()
                + "' with an object of type ");
        mv.visitMethodInsn(INVOKEVIRTUAL, "java/lang/StringBuilder", "append",
                "(Ljava/lang/Object;)Ljava/lang/StringBuilder;", false);

        mv.visitVarInsn(Type.getType(getTypeDescriptor(property.getType())).getOpcode(ILOAD), 1);
        mv.visitMethodInsn(INVOKEVIRTUAL, "java/lang/Object", "getClass", "()Ljava/lang/Class;", false);
        mv.visitMethodInsn(INVOKEVIRTUAL, "java/lang/Class", "getName", "()Ljava/lang/String;", false);
        mv.visitMethodInsn(INVOKEVIRTUAL, "java/lang/StringBuilder", "append",
                "(Ljava/lang/Object;)Ljava/lang/StringBuilder;", false);

        mv.visitLdcInsn(", instead of " + mostSpecificReturn.getSimpleName()
                + ". Though you may have been listening for a supertype of this " + "event, it's actually a "
                + type.getQualifiedName() + ". You need to ensure that the type of the event is what you think"
                + " it is, before calling the method (e.g TileEntityChangeEvent#setNewData");
        mv.visitMethodInsn(INVOKEVIRTUAL, "java/lang/StringBuilder", "append",
                "(Ljava/lang/Object;)Ljava/lang/StringBuilder;", false);
        mv.visitMethodInsn(INVOKEVIRTUAL, "java/lang/StringBuilder", "toString", "()Ljava/lang/String;", false);

        mv.visitMethodInsn(INVOKESPECIAL, "java/lang/RuntimeException", "<init>", "(Ljava/lang/String;)V",
                false);
        mv.visitInsn(ATHROW);

        mv.visitLabel(afterException);
    }

    mv.visitFieldInsn(PUTFIELD, internalName, property.getName(),
            getTypeDescriptor(property.getLeastSpecificType()));
    mv.visitInsn(RETURN);
    mv.visitMaxs(0, 0);
    mv.visitEnd();
}

From source file:org.spongepowered.lantern.event.filter.delegate.AllCauseFilterSourceDelegate.java

License:MIT License

@Override
protected void insertCheck(MethodVisitor mv, Parameter param, Class<?> targetType, int local) {
    if (this.anno.ignoreEmpty()) {
        mv.visitVarInsn(ALOAD, local);/*from ww w  .j  a v a 2 s.c  o m*/
        Label success = new Label();
        mv.visitMethodInsn(INVOKEINTERFACE, "java/util/List", "isEmpty", "()Z", true);
        mv.visitJumpInsn(IFEQ, success);
        mv.visitInsn(ACONST_NULL);
        mv.visitInsn(ARETURN);
        mv.visitLabel(success);
    }
}