Search in sources :

Example 6 with CompileException

use of org.mvel2.CompileException in project mvel by mikebrock.

the class ASMAccessorOptimizer method optimizeObjectCreation.

public Accessor optimizeObjectCreation(ParserContext pCtx, char[] property, int start, int offset, Object ctx, Object thisRef, VariableResolverFactory factory) {
    _initJIT();
    compiledInputs = new ArrayList<ExecutableStatement>();
    this.start = cursor = start;
    this.end = start + offset;
    this.length = this.end - this.start;
    this.ctx = ctx;
    this.thisRef = thisRef;
    this.variableFactory = factory;
    this.pCtx = pCtx;
    String[] cnsRes = captureContructorAndResidual(property, start, offset);
    List<char[]> constructorParms = parseMethodOrConstructor(cnsRes[0].toCharArray());
    try {
        if (constructorParms != null) {
            for (char[] constructorParm : constructorParms) {
                compiledInputs.add((ExecutableStatement) subCompileExpression(constructorParm, pCtx));
            }
            Class cls = findClass(factory, new String(subset(property, 0, findFirst('(', start, length, property))), pCtx);
            assert debug("NEW " + getInternalName(cls));
            mv.visitTypeInsn(NEW, getInternalName(cls));
            assert debug("DUP");
            mv.visitInsn(DUP);
            Object[] parms = new Object[constructorParms.size()];
            int i = 0;
            for (ExecutableStatement es : compiledInputs) {
                parms[i++] = es.getValue(ctx, factory);
            }
            Constructor cns = getBestConstructorCandidate(parms, cls, pCtx.isStrongTyping());
            if (cns == null) {
                StringBuilder error = new StringBuilder();
                for (int x = 0; x < parms.length; x++) {
                    error.append(parms[x].getClass().getName());
                    if (x + 1 < parms.length)
                        error.append(", ");
                }
                throw new CompileException("unable to find constructor: " + cls.getName() + "(" + error.toString() + ")", expr, st);
            }
            this.returnType = cns.getDeclaringClass();
            Class tg;
            for (i = 0; i < constructorParms.size(); i++) {
                assert debug("ALOAD 0");
                mv.visitVarInsn(ALOAD, 0);
                assert debug("GETFIELD p" + i);
                mv.visitFieldInsn(GETFIELD, className, "p" + i, "L" + NAMESPACE + "compiler/ExecutableStatement;");
                assert debug("ALOAD 2");
                mv.visitVarInsn(ALOAD, 2);
                assert debug("ALOAD 3");
                mv.visitVarInsn(ALOAD, 3);
                assert debug("INVOKEINTERFACE " + NAMESPACE + "compiler/ExecutableStatement.getValue");
                mv.visitMethodInsn(INVOKEINTERFACE, "" + NAMESPACE + "compiler/ExecutableStatement", "getValue", "(Ljava/lang/Object;L" + NAMESPACE + "integration/VariableResolverFactory;)Ljava/lang/Object;");
                tg = cns.getParameterTypes()[i].isPrimitive() ? getWrapperClass(cns.getParameterTypes()[i]) : cns.getParameterTypes()[i];
                if (parms[i] != null && !parms[i].getClass().isAssignableFrom(cns.getParameterTypes()[i])) {
                    ldcClassConstant(tg);
                    assert debug("INVOKESTATIC " + NAMESPACE + "DataConversion.convert");
                    mv.visitMethodInsn(INVOKESTATIC, "" + NAMESPACE + "DataConversion", "convert", "(Ljava/lang/Object;Ljava/lang/Class;)Ljava/lang/Object;");
                    if (cns.getParameterTypes()[i].isPrimitive()) {
                        unwrapPrimitive(cns.getParameterTypes()[i]);
                    } else {
                        assert debug("CHECKCAST " + getInternalName(tg));
                        mv.visitTypeInsn(CHECKCAST, getInternalName(tg));
                    }
                } else {
                    assert debug("CHECKCAST " + getInternalName(cns.getParameterTypes()[i]));
                    mv.visitTypeInsn(CHECKCAST, getInternalName(cns.getParameterTypes()[i]));
                }
            }
            assert debug("INVOKESPECIAL " + getInternalName(cls) + ".<init> : " + getConstructorDescriptor(cns));
            mv.visitMethodInsn(INVOKESPECIAL, getInternalName(cls), "<init>", getConstructorDescriptor(cns));
            _finishJIT();
            Accessor acc = _initializeAccessor();
            if (cnsRes.length > 1 && cnsRes[1] != null && !cnsRes[1].trim().equals("")) {
                return new Union(acc, cnsRes[1].toCharArray(), 0, cnsRes[1].length());
            }
            return acc;
        } else {
            Class cls = findClass(factory, new String(property), pCtx);
            assert debug("NEW " + getInternalName(cls));
            mv.visitTypeInsn(NEW, getInternalName(cls));
            assert debug("DUP");
            mv.visitInsn(DUP);
            Constructor cns = cls.getConstructor(EMPTYCLS);
            assert debug("INVOKESPECIAL <init>");
            mv.visitMethodInsn(INVOKESPECIAL, getInternalName(cls), "<init>", getConstructorDescriptor(cns));
            _finishJIT();
            Accessor acc = _initializeAccessor();
            if (cnsRes.length > 1 && cnsRes[1] != null && !cnsRes[1].trim().equals("")) {
                return new Union(acc, cnsRes[1].toCharArray(), 0, cnsRes[1].length());
            }
            return acc;
        }
    } catch (ClassNotFoundException e) {
        throw new CompileException("class or class reference not found: " + new String(property), property, st);
    } catch (Exception e) {
        throw new OptimizationFailure("could not optimize construtor: " + new String(property), e);
    }
}
Also used : PropertyTools.getFieldOrWriteAccessor(org.mvel2.util.PropertyTools.getFieldOrWriteAccessor) PropertyTools.getFieldOrAccessor(org.mvel2.util.PropertyTools.getFieldOrAccessor) Union(org.mvel2.optimizers.impl.refl.nodes.Union) IOException(java.io.IOException)

Example 7 with CompileException

use of org.mvel2.CompileException in project mvel by mikebrock.

the class ReflectiveAccessorOptimizer method getCollectionProperty.

/**
   * Handle accessing a property embedded in a collections, map, or array
   *
   * @param ctx  -
   * @param prop -
   * @return -
   * @throws Exception -
   */
private Object getCollectionProperty(Object ctx, String prop) throws Exception {
    if (prop.length() > 0) {
        ctx = getBeanProperty(ctx, prop);
    }
    if (ctx == null)
        return null;
    int start = ++cursor;
    skipWhitespace();
    if (cursor == end)
        throw new CompileException("unterminated '['", this.expr, this.start);
    String item;
    if (scanTo(']'))
        throw new CompileException("unterminated '['", this.expr, this.start);
    item = new String(expr, start, cursor - start);
    boolean itemSubExpr = true;
    Object idx = null;
    try {
        idx = parseInt(item);
        itemSubExpr = false;
    } catch (Exception e) {
    // not a number;
    }
    ExecutableStatement itemStmt = null;
    if (itemSubExpr) {
        try {
            idx = (itemStmt = (ExecutableStatement) subCompileExpression(item.toCharArray(), pCtx)).getValue(ctx, thisRef, variableFactory);
        } catch (CompileException e) {
            e.setExpr(this.expr);
            e.setCursor(start);
            throw e;
        }
    }
    ++cursor;
    if (ctx instanceof Map) {
        if (itemSubExpr) {
            addAccessorNode(new MapAccessorNest(itemStmt, null));
        } else {
            addAccessorNode(new MapAccessor(parseInt(item)));
        }
        return ((Map) ctx).get(idx);
    } else if (ctx instanceof List) {
        if (itemSubExpr) {
            addAccessorNode(new ListAccessorNest(itemStmt, null));
        } else {
            addAccessorNode(new ListAccessor(parseInt(item)));
        }
        return ((List) ctx).get((Integer) idx);
    } else if (ctx.getClass().isArray()) {
        if (itemSubExpr) {
            addAccessorNode(new ArrayAccessorNest(itemStmt));
        } else {
            addAccessorNode(new ArrayAccessor(parseInt(item)));
        }
        return Array.get(ctx, (Integer) idx);
    } else if (ctx instanceof CharSequence) {
        if (itemSubExpr) {
            addAccessorNode(new IndexedCharSeqAccessorNest(itemStmt));
        } else {
            addAccessorNode(new IndexedCharSeqAccessor(parseInt(item)));
        }
        return ((CharSequence) ctx).charAt((Integer) idx);
    } else {
        TypeDescriptor tDescr = new TypeDescriptor(expr, this.start, length, 0);
        if (tDescr.isArray()) {
            Class cls = getClassReference((Class) ctx, tDescr, variableFactory, pCtx);
            rootNode = new StaticReferenceAccessor(cls);
            return cls;
        }
        throw new CompileException("illegal use of []: unknown type: " + ctx.getClass().getName(), this.expr, this.start);
    }
}
Also used : ExecutableStatement(org.mvel2.compiler.ExecutableStatement) TypeDescriptor(org.mvel2.ast.TypeDescriptor) List(java.util.List) Map(java.util.Map) WeakHashMap(java.util.WeakHashMap)

Example 8 with CompileException

use of org.mvel2.CompileException in project mvel by mikebrock.

the class ReflectiveAccessorOptimizer method getCollectionPropertyAO.

private Object getCollectionPropertyAO(Object ctx, String prop) throws Exception {
    if (prop.length() > 0) {
        ctx = getBeanPropertyAO(ctx, prop);
    }
    if (ctx == null)
        return null;
    int _start = ++cursor;
    skipWhitespace();
    if (cursor == end)
        throw new CompileException("unterminated '['", this.expr, this.start);
    String item;
    if (scanTo(']'))
        throw new CompileException("unterminated '['", this.expr, this.start);
    item = new String(expr, _start, cursor - _start);
    boolean itemSubExpr = true;
    Object idx = null;
    try {
        idx = parseInt(item);
        itemSubExpr = false;
    } catch (Exception e) {
    // not a number;
    }
    ExecutableStatement itemStmt = null;
    if (itemSubExpr) {
        idx = (itemStmt = (ExecutableStatement) subCompileExpression(item.toCharArray(), pCtx)).getValue(ctx, thisRef, variableFactory);
    }
    ++cursor;
    if (ctx instanceof Map) {
        if (hasPropertyHandler(Map.class)) {
            return propHandler(item, ctx, Map.class);
        } else {
            if (itemSubExpr) {
                addAccessorNode(new MapAccessorNest(itemStmt, null));
            } else {
                addAccessorNode(new MapAccessor(parseInt(item)));
            }
            return ((Map) ctx).get(idx);
        }
    } else if (ctx instanceof List) {
        if (hasPropertyHandler(List.class)) {
            return propHandler(item, ctx, List.class);
        } else {
            if (itemSubExpr) {
                addAccessorNode(new ListAccessorNest(itemStmt, null));
            } else {
                addAccessorNode(new ListAccessor(parseInt(item)));
            }
            return ((List) ctx).get((Integer) idx);
        }
    } else if (ctx.getClass().isArray()) {
        if (hasPropertyHandler(Array.class)) {
            return propHandler(item, ctx, Array.class);
        } else {
            if (itemSubExpr) {
                addAccessorNode(new ArrayAccessorNest(itemStmt));
            } else {
                addAccessorNode(new ArrayAccessor(parseInt(item)));
            }
            return Array.get(ctx, (Integer) idx);
        }
    } else if (ctx instanceof CharSequence) {
        if (hasPropertyHandler(CharSequence.class)) {
            return propHandler(item, ctx, CharSequence.class);
        } else {
            if (itemSubExpr) {
                addAccessorNode(new IndexedCharSeqAccessorNest(itemStmt));
            } else {
                addAccessorNode(new IndexedCharSeqAccessor(parseInt(item)));
            }
            return ((CharSequence) ctx).charAt((Integer) idx);
        }
    } else {
        TypeDescriptor tDescr = new TypeDescriptor(expr, this.start, end - this.start, 0);
        if (tDescr.isArray()) {
            Class cls = getClassReference((Class) ctx, tDescr, variableFactory, pCtx);
            rootNode = new StaticReferenceAccessor(cls);
            return cls;
        }
        throw new CompileException("illegal use of []: unknown type: " + ctx.getClass().getName(), this.expr, this.st);
    }
}
Also used : ExecutableStatement(org.mvel2.compiler.ExecutableStatement) TypeDescriptor(org.mvel2.ast.TypeDescriptor) List(java.util.List) Map(java.util.Map) WeakHashMap(java.util.WeakHashMap)

Example 9 with CompileException

use of org.mvel2.CompileException in project mvel by mikebrock.

the class ReflectiveAccessorOptimizer method compileConstructor.

@SuppressWarnings({ "WeakerAccess" })
public AccessorNode compileConstructor(char[] expression, Object ctx, VariableResolverFactory vars) throws InstantiationException, IllegalAccessException, InvocationTargetException, ClassNotFoundException, NoSuchMethodException {
    String[] cnsRes = captureContructorAndResidual(expression, start, length);
    List<char[]> constructorParms = parseMethodOrConstructor(cnsRes[0].toCharArray());
    if (constructorParms != null) {
        String s = new String(subset(expression, 0, ArrayTools.findFirst('(', start, length, expression)));
        Class cls = ParseTools.findClass(vars, s, pCtx);
        ExecutableStatement[] cStmts = new ExecutableStatement[constructorParms.size()];
        for (int i = 0; i < constructorParms.size(); i++) {
            cStmts[i] = (ExecutableStatement) subCompileExpression(constructorParms.get(i), pCtx);
        }
        Object[] parms = new Object[constructorParms.size()];
        for (int i = 0; i < constructorParms.size(); i++) {
            parms[i] = cStmts[i].getValue(ctx, vars);
        }
        Constructor cns = getBestConstructorCandidate(parms, cls, pCtx.isStrongTyping());
        if (cns == null) {
            StringBuilder error = new StringBuilder();
            for (int i = 0; i < parms.length; i++) {
                error.append(parms[i].getClass().getName());
                if (i + 1 < parms.length)
                    error.append(", ");
            }
            throw new CompileException("unable to find constructor: " + cls.getName() + "(" + error.toString() + ")", this.expr, this.start);
        }
        for (int i = 0; i < parms.length; i++) {
            //noinspection unchecked
            parms[i] = convert(parms[i], cns.getParameterTypes()[i]);
        }
        AccessorNode ca = new ConstructorAccessor(cns, cStmts);
        if (cnsRes.length > 1) {
            ReflectiveAccessorOptimizer compiledOptimizer = new ReflectiveAccessorOptimizer(pCtx, cnsRes[1].toCharArray(), 0, cnsRes[1].length(), cns.newInstance(parms), ctx, vars);
            compiledOptimizer.ingressType = cns.getDeclaringClass();
            compiledOptimizer.setRootNode(ca);
            compiledOptimizer.compileGetChain();
            ca = compiledOptimizer.getRootNode();
            this.val = compiledOptimizer.getResultOptPass();
        }
        return ca;
    } else {
        Constructor<?> cns = Class.forName(new String(expression), true, Thread.currentThread().getContextClassLoader()).getConstructor(EMPTYCLS);
        AccessorNode ca = new ConstructorAccessor(cns, null);
        if (cnsRes.length > 1) {
            //noinspection NullArgumentToVariableArgMethod
            ReflectiveAccessorOptimizer compiledOptimizer = new ReflectiveAccessorOptimizer(getCurrentThreadParserContext(), cnsRes[1].toCharArray(), 0, cnsRes[1].length(), cns.newInstance(null), ctx, vars);
            compiledOptimizer.setRootNode(ca);
            compiledOptimizer.compileGetChain();
            ca = compiledOptimizer.getRootNode();
            this.val = compiledOptimizer.getResultOptPass();
        }
        return ca;
    }
}
Also used : ExecutableStatement(org.mvel2.compiler.ExecutableStatement) AccessorNode(org.mvel2.compiler.AccessorNode)

Example 10 with CompileException

use of org.mvel2.CompileException in project mvel by mikebrock.

the class ASTNode method setName.

@SuppressWarnings({ "SuspiciousMethodCalls" })
protected void setName(char[] name) {
    if (isNumber(name, start, offset)) {
        egressType = (literal = handleNumericConversion(name, start, offset)).getClass();
        if (((fields |= NUMERIC | LITERAL | IDENTIFIER) & INVERT) != 0) {
            try {
                literal = ~((Integer) literal);
            } catch (ClassCastException e) {
                throw new CompileException("bitwise (~) operator can only be applied to integers", expr, start);
            }
        }
        return;
    }
    this.literal = new String(name, start, offset);
    int end = start + offset;
    Scan: for (int i = start; i < end; i++) {
        switch(name[i]) {
            case '.':
                if (firstUnion == 0) {
                    firstUnion = i;
                }
                break;
            case '[':
            case '(':
                if (firstUnion == 0) {
                    firstUnion = i;
                }
                if (endOfName == 0) {
                    endOfName = i;
                    if (i < name.length && name[i + 1] == ']')
                        fields |= ARRAY_TYPE_LITERAL;
                    break Scan;
                }
        }
    }
    if ((fields & INLINE_COLLECTION) != 0) {
        return;
    }
    if (firstUnion > start) {
        fields |= DEEP_PROPERTY | IDENTIFIER;
    } else {
        fields |= IDENTIFIER;
    }
}
Also used : CompileException(org.mvel2.CompileException)

Aggregations

CompileException (org.mvel2.CompileException)23 List (java.util.List)8 Map (java.util.Map)8 IOException (java.io.IOException)7 ExecutableStatement (org.mvel2.compiler.ExecutableStatement)7 ArrayList (java.util.ArrayList)6 Function (org.mvel2.ast.Function)4 TypeDescriptor (org.mvel2.ast.TypeDescriptor)4 WeakHashMap (java.util.WeakHashMap)3 ParserContext (org.mvel2.ParserContext)3 Proto (org.mvel2.ast.Proto)3 ExpressionCompiler (org.mvel2.compiler.ExpressionCompiler)3 StringAppender (org.mvel2.util.StringAppender)3 Label (org.mvel2.asm.Label)2 ASTNode (org.mvel2.ast.ASTNode)2 EndOfStatement (org.mvel2.ast.EndOfStatement)2 CompiledExpression (org.mvel2.compiler.CompiledExpression)2 DefaultLocalVariableResolverFactory (org.mvel2.integration.impl.DefaultLocalVariableResolverFactory)2 ItemResolverFactory (org.mvel2.integration.impl.ItemResolverFactory)2 ExecutionStack (org.mvel2.util.ExecutionStack)2