Search in sources :

Example 16 with Function

use of org.mvel2.ast.Function in project mvel by mikebrock.

the class AbstractParser method _captureBlock.

private ASTNode _captureBlock(ASTNode node, final char[] expr, boolean cond, int type) {
    skipWhitespace();
    int startCond = 0;
    int endCond = 0;
    int blockStart;
    int blockEnd;
    String name;
    /**
     * Functions are a special case we handle differently from the rest of block parsing
     */
    switch(type) {
        case FUNCTION:
            {
                int st = cursor;
                captureToNextTokenJunction();
                if (cursor == end) {
                    throw new CompileException("unexpected end of statement", expr, st);
                }
                /**
                 * Check to see if the name is legal.
                 */
                if (isReservedWord(name = createStringTrimmed(expr, st, cursor - st)) || isNotValidNameorLabel(name))
                    throw new CompileException("illegal function name or use of reserved word", expr, cursor);
                if (pCtx == null)
                    pCtx = getParserContext();
                FunctionParser parser = new FunctionParser(name, cursor, end - cursor, expr, fields, pCtx, splitAccumulator);
                Function function = parser.parse();
                cursor = parser.getCursor();
                return lastNode = function;
            }
        case PROTO:
            if (ProtoParser.isUnresolvedWaiting()) {
                if (pCtx == null)
                    pCtx = getParserContext();
                ProtoParser.checkForPossibleUnresolvedViolations(expr, cursor, pCtx);
            }
            int st = cursor;
            captureToNextTokenJunction();
            if (isReservedWord(name = createStringTrimmed(expr, st, cursor - st)) || isNotValidNameorLabel(name))
                throw new CompileException("illegal prototype name or use of reserved word", expr, cursor);
            if (expr[cursor = nextNonBlank()] != '{') {
                throw new CompileException("expected '{' but found: " + expr[cursor], expr, cursor);
            }
            cursor = balancedCaptureWithLineAccounting(expr, st = cursor + 1, end, '{', pCtx);
            if (pCtx == null)
                pCtx = getParserContext();
            ProtoParser parser = new ProtoParser(expr, st, cursor, name, pCtx, fields, splitAccumulator);
            Proto proto = parser.parse();
            if (pCtx == null)
                pCtx = getParserContext();
            pCtx.addImport(proto);
            proto.setCursorPosition(st, cursor);
            cursor = parser.getCursor();
            ProtoParser.notifyForLateResolution(proto);
            return lastNode = proto;
        default:
            if (cond) {
                if (expr[cursor] != '(') {
                    throw new CompileException("expected '(' but encountered: " + expr[cursor], expr, cursor);
                }
                /**
                 * This block is an: IF, FOREACH or WHILE node.
                 */
                endCond = cursor = balancedCaptureWithLineAccounting(expr, startCond = cursor, end, '(', pCtx);
                startCond++;
                cursor++;
            }
    }
    skipWhitespace();
    if (cursor >= end) {
        throw new CompileException("unexpected end of statement", expr, end);
    } else if (expr[cursor] == '{') {
        blockEnd = cursor = balancedCaptureWithLineAccounting(expr, blockStart = cursor, end, '{', pCtx);
    } else {
        blockStart = cursor - 1;
        captureToEOSorEOL();
        blockEnd = cursor + 1;
    }
    if (type == ASTNode.BLOCK_IF) {
        IfNode ifNode = (IfNode) node;
        if (node != null) {
            if (!cond) {
                return ifNode.setElseBlock(expr, st = trimRight(blockStart + 1), trimLeft(blockEnd) - st, pCtx);
            } else {
                return ifNode.setElseIf((IfNode) createBlockToken(startCond, endCond, trimRight(blockStart + 1), trimLeft(blockEnd), type));
            }
        } else {
            return createBlockToken(startCond, endCond, blockStart + 1, blockEnd, type);
        }
    } else if (type == ASTNode.BLOCK_DO) {
        cursor++;
        skipWhitespace();
        st = cursor;
        captureToNextTokenJunction();
        if ("while".equals(name = new String(expr, st, cursor - st))) {
            skipWhitespace();
            startCond = cursor + 1;
            endCond = cursor = balancedCaptureWithLineAccounting(expr, cursor, end, '(', pCtx);
            return createBlockToken(startCond, endCond, trimRight(blockStart + 1), trimLeft(blockEnd), type);
        } else if ("until".equals(name)) {
            skipWhitespace();
            startCond = cursor + 1;
            endCond = cursor = balancedCaptureWithLineAccounting(expr, cursor, end, '(', pCtx);
            return createBlockToken(startCond, endCond, trimRight(blockStart + 1), trimLeft(blockEnd), ASTNode.BLOCK_DO_UNTIL);
        } else {
            throw new CompileException("expected 'while' or 'until' but encountered: " + name, expr, cursor);
        }
    } else // DON"T REMOVE THIS COMMENT!
    // else if (isFlag(ASTNode.BLOCK_FOREACH) || isFlag(ASTNode.BLOCK_WITH)) {
    {
        return createBlockToken(startCond, endCond, trimRight(blockStart + 1), trimLeft(blockEnd), type);
    }
}
Also used : FunctionParser(org.mvel2.util.FunctionParser) ProtoParser(org.mvel2.util.ProtoParser) CompileException(org.mvel2.CompileException)

Example 17 with Function

use of org.mvel2.ast.Function in project mvel by mikebrock.

the class PropertyVerifier method getMethod.

/**
 * Process method
 *
 * @param ctx  - the ingress type
 * @param name - the property component
 * @return known egress type.
 */
private Class getMethod(Class ctx, String name) {
    int st = cursor;
    /**
     * Check to see if this is the first element in the statement.
     */
    if (first) {
        first = false;
        methodCall = true;
        /**
         * It's the first element in the statement, therefore we check to see if there is a static import of a
         * native Java method or an MVEL function.
         */
        if (pCtx.hasImport(name)) {
            Method m = pCtx.getStaticImport(name).getMethod();
            /**
             * Replace the method parameters.
             */
            ctx = m.getDeclaringClass();
            name = m.getName();
        } else if (pCtx.hasFunction(name)) {
            resolvedExternally = false;
            Function f = pCtx.getFunction(name);
            f.checkArgumentCount(parseParameterList((((cursor = balancedCapture(expr, cursor, end, '(')) - st) > 1 ? ParseTools.subset(expr, st + 1, cursor - st - 1) : new char[0]), 0, -1).size());
            return f.getEgressType();
        } else if (pCtx.hasVarOrInput("this")) {
            if (pCtx.isStrictTypeEnforcement()) {
                recordTypeParmsForProperty("this");
            }
            ctx = pCtx.getVarOrInputType("this");
            resolvedExternally = false;
        }
    }
    /**
     * Get the arguments for the method.
     */
    String tk;
    if (cursor < end && expr[cursor] == '(' && ((cursor = balancedCapture(expr, cursor, end, '(')) - st) > 1) {
        tk = new String(expr, st + 1, cursor - st - 1);
    } else {
        tk = "";
    }
    cursor++;
    /**
     * Parse out the arguments list.
     */
    Class[] args;
    List<char[]> subtokens = parseParameterList(tk.toCharArray(), 0, -1);
    if (subtokens.size() == 0) {
        args = new Class[0];
        subtokens = Collections.emptyList();
    } else {
        // ParserContext subCtx = pCtx.createSubcontext();
        args = new Class[subtokens.size()];
        /**
         *  Subcompile all the arguments to determine their known types.
         */
        // ExpressionCompiler compiler;
        List<ErrorDetail> errors = pCtx.getErrorList().isEmpty() ? pCtx.getErrorList() : new ArrayList<ErrorDetail>(pCtx.getErrorList());
        CompileException rethrow = null;
        for (int i = 0; i < subtokens.size(); i++) {
            try {
                args[i] = MVEL.analyze(subtokens.get(i), pCtx);
                if ("null".equals(String.valueOf(subtokens.get(i)))) {
                    args[i] = NullType.class;
                }
            } catch (CompileException e) {
                rethrow = ErrorUtil.rewriteIfNeeded(e, expr, this.st);
            }
            if (errors.size() < pCtx.getErrorList().size()) {
                for (ErrorDetail detail : pCtx.getErrorList()) {
                    if (!errors.contains(detail)) {
                        detail.setExpr(expr);
                        detail.setCursor(new String(expr).substring(this.st).indexOf(new String(subtokens.get(i))) + this.st);
                        detail.setColumn(0);
                        detail.setLineNumber(0);
                        detail.calcRowAndColumn();
                    }
                }
            }
            if (rethrow != null) {
                throw rethrow;
            }
        }
    }
    /**
     * If the target object is an instance of java.lang.Class itself then do not
     * adjust the Class scope target.
     */
    Method m;
    if ((m = getBestCandidate(args, name, ctx, ctx.getMethods(), pCtx.isStrongTyping())) == null) {
        if ((m = getBestCandidate(args, name, ctx, ctx.getDeclaredMethods(), pCtx.isStrongTyping())) == null) {
            StringAppender errorBuild = new StringAppender();
            for (int i = 0; i < args.length; i++) {
                errorBuild.append(args[i] != null ? args[i].getName() : null);
                if (i < args.length - 1)
                    errorBuild.append(", ");
            }
            if (("size".equals(name) || "length".equals(name)) && args.length == 0 && ctx.isArray()) {
                return Integer.class;
            }
            if (pCtx.isStrictTypeEnforcement()) {
                throw new CompileException("unable to resolve method using strict-mode: " + ctx.getName() + "." + name + "(" + errorBuild.toString() + ")", expr, tkStart);
            }
            return Object.class;
        }
    }
    /**
     * If we're in strict mode, we look for generic type information.
     */
    if (pCtx.isStrictTypeEnforcement() && m.getGenericReturnType() != null) {
        Map<String, Class> typeArgs = new HashMap<String, Class>();
        Type[] gpt = m.getGenericParameterTypes();
        Class z;
        ParameterizedType pt;
        for (int i = 0; i < gpt.length; i++) {
            if (gpt[i] instanceof ParameterizedType) {
                pt = (ParameterizedType) gpt[i];
                if ((z = pCtx.getImport(new String(subtokens.get(i)))) != null) {
                    /**
                     * We record the value of the type parameter to our typeArgs Map.
                     */
                    if (pt.getRawType().equals(Class.class)) {
                        /**
                         * If this is an instance of Class, we deal with the special parameterization case.
                         */
                        typeArgs.put(pt.getActualTypeArguments()[0].toString(), z);
                    } else {
                        typeArgs.put(gpt[i].toString(), z);
                    }
                }
            }
        }
        if (pCtx.isStrictTypeEnforcement() && ctx.getTypeParameters().length != 0 && pCtx.getLastTypeParameters() != null && pCtx.getLastTypeParameters().length == ctx.getTypeParameters().length) {
            TypeVariable[] typeVariables = ctx.getTypeParameters();
            for (int i = 0; i < typeVariables.length; i++) {
                typeArgs.put(typeVariables[i].getName(), (Class) pCtx.getLastTypeParameters()[i]);
            }
        }
        /**
         * Get the return type argument
         */
        Type parametricReturnType = m.getGenericReturnType();
        String returnTypeArg = parametricReturnType.toString();
        // push return type parameters onto parser context, only if this is a parametric type
        if (parametricReturnType instanceof ParameterizedType) {
            pCtx.setLastTypeParameters(((ParameterizedType) parametricReturnType).getActualTypeArguments());
        }
        if (paramTypes != null && paramTypes.containsKey(returnTypeArg)) {
            /**
             * If the paramTypes Map contains the known type, return that type.
             */
            return (Class) paramTypes.get(returnTypeArg);
        } else if (typeArgs.containsKey(returnTypeArg)) {
            /**
             * If the generic type was declared as part of the method, it will be in this
             * Map.
             */
            return typeArgs.get(returnTypeArg);
        }
    }
    if (!Modifier.isPublic(m.getModifiers())) {
        StringAppender errorBuild = new StringAppender();
        for (int i = 0; i < args.length; i++) {
            errorBuild.append(args[i] != null ? args[i].getName() : null);
            if (i < args.length - 1)
                errorBuild.append(", ");
        }
        String scope = Modifier.toString(m.getModifiers());
        if (scope.trim().equals(""))
            scope = "<package local>";
        addFatalError("the referenced method is not accessible: " + ctx.getName() + "." + name + "(" + errorBuild.toString() + ")" + " (scope: " + scope + "; required: public", this.tkStart);
    }
    return m.getReturnType();
}
Also used : Function(org.mvel2.ast.Function) NullType(org.mvel2.util.NullType) StringAppender(org.mvel2.util.StringAppender)

Example 18 with Function

use of org.mvel2.ast.Function in project mvel by mikebrock.

the class PropertyAccessor method getMethod.

/**
 * Find an appropriate method, execute it, and return it's response.
 *
 * @param ctx  -
 * @param name -
 * @return -
 * @throws Exception -
 */
@SuppressWarnings({ "unchecked" })
private Object getMethod(Object ctx, String name) {
    int _start = cursor;
    String tk = cursor != end && property[cursor] == '(' && ((cursor = balancedCapture(property, cursor, '(')) - _start) > 1 ? new String(property, _start + 1, cursor - _start - 1) : "";
    cursor++;
    Object[] args;
    if (tk.length() == 0) {
        args = ParseTools.EMPTY_OBJ_ARR;
    } else {
        List<char[]> subtokens = parseParameterList(tk.toCharArray(), 0, -1);
        args = new Object[subtokens.size()];
        for (int i = 0; i < subtokens.size(); i++) {
            args[i] = eval(subtokens.get(i), thisReference, variableFactory);
        }
    }
    if (first && variableFactory != null && variableFactory.isResolveable(name)) {
        Object ptr = variableFactory.getVariableResolver(name).getValue();
        if (ptr instanceof Method) {
            ctx = ((Method) ptr).getDeclaringClass();
            name = ((Method) ptr).getName();
        } else if (ptr instanceof MethodStub) {
            ctx = ((MethodStub) ptr).getClassReference();
            name = ((MethodStub) ptr).getMethodName();
        } else if (ptr instanceof Function) {
            ((Function) ptr).checkArgumentCount(args.length);
            return ((Function) ptr).call(null, thisReference, variableFactory, args);
        } else {
            throw new OptimizationFailure("attempt to optimize a method call for a reference that does not point to a method: " + name + " (reference is type: " + (ctx != null ? ctx.getClass().getName() : null) + ")");
        }
        first = false;
    }
    if (ctx == null)
        throw new CompileException("no such method or function: " + name, property, cursor);
    /**
     * If the target object is an instance of java.lang.Class itself then do not
     * adjust the Class scope target.
     */
    Class cls = (ctx instanceof Class ? (Class) ctx : ctx.getClass());
    if (cls == Proto.ProtoInstance.class) {
        return ((Proto.ProtoInstance) ctx).get(name).call(null, thisReference, variableFactory, args);
    }
    /**
     * Check to see if we have already cached this method;
     */
    Object[] cache = checkMethodCache(cls, createSignature(name, tk));
    Method m;
    Class[] parameterTypes;
    if (cache != null) {
        m = (Method) cache[0];
        parameterTypes = (Class[]) cache[1];
    } else {
        m = null;
        parameterTypes = null;
    }
    /**
     * If we have not cached the method then we need to go ahead and try to resolve it.
     */
    if (m == null) {
        /**
         * Try to find an instance method from the class target.
         */
        if ((m = getBestCandidate(args, name, cls, cls.getMethods(), false)) != null) {
            addMethodCache(cls, createSignature(name, tk), m);
            parameterTypes = m.getParameterTypes();
        }
        if (m == null) {
            /**
             * If we didn't find anything, maybe we're looking for the actual java.lang.Class methods.
             */
            if ((m = getBestCandidate(args, name, cls, cls.getClass().getDeclaredMethods(), false)) != null) {
                addMethodCache(cls, createSignature(name, tk), m);
                parameterTypes = m.getParameterTypes();
            }
        }
    }
    if (m == null) {
        StringAppender errorBuild = new StringAppender();
        for (int i = 0; i < args.length; i++) {
            errorBuild.append(args[i] != null ? args[i].getClass().getName() : null);
            if (i < args.length - 1)
                errorBuild.append(", ");
        }
        if ("size".equals(name) && args.length == 0 && cls.isArray()) {
            return getLength(ctx);
        }
        System.out.println("{ " + new String(property) + " }");
        throw new PropertyAccessException("unable to resolve method: " + cls.getName() + "." + name + "(" + errorBuild.toString() + ") [arglength=" + args.length + "]", property, st);
    } else {
        for (int i = 0; i < args.length; i++) {
            args[i] = convert(args[i], parameterTypes[i]);
        }
        /**
         * Invoke the target method and return the response.
         */
        try {
            return m.invoke(ctx, args);
        } catch (IllegalAccessException e) {
            try {
                addMethodCache(cls, createSignature(name, tk), (m = getWidenedTarget(m)));
                return m.invoke(ctx, args);
            } catch (Exception e2) {
                throw new PropertyAccessException("unable to invoke method: " + name, property, cursor, e2);
            }
        } catch (RuntimeException e) {
            throw e;
        } catch (Exception e) {
            throw new PropertyAccessException("unable to invoke method: " + name, property, cursor, e);
        }
    }
}
Also used : Function(org.mvel2.ast.Function) Proto(org.mvel2.ast.Proto) MethodStub(org.mvel2.util.MethodStub) StringAppender(org.mvel2.util.StringAppender)

Example 19 with Function

use of org.mvel2.ast.Function in project mvel by mikebrock.

the class ProtoParser method parse.

public Proto parse() {
    Proto proto = new Proto(protoName);
    Mainloop: while (cursor < endOffset) {
        cursor = ParseTools.skipWhitespace(expr, cursor);
        int start = cursor;
        if (tk2 == null) {
            while (cursor < endOffset && isIdentifierPart(expr[cursor])) cursor++;
            if (cursor > start) {
                tk1 = new String(expr, start, cursor - start);
                if ("def".equals(tk1) || "function".equals(tk1)) {
                    cursor++;
                    cursor = ParseTools.skipWhitespace(expr, cursor);
                    start = cursor;
                    while (cursor < endOffset && isIdentifierPart(expr[cursor])) cursor++;
                    if (start == cursor) {
                        throw new CompileException("attempt to declare an anonymous function as a prototype member", expr, start);
                    }
                    FunctionParser parser = new FunctionParser(new String(expr, start, cursor - start), cursor, endOffset, expr, 0, pCtx, null);
                    proto.declareReceiver(parser.getName(), parser.parse());
                    cursor = parser.getCursor() + 1;
                    tk1 = null;
                    continue;
                }
            }
            cursor = ParseTools.skipWhitespace(expr, cursor);
        }
        if (cursor > endOffset) {
            throw new CompileException("unexpected end of statement in proto declaration: " + protoName, expr, start);
        }
        switch(expr[cursor]) {
            case ';':
                cursor++;
                calculateDecl();
                if (interpreted && type == DeferredTypeResolve.class) {
                    /**
                     * If this type could not be immediately resolved, it may be a look-ahead case, so
                     * we defer resolution of the type until later and place it in the wait queue.
                     */
                    enqueueReceiverForLateResolution(deferredName, proto.declareReceiver(name, Proto.ReceiverType.DEFERRED, null), null);
                } else {
                    proto.declareReceiver(name, type, null);
                }
                break;
            case '=':
                cursor++;
                cursor = ParseTools.skipWhitespace(expr, cursor);
                start = cursor;
                Loop: while (cursor < endOffset) {
                    switch(expr[cursor]) {
                        case '{':
                        case '[':
                        case '(':
                        case '\'':
                        case '"':
                            cursor = balancedCaptureWithLineAccounting(expr, cursor, endOffset, expr[cursor], pCtx);
                            break;
                        case ';':
                            break Loop;
                    }
                    cursor++;
                }
                calculateDecl();
                String initString = new String(expr, start, cursor++ - start);
                if (interpreted && type == DeferredTypeResolve.class) {
                    enqueueReceiverForLateResolution(deferredName, proto.declareReceiver(name, Proto.ReceiverType.DEFERRED, null), initString);
                } else {
                    proto.declareReceiver(name, type, (ExecutableStatement) subCompileExpression(initString, pCtx));
                }
                break;
            default:
                start = cursor;
                while (cursor < endOffset && isIdentifierPart(expr[cursor])) cursor++;
                if (cursor > start) {
                    tk2 = new String(expr, start, cursor - start);
                }
        }
    }
    cursor++;
    /**
     * Check if the function is manually terminated.
     */
    if (splitAccumulator != null && ParseTools.isStatementNotManuallyTerminated(expr, cursor)) {
        /**
         * Add an EndOfStatement to the split accumulator in the parser.
         */
        splitAccumulator.add(new EndOfStatement());
    }
    return proto;
}
Also used : ExecutableStatement(org.mvel2.compiler.ExecutableStatement) Proto(org.mvel2.ast.Proto) EndOfStatement(org.mvel2.ast.EndOfStatement) CompileException(org.mvel2.CompileException)

Example 20 with Function

use of org.mvel2.ast.Function in project mvel by mikebrock.

the class FunctionParser method parse.

public Function parse() {
    int start = cursor;
    int startCond = 0;
    int endCond = 0;
    int blockStart;
    int blockEnd;
    int end = cursor + length;
    cursor = ParseTools.captureToNextTokenJunction(expr, cursor, end, pCtx);
    if (expr[cursor = ParseTools.nextNonBlank(expr, cursor)] == '(') {
        /**
         * If we discover an opening bracket after the function name, we check to see
         * if this function accepts parameters.
         */
        endCond = cursor = balancedCaptureWithLineAccounting(expr, startCond = cursor, end, '(', pCtx);
        startCond++;
        cursor++;
        cursor = ParseTools.skipWhitespace(expr, cursor);
        if (cursor >= end) {
            throw new CompileException("incomplete statement", expr, cursor);
        } else if (expr[cursor] == '{') {
            blockEnd = cursor = balancedCaptureWithLineAccounting(expr, blockStart = cursor, end, '{', pCtx);
        } else {
            blockStart = cursor - 1;
            cursor = ParseTools.captureToEOS(expr, cursor, end, pCtx);
            blockEnd = cursor;
        }
    } else {
        /**
         * This function has not parameters.
         */
        if (expr[cursor] == '{') {
            /**
             * This function is bracketed.  We capture the entire range in the brackets.
             */
            blockEnd = cursor = balancedCaptureWithLineAccounting(expr, blockStart = cursor, end, '{', pCtx);
        } else {
            /**
             * This is a single statement function declaration.  We only capture the statement.
             */
            blockStart = cursor - 1;
            cursor = ParseTools.captureToEOS(expr, cursor, end, pCtx);
            blockEnd = cursor;
        }
    }
    /**
     * Trim any whitespace from the captured block range.
     */
    blockStart = ParseTools.trimRight(expr, start, blockStart + 1);
    blockEnd = ParseTools.trimLeft(expr, start, blockEnd);
    cursor++;
    /**
     * Check if the function is manually terminated.
     */
    if (splitAccumulator != null && ParseTools.isStatementNotManuallyTerminated(expr, cursor)) {
        /**
         * Add an EndOfStatement to the split accumulator in the parser.
         */
        splitAccumulator.add(new EndOfStatement());
    }
    /**
     * Produce the funciton node.
     */
    return new Function(name, expr, startCond, endCond - startCond, blockStart, blockEnd - blockStart, fields, pCtx == null ? pCtx = AbstractParser.getCurrentThreadParserContext() : pCtx);
}
Also used : Function(org.mvel2.ast.Function) EndOfStatement(org.mvel2.ast.EndOfStatement) CompileException(org.mvel2.CompileException)

Aggregations

Function (org.mvel2.ast.Function)12 CompileException (org.mvel2.CompileException)10 EndOfStatement (org.mvel2.ast.EndOfStatement)5 StringAppender (org.mvel2.util.StringAppender)5 IOException (java.io.IOException)4 HashMap (java.util.HashMap)4 Proto (org.mvel2.ast.Proto)4 ExecutableStatement (org.mvel2.compiler.ExecutableStatement)4 Serializable (java.io.Serializable)3 Method (java.lang.reflect.Method)3 MapVariableResolverFactory (org.mvel2.integration.impl.MapVariableResolverFactory)3 MethodStub (org.mvel2.util.MethodStub)3 BufferedReader (java.io.BufferedReader)2 StringReader (java.io.StringReader)2 Map (java.util.Map)2 FunctionError (org.drools.compiler.compiler.FunctionError)2 LineMappings (org.drools.core.rule.LineMappings)2 OptimizationFailure (org.mvel2.OptimizationFailure)2 PropertyAccessException (org.mvel2.PropertyAccessException)2 FunctionInstance (org.mvel2.ast.FunctionInstance)2