Example usage for org.objectweb.asm.commons GeneratorAdapter cast

List of usage examples for org.objectweb.asm.commons GeneratorAdapter cast

Introduction

In this page you can find the example usage for org.objectweb.asm.commons GeneratorAdapter cast.

Prototype

public void cast(final Type from, final Type to) 

Source Link

Document

Generates the instructions to cast a numerical value from one type to another.

Usage

From source file:io.datakernel.codegen.ExpressionArithmeticOp.java

License:Apache License

@Override
public Type load(Context ctx) {
    GeneratorAdapter g = ctx.getGeneratorAdapter();
    Expression leftVar = left;//from  ww w  . java 2s  .  co  m
    Expression rightVar = right;
    if (isWrapperType(leftVar.type(ctx))) {
        leftVar.load(ctx);
        g.unbox(unwrap(leftVar.type(ctx)));
        VarLocal newLeftVar = newLocal(ctx, unwrap(leftVar.type(ctx)));
        newLeftVar.storeLocal(g);
        leftVar = newLeftVar;
    }
    if (isWrapperType(rightVar.type(ctx))) {
        rightVar.load(ctx);
        g.unbox(unwrap(rightVar.type(ctx)));
        VarLocal newRightVar = newLocal(ctx, unwrap(rightVar.type(ctx)));
        newRightVar.storeLocal(g);
        rightVar = newRightVar;
    }
    Type resultType = getType(
            unifyArithmeticTypes(getJavaType(leftVar.type(ctx)), getJavaType(rightVar.type(ctx))));
    if (leftVar.type(ctx) != resultType) {
        leftVar.load(ctx);
        g.cast(leftVar.type(ctx), resultType);
        VarLocal newLeftVar = newLocal(ctx, resultType);
        newLeftVar.storeLocal(g);
        leftVar = newLeftVar;
    }
    if (rightVar.type(ctx) != resultType) {
        rightVar.load(ctx);
        g.cast(rightVar.type(ctx), resultType);
        VarLocal newRightVar = newLocal(ctx, resultType);
        newRightVar.storeLocal(g);
        rightVar = newRightVar;
    }
    leftVar.load(ctx);
    rightVar.load(ctx);
    g.visitInsn(resultType.getOpcode(op.opCode));
    return resultType;
}

From source file:io.datakernel.codegen.ExpressionBitOp.java

License:Apache License

private Type loadOther(Context ctx) {
    GeneratorAdapter g = ctx.getGeneratorAdapter();
    Type type = type(ctx);// w ww. ja  v  a2 s  .com

    left.load(ctx);
    if (!left.type(ctx).equals(type)) {
        g.cast(left.type(ctx), type);
    }

    right.load(ctx);
    if (!right.type(ctx).equals(type)) {
        g.cast(right.type(ctx), type);
    }

    g.visitInsn(type.getOpcode(op.opCode));
    return type;
}

From source file:io.datakernel.codegen.ExpressionBitOp.java

License:Apache License

private Type loadShift(Context ctx) {
    GeneratorAdapter g = ctx.getGeneratorAdapter();

    VarLocal varIntShift = newLocal(ctx, Type.INT_TYPE);
    right.load(ctx);//from ww  w  .jav a2s . co  m
    switch (right.type(ctx).getSort()) {
    case Type.BOOLEAN:
    case Type.SHORT:
    case Type.CHAR:
    case Type.BYTE:
        g.cast(right.type(ctx), Type.INT_TYPE);
        break;
    case Type.INT:
        break;
    default:
        throw new IllegalArgumentException();
    }
    varIntShift.store(ctx);

    left.load(ctx);
    int valueSort = left.type(ctx).getSort();

    if (valueSort == Type.LONG) {
        varIntShift.load(ctx);
        g.visitInsn(Type.LONG_TYPE.getOpcode(op.opCode));
        return Type.LONG_TYPE;
    }

    if (valueSort == Type.INT) {
        varIntShift.load(ctx);
        g.visitInsn(Type.INT_TYPE.getOpcode(op.opCode));
        return Type.INT_TYPE;
    }

    if (valueSort == Type.BYTE || valueSort == Type.SHORT || valueSort == Type.CHAR
            || valueSort == Type.BOOLEAN) {
        g.cast(left.type(ctx), Type.INT_TYPE);
        varIntShift.load(ctx);

        g.visitInsn(Type.INT_TYPE.getOpcode(op.opCode));
        return Type.INT_TYPE;
    }

    throw new IllegalArgumentException();
}

From source file:io.datakernel.codegen.ExpressionNeg.java

License:Apache License

@Override
public Type load(Context ctx) {
    GeneratorAdapter g = ctx.getGeneratorAdapter();
    int sort = arg.type(ctx).getSort();
    arg.load(ctx);/*  ww  w .ja  v a  2 s.c o m*/

    if (sort == Type.DOUBLE || sort == Type.FLOAT || sort == Type.LONG || sort == Type.INT) {
        g.math(GeneratorAdapter.NEG, arg.type(ctx));
        return arg.type(ctx);
    }
    if (sort == Type.BYTE || sort == Type.SHORT || sort == Type.CHAR) {
        g.cast(arg.type(ctx), INT_TYPE);
        g.math(GeneratorAdapter.NEG, INT_TYPE);
        return arg.type(ctx);
    }

    if (sort == Type.BOOLEAN) {
        Label labelTrue = new Label();
        Label labelExit = new Label();
        g.push(true);
        g.ifCmp(BOOLEAN_TYPE, GeneratorAdapter.EQ, labelTrue);
        g.push(true);
        g.goTo(labelExit);

        g.mark(labelTrue);
        g.push(false);

        g.mark(labelExit);
        return INT_TYPE;
    }

    throw new RuntimeException(format("%s is not primitive. %s",
            getJavaType(ctx.getClassLoader(), arg.type(ctx)), exceptionInGeneratedClass(ctx)));
}

From source file:io.datakernel.codegen.Utils.java

License:Apache License

public static void cast(Context ctx, Type type, Type targetType) {
    GeneratorAdapter g = ctx.getGeneratorAdapter();

    if (type.equals(targetType)) {
        return;//  ww  w. j av  a  2 s .c om
    }

    if (targetType == Type.VOID_TYPE) {
        if (type.getSize() == 1)
            g.pop();
        if (type.getSize() == 2)
            g.pop2();
        return;
    }

    if (type == Type.VOID_TYPE) {
        throw new RuntimeException(format("Can't cast VOID_TYPE to %s. %s", targetType.getClassName(),
                exceptionInGeneratedClass(ctx)));
    }

    if (type.equals(ctx.getThisType())) {
        final Class<?> javaType = getJavaType(ctx.getClassLoader(), targetType);
        for (Class<?> aClass : ctx.getOtherClasses()) {
            if (javaType.isAssignableFrom(aClass)) {
                return;
            }
        }
        throw new RuntimeException(format("Can't cast self %s to %s, %s", type.getClassName(),
                targetType.getClassName(), exceptionInGeneratedClass(ctx)));
    }

    if (!type.equals(ctx.getThisType()) && !targetType.equals(ctx.getThisType())
            && getJavaType(ctx.getClassLoader(), targetType)
                    .isAssignableFrom(getJavaType(ctx.getClassLoader(), type))) {
        return;
    }

    if (targetType.equals(getType(Object.class)) && isPrimitiveType(type)) {
        g.box(type);
        g.cast(wrap(type), getType(Object.class));
        return;
    }

    if ((isPrimitiveType(type) || isWrapperType(type))
            && (isPrimitiveType(targetType) || isWrapperType(targetType))) {

        Type targetTypePrimitive = isPrimitiveType(targetType) ? targetType : unwrap(targetType);

        if (isWrapperType(type)) {
            g.invokeVirtual(type, primitiveValueMethod(targetType));
            return;
        }

        assert isPrimitiveType(type);

        if (type != targetTypePrimitive) {
            g.cast(type, targetTypePrimitive);
        }

        if (isWrapperType(targetType)) {
            g.valueOf(targetTypePrimitive);
        }

        return;
    }

    g.checkCast(targetType);
}

From source file:lucee.transformer.bytecode.cast.CastFloat.java

License:Open Source License

/**
 * @see lucee.transformer.bytecode.expression.Expression#_writeOut(org.objectweb.asm.commons.GeneratorAdapter, int)
 *///www .  j a v a2s . com
public Type _writeOut(BytecodeContext bc, int mode) throws BytecodeException {

    GeneratorAdapter adapter = bc.getAdapter();

    if (expr instanceof OpDouble) {
        ((OpDouble) expr).writeOutDouble(bc, MODE_VALUE);
        if (mode == MODE_VALUE)
            adapter.invokeStatic(Types.CASTER, Methods.METHOD_TO_FLOAT_VALUE_FROM_DOUBLE);
        else
            adapter.invokeStatic(Types.CASTER, Methods.METHOD_TO_FLOAT_FROM_DOUBLE);
    } else if (expr instanceof ExprBoolean) {
        expr.writeOut(bc, MODE_VALUE);
        if (mode == MODE_VALUE)
            adapter.invokeStatic(Types.CASTER, Methods.METHOD_TO_FLOAT_VALUE_FROM_BOOLEAN);
        else
            adapter.invokeStatic(Types.CASTER, Methods.METHOD_TO_FLOAT_FROM_BOOLEAN);

    } else if (expr instanceof ExprFloat) {
        expr.writeOut(bc, mode);
    } else if (expr instanceof ExprDouble) {
        expr.writeOut(bc, MODE_VALUE);
        if (mode == MODE_VALUE)
            adapter.invokeStatic(Types.CASTER, Methods.METHOD_TO_FLOAT_VALUE_FROM_DOUBLE);
        else
            adapter.invokeStatic(Types.CASTER, Methods.METHOD_TO_FLOAT_FROM_DOUBLE);
    } else if (expr instanceof ExprString) {
        expr.writeOut(bc, MODE_REF);
        if (mode == MODE_VALUE)
            adapter.invokeStatic(Types.CASTER, Methods.METHOD_TO_FLOAT_VALUE_FROM_STRING);
        else
            adapter.invokeStatic(Types.CASTER, Methods.METHOD_TO_FLOAT_FROM_STRING);
    } else {
        Type rtn = expr.writeOut(bc, mode);
        if (mode == MODE_VALUE) {
            if (!Types.isPrimitiveType(rtn)) {
                adapter.invokeStatic(Types.CASTER, Methods.METHOD_TO_FLOAT_VALUE);
            } else if (Types.DOUBLE_VALUE.equals(rtn)) {
                adapter.cast(Types.DOUBLE_VALUE, Types.FLOAT_VALUE);
            } else if (Types.FLOAT_VALUE.equals(rtn)) {
            } else if (Types.BOOLEAN_VALUE.equals(rtn)) {
                adapter.invokeStatic(Types.CASTER, Methods.METHOD_TO_FLOAT_VALUE_FROM_BOOLEAN);
            } else {
                adapter.invokeStatic(Types.CASTER,
                        new Method("toRef", Types.toRefType(rtn), new Type[] { rtn }));
                adapter.invokeStatic(Types.CASTER, Methods.METHOD_TO_FLOAT_VALUE);
            }
            return Types.FLOAT_VALUE;
        } else if (Types.isPrimitiveType(rtn)) {
            if (Types.DOUBLE_VALUE.equals(rtn)) {
                adapter.invokeStatic(Types.CASTER, Methods.METHOD_TO_FLOAT_FROM_DOUBLE);
            } else if (Types.FLOAT_VALUE.equals(rtn)) {
                adapter.invokeStatic(Types.CASTER, Methods.METHOD_TO_FLOAT_FROM_FLOAT);
            } else if (Types.BOOLEAN_VALUE.equals(rtn)) {
                adapter.invokeStatic(Types.CASTER, Methods.METHOD_TO_FLOAT_FROM_BOOLEAN);
            } else {
                adapter.invokeStatic(Types.CASTER,
                        new Method("toRef", Types.toRefType(rtn), new Type[] { rtn }));
                adapter.invokeStatic(Types.CASTER, Methods.METHOD_TO_FLOAT);
            }
            return Types.FLOAT;
        }
        //else {
        if (!Types.FLOAT.equals(rtn))
            adapter.invokeStatic(Types.CASTER, Methods.METHOD_TO_FLOAT);
        return Types.FLOAT;
        //}
    }

    if (mode == MODE_VALUE)
        return Types.FLOAT_VALUE;
    return Types.FLOAT;
}

From source file:lucee.transformer.bytecode.cast.CastInt.java

License:Open Source License

/**
 * @see lucee.transformer.bytecode.expression.Expression#_writeOut(org.objectweb.asm.commons.GeneratorAdapter, int)
 *///from  w ww .j  a va 2s.  c om
public Type _writeOut(BytecodeContext bc, int mode) throws BytecodeException {
    GeneratorAdapter adapter = bc.getAdapter();

    if (expr instanceof ExprString) {
        expr.writeOut(bc, MODE_REF);
        if (mode == MODE_VALUE)
            adapter.invokeStatic(Types.CASTER, Methods.METHOD_TO_INT_VALUE_FROM_STRING);
        else
            adapter.invokeStatic(Types.CASTER, Methods.METHOD_TO_INTEGER_FROM_STRING);
    } else {
        Type rtn = expr.writeOut(bc, mode);
        if (mode == MODE_VALUE) {
            if (!Types.isPrimitiveType(rtn)) {
                adapter.invokeStatic(Types.CASTER, Methods.METHOD_TO_INT_VALUE);
            } else if (Types.BOOLEAN_VALUE.equals(rtn)) {
                adapter.invokeStatic(Types.CASTER, Methods.METHOD_TO_INT_VALUE_FROM_BOOLEAN);
            } else if (Types.SHORT_VALUE.equals(rtn)) {
                // No Cast needed
            } else if (Types.FLOAT_VALUE.equals(rtn)) {
                adapter.cast(Types.FLOAT_VALUE, Types.INT_VALUE);
            } else if (Types.LONG_VALUE.equals(rtn)) {
                adapter.cast(Types.LONG_VALUE, Types.INT_VALUE);
            } else if (Types.DOUBLE_VALUE.equals(rtn)) {
                adapter.cast(Types.DOUBLE_VALUE, Types.INT_VALUE);
            } else if (Types.INT_VALUE.equals(rtn)) {
                // No Cast needed
            } else {
                adapter.invokeStatic(Types.CASTER,
                        new Method("toRef", Types.toRefType(rtn), new Type[] { rtn }));
                adapter.invokeStatic(Types.CASTER, Methods.METHOD_TO_INT_VALUE);
            }
            return Types.INT_VALUE;

        } else if (Types.isPrimitiveType(rtn)) {
            if (Types.DOUBLE_VALUE.equals(rtn)) {
                adapter.invokeStatic(Types.CASTER, Methods.METHOD_TO_INTEGER_FROM_DOUBLE);
            } else if (Types.BOOLEAN_VALUE.equals(rtn)) {
                adapter.invokeStatic(Types.CASTER, Methods.METHOD_TO_INTEGER_FROM_BOOLEAN);
            } else {
                adapter.invokeStatic(Types.CASTER,
                        new Method("toRef", Types.toRefType(rtn), new Type[] { rtn }));
                adapter.invokeStatic(Types.CASTER, Methods.METHOD_TO_INTEGER);
            }
            return Types.INTEGER;
        }

        if (!Types.INTEGER.equals(rtn))
            adapter.invokeStatic(Types.CASTER, Methods.METHOD_TO_INTEGER);
        return Types.INTEGER;
    }

    if (mode == MODE_VALUE)
        return Types.INT_VALUE;
    return Types.INTEGER;
}

From source file:lucee.transformer.bytecode.statement.tag.TagHelper.java

License:Open Source License

/**
 * writes out the tag/*from  w w w .  j  ava  2 s  .c o  m*/
 * @param tag
 * @param bc
 * @param doReuse
 * @throws BytecodeException
 */
public static void writeOut(Tag tag, BytecodeContext bc, boolean doReuse, final FlowControlFinal fcf)
        throws BytecodeException {
    final GeneratorAdapter adapter = bc.getAdapter();
    final TagLibTag tlt = tag.getTagLibTag();
    final Type currType = getTagType(tag);

    final int currLocal = adapter.newLocal(currType);
    Label tagBegin = new Label();
    Label tagEnd = new Label();
    ExpressionUtil.visitLine(bc, tag.getStart());
    // TODO adapter.visitLocalVariable("tag", "L"+currType.getInternalName()+";", null, tagBegin, tagEnd, currLocal);

    adapter.visitLabel(tagBegin);

    // tag=pc.use(str);
    adapter.loadArg(0);
    adapter.checkCast(Types.PAGE_CONTEXT_IMPL);
    adapter.push(tlt.getTagClassName());
    adapter.push(tlt.getFullName());
    adapter.push(tlt.getAttributeType());
    adapter.invokeVirtual(Types.PAGE_CONTEXT_IMPL, USE3);
    adapter.checkCast(currType);
    adapter.storeLocal(currLocal);

    TryFinallyVisitor outerTcfv = new TryFinallyVisitor(new OnFinally() {
        public void _writeOut(BytecodeContext bc) {

            adapter.loadArg(0);
            adapter.loadLocal(currLocal);
            adapter.invokeVirtual(Types.PAGE_CONTEXT, RE_USE);
        }
    }, null);
    if (doReuse)
        outerTcfv.visitTryBegin(bc);

    // appendix
    if (tlt.hasAppendix()) {
        adapter.loadLocal(currLocal);
        adapter.push(tag.getAppendix());
        adapter.invokeVirtual(currType, SET_APPENDIX);
    }

    // hasBody
    boolean hasBody = tag.getBody() != null;
    if (tlt.isBodyFree() && tlt.hasBodyMethodExists()) {
        adapter.loadLocal(currLocal);
        adapter.push(hasBody);
        adapter.invokeVirtual(currType, HAS_BODY);
    }

    // default attributes (get overwritten by attributeCollection because of that set before)
    setAttributes(bc, tag, currLocal, currType, true);

    // attributeCollection
    Attribute attrColl = tag.getAttribute("attributecollection");
    if (attrColl != null) {
        int attrType = tag.getTagLibTag().getAttributeType();
        if (TagLibTag.ATTRIBUTE_TYPE_NONAME != attrType) {
            tag.removeAttribute("attributecollection");
            // TagUtil.setAttributeCollection(Tag, Struct)
            adapter.loadArg(0);
            adapter.loadLocal(currLocal);
            adapter.cast(currType, TAG);

            ///
            TagLibTagAttr[] missings = tag.getMissingAttributes();
            if (!ArrayUtil.isEmpty(missings)) {
                ArrayVisitor av = new ArrayVisitor();
                av.visitBegin(adapter, MISSING_ATTRIBUTE, missings.length);
                int count = 0;
                TagLibTagAttr miss;
                for (int i = 0; i < missings.length; i++) {
                    miss = missings[i];
                    av.visitBeginItem(adapter, count++);
                    Variable.registerKey(bc, LitString.toExprString(miss.getName()));
                    adapter.push(miss.getType());
                    if (ArrayUtil.isEmpty(miss.getAlias()))
                        adapter.invokeStatic(MISSING_ATTRIBUTE, NEW_INSTANCE_MAX2);
                    else {
                        new LiteralStringArray(miss.getAlias()).writeOut(bc, Expression.MODE_REF);
                        adapter.invokeStatic(MISSING_ATTRIBUTE, NEW_INSTANCE_MAX3);
                    }
                    av.visitEndItem(bc.getAdapter());
                }
                av.visitEnd();
            } else {
                ASMConstants.NULL(adapter);
            }
            ///
            attrColl.getValue().writeOut(bc, Expression.MODE_REF);

            adapter.push(attrType);
            adapter.invokeStatic(TAG_UTIL, SET_ATTRIBUTE_COLLECTION);
        }
    }

    // metadata
    Attribute attr;
    Map<String, Attribute> metadata = tag.getMetaData();
    if (metadata != null) {
        Iterator<Attribute> it = metadata.values().iterator();
        while (it.hasNext()) {
            attr = it.next();
            adapter.loadLocal(currLocal);
            adapter.push(attr.getName());
            attr.getValue().writeOut(bc, Expression.MODE_REF);
            adapter.invokeVirtual(currType, SET_META_DATA);
        }
    }

    // set attributes
    setAttributes(bc, tag, currLocal, currType, false);

    // Body
    if (hasBody) {
        final int state = adapter.newLocal(Types.INT_VALUE);

        // int state=tag.doStartTag();
        adapter.loadLocal(currLocal);
        adapter.invokeVirtual(currType, DO_START_TAG);
        adapter.storeLocal(state);

        // if (state!=Tag.SKIP_BODY)
        Label endBody = new Label();
        adapter.loadLocal(state);
        adapter.push(javax.servlet.jsp.tagext.Tag.SKIP_BODY);
        adapter.visitJumpInsn(Opcodes.IF_ICMPEQ, endBody);
        // pc.initBody(tag, state);
        adapter.loadArg(0);
        adapter.loadLocal(currLocal);
        adapter.loadLocal(state);
        adapter.invokeVirtual(Types.PAGE_CONTEXT, INIT_BODY);

        OnFinally onFinally = new OnFinally() {

            public void _writeOut(BytecodeContext bc) {
                Label endIf = new Label();
                /*if(tlt.handleException() && fcf!=null && fcf.getAfterFinalGOTOLabel()!=null){
                   ASMUtil.visitLabel(adapter, fcf.getFinalEntryLabel());
                }*/
                adapter.loadLocal(state);
                adapter.push(javax.servlet.jsp.tagext.Tag.EVAL_BODY_INCLUDE);
                adapter.visitJumpInsn(Opcodes.IF_ICMPEQ, endIf);
                // ... pc.popBody();
                adapter.loadArg(0);
                adapter.invokeVirtual(Types.PAGE_CONTEXT, POP_BODY);
                adapter.pop();
                adapter.visitLabel(endIf);

                // tag.doFinally();
                if (tlt.handleException()) {
                    adapter.loadLocal(currLocal);
                    adapter.invokeVirtual(currType, DO_FINALLY);
                }
                // GOTO after execution body, used when a continue/break was called before
                /*if(fcf!=null) {
                   Label l = fcf.getAfterFinalGOTOLabel();
                   if(l!=null)adapter.visitJumpInsn(Opcodes.GOTO, l);
                }*/

            }
        };

        if (tlt.handleException()) {
            TryCatchFinallyVisitor tcfv = new TryCatchFinallyVisitor(onFinally, fcf);
            tcfv.visitTryBegin(bc);
            doTry(bc, adapter, tag, currLocal, currType);
            int t = tcfv.visitTryEndCatchBeging(bc);
            // tag.doCatch(t);
            adapter.loadLocal(currLocal);
            adapter.loadLocal(t);
            //adapter.visitVarInsn(Opcodes.ALOAD,t);
            adapter.invokeVirtual(currType, DO_CATCH);
            tcfv.visitCatchEnd(bc);
        } else {
            TryFinallyVisitor tfv = new TryFinallyVisitor(onFinally, fcf);
            tfv.visitTryBegin(bc);
            doTry(bc, adapter, tag, currLocal, currType);
            tfv.visitTryEnd(bc);
        }

        adapter.visitLabel(endBody);

    } else {
        //tag.doStartTag();
        adapter.loadLocal(currLocal);
        adapter.invokeVirtual(currType, DO_START_TAG);
        adapter.pop();
    }

    // if (tag.doEndTag()==Tag.SKIP_PAGE) throw new Abort(0<!-- SCOPE_PAGE -->);
    Label endDoEndTag = new Label();
    adapter.loadLocal(currLocal);
    adapter.invokeVirtual(currType, DO_END_TAG);
    adapter.push(javax.servlet.jsp.tagext.Tag.SKIP_PAGE);
    adapter.visitJumpInsn(Opcodes.IF_ICMPNE, endDoEndTag);
    adapter.push(Abort.SCOPE_PAGE);
    adapter.invokeStatic(ABORT, NEW_INSTANCE);
    adapter.throwException();
    adapter.visitLabel(endDoEndTag);

    if (doReuse) {
        // } finally{pc.reuse(tag);}
        outerTcfv.visitTryEnd(bc);
    }

    adapter.visitLabel(tagEnd);
    ExpressionUtil.visitLine(bc, tag.getEnd());
}

From source file:lucee.transformer.bytecode.statement.tag.TagLoop.java

License:Open Source License

/**
 * write out file loop//from  w  w w  . ja v a  2 s .  com
 * @param adapter
 * @throws TemplateException
 */
private void writeOutTypeFile(BytecodeContext bc) throws BytecodeException {
    WhileVisitor whileVisitor = new WhileVisitor();
    loopVisitor = whileVisitor;
    GeneratorAdapter adapter = bc.getAdapter();

    // charset=@charset
    int charset = adapter.newLocal(Types.STRING);
    Attribute attrCharset = getAttribute("charset");
    if (attrCharset == null)
        adapter.visitInsn(Opcodes.ACONST_NULL);
    else
        attrCharset.getValue().writeOut(bc, Expression.MODE_REF);
    adapter.storeLocal(charset);

    // startline=@startline
    int startline = adapter.newLocal(Types.INT_VALUE);
    Attribute attrStartLine = getAttribute("startline");
    if (attrStartLine == null)
        attrStartLine = getAttribute("from"); // CF8
    if (attrStartLine == null)
        adapter.push(1);
    else {
        attrStartLine.getValue().writeOut(bc, Expression.MODE_VALUE);
        adapter.visitInsn(Opcodes.D2I);
    }
    adapter.storeLocal(startline);

    // endline=@endline
    int endline = adapter.newLocal(Types.INT_VALUE);
    Attribute attrEndLine = getAttribute("endline");
    if (attrEndLine == null)
        attrEndLine = getAttribute("to");
    if (attrEndLine == null)
        adapter.push(-1);
    else {
        attrEndLine.getValue().writeOut(bc, Expression.MODE_VALUE);
        adapter.visitInsn(Opcodes.D2I);
    }
    adapter.storeLocal(endline);

    //VariableReference index=VariableInterpreter.getVariableReference(pc,@index);
    int index = -1, item = -1;

    // item
    Attribute attrItem = getAttribute("item");
    if (attrItem != null) {
        item = adapter.newLocal(Types.VARIABLE_REFERENCE);
        adapter.loadArg(0);
        attrItem.getValue().writeOut(bc, Expression.MODE_REF);
        adapter.invokeStatic(Types.VARIABLE_INTERPRETER, GET_VARIABLE_REFERENCE);
        adapter.storeLocal(item);
    }

    // index
    Attribute attrIndex = getAttribute("index");
    if (attrIndex != null) {
        index = adapter.newLocal(Types.VARIABLE_REFERENCE);
        adapter.loadArg(0);
        attrIndex.getValue().writeOut(bc, Expression.MODE_REF);
        adapter.invokeStatic(Types.VARIABLE_INTERPRETER, GET_VARIABLE_REFERENCE);
        adapter.storeLocal(index);
    }

    //java.io.File file=FileUtil.toResourceExisting(pc,@file);
    int resource = adapter.newLocal(Types.RESOURCE);
    adapter.loadArg(0);
    getAttribute("file").getValue().writeOut(bc, Expression.MODE_REF);
    adapter.invokeStatic(RESOURCE_UTIL, TO_RESOURCE_EXISTING);
    adapter.storeLocal(resource);

    // pc.getConfig().getSecurityManager().checkFileLocation(resource);
    adapter.loadArg(0);
    adapter.invokeVirtual(Types.PAGE_CONTEXT, GET_CONFIG);
    adapter.invokeInterface(Types.CONFIG_WEB, GET_SECURITY_MANAGER);
    adapter.loadLocal(resource);
    adapter.invokeInterface(Types.SECURITY_MANAGER, CHECK_FILE_LOCATION);

    // char[] carr=new char[characters];
    Attribute attr = getAttribute("characters");
    int carr = -1;
    if (attr != null) {
        carr = adapter.newLocal(Types.CHAR_ARRAY);
        attr.getValue().writeOut(bc, Expression.MODE_VALUE);
        adapter.cast(Types.DOUBLE_VALUE, Types.INT_VALUE);
        adapter.newArray(Types.CHAR);
        adapter.storeLocal(carr);
    }

    // BufferedReader reader = IOUtil.getBufferedReader(resource,charset);
    final int br = adapter.newLocal(Types.BUFFERED_READER);
    adapter.loadLocal(resource);
    adapter.loadLocal(charset);
    adapter.invokeStatic(IO_UTIL, GET_BUFFERED_READER);
    adapter.storeLocal(br);

    // String line;
    int line = adapter.newLocal(Types.STRING);

    // int count=0;  
    int count = adapter.newLocal(Types.INT_VALUE);
    adapter.push(0);
    adapter.storeLocal(count);

    TryFinallyVisitor tfv = new TryFinallyVisitor(new OnFinally() {
        public void _writeOut(BytecodeContext bc) {
            bc.getAdapter().loadLocal(br);
            bc.getAdapter().invokeStatic(IO_UTIL, CLOSE_EL);
        }
    }, null);
    //TryFinallyVisitor tcfv=new TryFinallyVisitor();

    // try
    tfv.visitTryBegin(bc);
    //tcfv.visitTryBegin(bc);
    // while((line=br.readLine())!=null) { 
    //WhileVisitor wv=new WhileVisitor();
    whileVisitor.visitBeforeExpression(bc);
    DecisionObjectVisitor dv = new DecisionObjectVisitor();
    dv.visitBegin();
    if (attr != null) {
        // IOUtil.read(bufferedreader,12)
        adapter.loadLocal(br);
        adapter.loadLocal(carr);
        adapter.arrayLength();
        adapter.invokeStatic(Types.IOUTIL, READ);
    } else {
        // br.readLine()
        adapter.loadLocal(br);
        adapter.invokeVirtual(Types.BUFFERED_READER, READ_LINE);
    }
    adapter.dup();
    adapter.storeLocal(line);

    dv.visitNEQ();
    adapter.visitInsn(Opcodes.ACONST_NULL);
    dv.visitEnd(bc);

    whileVisitor.visitAfterExpressionBeforeBody(bc);
    //if(++count < startLine) continue; 
    DecisionIntVisitor dv2 = new DecisionIntVisitor();
    dv2.visitBegin();
    adapter.iinc(count, 1);
    adapter.loadLocal(count);
    dv2.visitLT();
    adapter.loadLocal(startline);
    dv2.visitEnd(bc);
    Label end = new Label();
    adapter.ifZCmp(Opcodes.IFEQ, end);
    whileVisitor.visitContinue(bc);
    adapter.visitLabel(end);

    // if(endLine!=-1 && count > endLine) break; 
    DecisionIntVisitor div = new DecisionIntVisitor();
    div.visitBegin();
    adapter.loadLocal(endline);
    div.visitNEQ();
    adapter.push(-1);
    div.visitEnd(bc);
    Label end2 = new Label();
    adapter.ifZCmp(Opcodes.IFEQ, end2);

    DecisionIntVisitor div2 = new DecisionIntVisitor();
    div2.visitBegin();
    adapter.loadLocal(count);
    div2.visitGT();
    adapter.loadLocal(endline);
    div2.visitEnd(bc);
    Label end3 = new Label();
    adapter.ifZCmp(Opcodes.IFEQ, end3);
    whileVisitor.visitBreak(bc);
    adapter.visitLabel(end3);
    adapter.visitLabel(end2);

    // index and item
    if (index != -1 && item != -1) {
        // index.set(pc,line); 
        adapter.loadLocal(index);
        adapter.loadArg(0);
        adapter.loadLocal(count);
        adapter.cast(Types.INT_VALUE, Types.DOUBLE_VALUE);
        adapter.invokeStatic(Types.CASTER, Methods.METHOD_TO_DOUBLE_FROM_DOUBLE);

        adapter.invokeVirtual(Types.VARIABLE_REFERENCE, SET);
        adapter.pop();

        // item.set(pc,line); 
        adapter.loadLocal(item);
        adapter.loadArg(0);
        adapter.loadLocal(line);
        adapter.invokeVirtual(Types.VARIABLE_REFERENCE, SET);
        adapter.pop();

    }
    // only index
    else if (index != -1) {
        // index.set(pc,line); 
        adapter.loadLocal(index);
        adapter.loadArg(0);
        adapter.loadLocal(line);
        adapter.invokeVirtual(Types.VARIABLE_REFERENCE, SET);
        adapter.pop();

    }
    // only item
    else {
        // item.set(pc,line); 
        adapter.loadLocal(item);
        adapter.loadArg(0);
        adapter.loadLocal(line);
        adapter.invokeVirtual(Types.VARIABLE_REFERENCE, SET);
        adapter.pop();
    }

    getBody().writeOut(bc);

    whileVisitor.visitAfterBody(bc, getEnd());

    tfv.visitTryEnd(bc);

}

From source file:lucee.transformer.bytecode.statement.tag.TagLoop.java

License:Open Source License

/**
 * write out list loop//w  w w .j ava2 s .co  m
 * @param adapter
 * @throws TemplateException
 */
private void writeOutTypeListArray(BytecodeContext bc, boolean isArray) throws BytecodeException {
    ForVisitor forVisitor = new ForVisitor();
    loopVisitor = forVisitor;
    GeneratorAdapter adapter = bc.getAdapter();

    //List.listToArrayRemoveEmpty("", 'c')
    int array = adapter.newLocal(Types.ARRAY);
    int len = adapter.newLocal(Types.INT_VALUE);

    if (isArray) {
        getAttribute("array").getValue().writeOut(bc, Expression.MODE_REF);
    } else {
        // array=List.listToArrayRemoveEmpty(list, delimter)
        getAttribute("list").getValue().writeOut(bc, Expression.MODE_REF);
        if (containsAttribute("delimiters")) {
            getAttribute("delimiters").getValue().writeOut(bc, Expression.MODE_REF);
            adapter.invokeStatic(Types.LIST_UTIL, LIST_TO_ARRAY_REMOVE_EMPTY_SS);
        } else {
            adapter.visitIntInsn(Opcodes.BIPUSH, 44);// ','
            //adapter.push(',');
            adapter.invokeStatic(Types.LIST_UTIL, LIST_TO_ARRAY_REMOVE_EMPTY_SC);
        }
    }
    adapter.storeLocal(array);

    // int len=array.size();
    adapter.loadLocal(array);
    adapter.invokeInterface(Types.ARRAY, SIZE);
    adapter.storeLocal(len);

    //VariableInterpreter.getVariableReference(pc,Caster.toString(index));
    Attribute attrIndex = getAttribute("index");
    int index = -1;
    if (attrIndex != null) {
        index = adapter.newLocal(Types.VARIABLE_REFERENCE);
        adapter.loadArg(0);
        attrIndex.getValue().writeOut(bc, Expression.MODE_REF);
        adapter.invokeStatic(Types.VARIABLE_INTERPRETER, GET_VARIABLE_REFERENCE);
        adapter.storeLocal(index);
    }

    //VariableInterpreter.getVariableReference(pc,Caster.toString(item));
    Attribute attrItem = getAttribute("item");
    int item = -1;
    if (attrItem != null) {
        item = adapter.newLocal(Types.VARIABLE_REFERENCE);
        adapter.loadArg(0);
        attrItem.getValue().writeOut(bc, Expression.MODE_REF);
        adapter.invokeStatic(Types.VARIABLE_INTERPRETER, GET_VARIABLE_REFERENCE);
        adapter.storeLocal(item);
    }

    int obj = 0;
    if (isArray)
        obj = adapter.newLocal(Types.OBJECT);

    // for(int i=1;i<=len;i++) {      
    int i = forVisitor.visitBegin(adapter, 1, false);
    // index.set(pc, list.get(i));

    if (isArray) {

        // value
        adapter.loadLocal(array);
        adapter.visitVarInsn(Opcodes.ILOAD, i);
        ASMConstants.NULL(adapter);
        adapter.invokeInterface(Types.ARRAY, GET);
        adapter.dup();
        adapter.storeLocal(obj);
        Label endIf = new Label();
        //adapter.loadLocal(obj);
        adapter.visitJumpInsn(Opcodes.IFNONNULL, endIf);
        adapter.goTo(forVisitor.getContinueLabel());
        adapter.visitLabel(endIf);

        if (item == -1)
            adapter.loadLocal(index);
        else
            adapter.loadLocal(item);

        adapter.loadArg(0);

        adapter.loadLocal(obj);

    } else {
        if (item == -1)
            adapter.loadLocal(index);
        else
            adapter.loadLocal(item);
        adapter.loadArg(0);
        adapter.loadLocal(array);
        adapter.visitVarInsn(Opcodes.ILOAD, i);
        adapter.invokeInterface(Types.ARRAY, GETE);

    }
    adapter.invokeVirtual(Types.VARIABLE_REFERENCE, SET);
    adapter.pop();

    // key
    if (index != -1 && item != -1) {
        adapter.loadLocal(index);
        adapter.loadArg(0);
        adapter.visitVarInsn(Opcodes.ILOAD, i);
        adapter.cast(Types.INT_VALUE, Types.DOUBLE_VALUE);
        adapter.invokeStatic(Types.CASTER, Methods_Caster.TO_DOUBLE[Methods_Caster.DOUBLE]);
        adapter.invokeVirtual(Types.VARIABLE_REFERENCE, SET);
        adapter.pop();
    }

    getBody().writeOut(bc);
    forVisitor.visitEnd(bc, len, true, getStart());
}