Search in sources :

Example 1 with IfNode

use of org.mvel2.ast.IfNode in project mvel by mvel.

the class TemplateCompiler method compileFrom.

public Node compileFrom(Node root, ExecutionStack stack) {
    line = 1;
    Node n = root;
    if (root == null) {
        n = root = new TextNode(0, 0);
    }
    IfNode last;
    Integer opcode;
    String name;
    int x;
    try {
        while (cursor < length) {
            switch(template[cursor]) {
                case '\n':
                    line++;
                    colStart = cursor + 1;
                    break;
                case '@':
                case '$':
                    if (isNext(template[cursor])) {
                        start = ++cursor;
                        (n = markTextNode(n)).setEnd(n.getEnd() + 1);
                        start = lastTextRangeEnding = ++cursor;
                        continue;
                    }
                    if ((x = captureOrbToken()) != -1) {
                        start = x;
                        switch((opcode = OPCODES.get(name = new String(capture()))) == null ? 0 : opcode) {
                            case Opcodes.IF:
                                /**
                                 * Capture any residual text node, and push the if statement on the nesting stack.
                                 */
                                stack.push(n = markTextNode(n).next = codeCache ? new CompiledIfNode(start, name, template, captureOrbInternal(), start, parserContext) : new IfNode(start, name, template, captureOrbInternal(), start));
                                n.setTerminus(new TerminalNode());
                                break;
                            case Opcodes.ELSE:
                                if (!stack.isEmpty() && stack.peek() instanceof IfNode) {
                                    markTextNode(n).next = (last = (IfNode) stack.pop()).getTerminus();
                                    last.demarcate(last.getTerminus(), template);
                                    last.next = n = codeCache ? new CompiledIfNode(start, name, template, captureOrbInternal(), start, parserContext) : new IfNode(start, name, template, captureOrbInternal(), start);
                                    n.setTerminus(last.getTerminus());
                                    stack.push(n);
                                }
                                break;
                            case Opcodes.FOREACH:
                                stack.push(n = markTextNode(n).next = codeCache ? new CompiledForEachNode(start, name, template, captureOrbInternal(), start, parserContext) : new ForEachNode(start, name, template, captureOrbInternal(), start));
                                n.setTerminus(new TerminalNode());
                                break;
                            case Opcodes.INCLUDE_FILE:
                                n = markTextNode(n).next = codeCache ? new CompiledIncludeNode(start, name, template, captureOrbInternal(), start = cursor + 1, parserContext) : new IncludeNode(start, name, template, captureOrbInternal(), start = cursor + 1);
                                break;
                            case Opcodes.INCLUDE_NAMED:
                                n = markTextNode(n).next = codeCache ? new CompiledNamedIncludeNode(start, name, template, captureOrbInternal(), start = cursor + 1, parserContext) : new NamedIncludeNode(start, name, template, captureOrbInternal(), start = cursor + 1);
                                break;
                            case Opcodes.CODE:
                                n = markTextNode(n).next = codeCache ? new CompiledCodeNode(start, name, template, captureOrbInternal(), start = cursor + 1, parserContext) : new CodeNode(start, name, template, captureOrbInternal(), start = cursor + 1);
                                break;
                            case Opcodes.EVAL:
                                n = markTextNode(n).next = codeCache ? new CompiledEvalNode(start, name, template, captureOrbInternal(), start = cursor + 1, parserContext) : new EvalNode(start, name, template, captureOrbInternal(), start = cursor + 1);
                                break;
                            case Opcodes.COMMENT:
                                n = markTextNode(n).next = new CommentNode(start, name, template, captureOrbInternal(), start = cursor + 1);
                                break;
                            case Opcodes.DECLARE:
                                stack.push(n = markTextNode(n).next = codeCache ? new CompiledDeclareNode(start, name, template, captureOrbInternal(), start = cursor + 1, parserContext) : new DeclareNode(start, name, template, captureOrbInternal(), start = cursor + 1));
                                n.setTerminus(new TerminalNode());
                                break;
                            case Opcodes.END:
                                n = markTextNode(n);
                                Node end = (Node) stack.pop();
                                Node terminal = end.getTerminus();
                                terminal.setCStart(captureOrbInternal());
                                terminal.setEnd((lastTextRangeEnding = start) - 1);
                                terminal.calculateContents(template);
                                if (end.demarcate(terminal, template))
                                    n = n.next = terminal;
                                else
                                    n = terminal;
                                break;
                            default:
                                if (name.length() == 0) {
                                    n = markTextNode(n).next = codeCache ? new CompiledExpressionNode(start, name, template, captureOrbInternal(), start = cursor + 1, parserContext) : new ExpressionNode(start, name, template, captureOrbInternal(), start = cursor + 1);
                                } else if (customNodes != null && customNodes.containsKey(name)) {
                                    Class<? extends Node> customNode = customNodes.get(name);
                                    try {
                                        (n = markTextNode(n).next = (customNode.newInstance())).setBegin(start);
                                        n.setName(name);
                                        n.setCStart(captureOrbInternal());
                                        n.setCEnd(start = cursor + 1);
                                        n.setEnd(n.getCEnd());
                                        n.setContents(subset(template, n.getCStart(), n.getCEnd() - n.getCStart() - 1));
                                        if (n.isOpenNode()) {
                                            stack.push(n);
                                        }
                                    } catch (InstantiationException e) {
                                        throw new RuntimeException("unable to instantiate custom node class: " + customNode.getName());
                                    } catch (IllegalAccessException e) {
                                        throw new RuntimeException("unable to instantiate custom node class: " + customNode.getName());
                                    }
                                } else {
                                    throw new RuntimeException("unknown token type: " + name);
                                }
                        }
                    }
                    break;
            }
            cursor++;
        }
    } catch (RuntimeException e) {
        CompileException ce = new CompileException(e.getMessage(), template, cursor, e);
        ce.setExpr(template);
        if (e instanceof CompileException) {
            CompileException ce2 = (CompileException) e;
            if (ce2.getCursor() != -1) {
                ce.setCursor(ce2.getCursor());
                if (ce2.getColumn() == -1)
                    ce.setColumn(ce.getCursor() - colStart);
                else
                    ce.setColumn(ce2.getColumn());
            }
        }
        ce.setLineNumber(line);
        throw ce;
    }
    if (!stack.isEmpty()) {
        CompileException ce = new CompileException("unclosed @" + ((Node) stack.peek()).getName() + "{} block. expected @end{}", template, cursor);
        ce.setColumn(cursor - colStart);
        ce.setLineNumber(line);
        throw ce;
    }
    if (start < template.length) {
        n = n.next = new TextNode(start, template.length);
    }
    n.next = new EndNode();
    n = root;
    do {
        if (n.getLength() != 0) {
            break;
        }
    } while ((n = n.getNext()) != null);
    if (n != null && n.getLength() == template.length - 1) {
        if (n instanceof ExpressionNode) {
            return codeCache ? new CompiledTerminalExpressionNode(n, parserContext) : new TerminalExpressionNode(n);
        } else {
            return n;
        }
    }
    return root;
}
Also used : CompileException(org.mvel2.CompileException)

Example 2 with IfNode

use of org.mvel2.ast.IfNode 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 3 with IfNode

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

the class TemplateCompiler method compileFrom.

public Node compileFrom(Node root, ExecutionStack stack) {
    line = 1;
    Node n = root;
    if (root == null) {
        n = root = new TextNode(0, 0);
    }
    IfNode last;
    Integer opcode;
    String name;
    int x;
    try {
        while (cursor < length) {
            switch(template[cursor]) {
                case '\n':
                    line++;
                    colStart = cursor + 1;
                    break;
                case '@':
                case '$':
                    if (isNext(template[cursor])) {
                        start = ++cursor;
                        (n = markTextNode(n)).setEnd(n.getEnd() + 1);
                        start = lastTextRangeEnding = ++cursor;
                        continue;
                    }
                    if ((x = captureOrbToken()) != -1) {
                        start = x;
                        switch((opcode = OPCODES.get(name = new String(capture()))) == null ? 0 : opcode) {
                            case Opcodes.IF:
                                /**
                                 * Capture any residual text node, and push the if statement on the nesting stack.
                                 */
                                stack.push(n = markTextNode(n).next = codeCache ? new CompiledIfNode(start, name, template, captureOrbInternal(), start, parserContext) : new IfNode(start, name, template, captureOrbInternal(), start));
                                n.setTerminus(new TerminalNode());
                                break;
                            case Opcodes.ELSE:
                                if (!stack.isEmpty() && stack.peek() instanceof IfNode) {
                                    markTextNode(n).next = (last = (IfNode) stack.pop()).getTerminus();
                                    last.demarcate(last.getTerminus(), template);
                                    last.next = n = codeCache ? new CompiledIfNode(start, name, template, captureOrbInternal(), start, parserContext) : new IfNode(start, name, template, captureOrbInternal(), start);
                                    n.setTerminus(last.getTerminus());
                                    stack.push(n);
                                }
                                break;
                            case Opcodes.FOREACH:
                                stack.push(n = markTextNode(n).next = codeCache ? new CompiledForEachNode(start, name, template, captureOrbInternal(), start, parserContext) : new ForEachNode(start, name, template, captureOrbInternal(), start));
                                n.setTerminus(new TerminalNode());
                                break;
                            case Opcodes.INCLUDE_FILE:
                                n = markTextNode(n).next = codeCache ? new CompiledIncludeNode(start, name, template, captureOrbInternal(), start = cursor + 1, parserContext) : new IncludeNode(start, name, template, captureOrbInternal(), start = cursor + 1);
                                break;
                            case Opcodes.INCLUDE_NAMED:
                                n = markTextNode(n).next = codeCache ? new CompiledNamedIncludeNode(start, name, template, captureOrbInternal(), start = cursor + 1, parserContext) : new NamedIncludeNode(start, name, template, captureOrbInternal(), start = cursor + 1);
                                break;
                            case Opcodes.CODE:
                                n = markTextNode(n).next = codeCache ? new CompiledCodeNode(start, name, template, captureOrbInternal(), start = cursor + 1, parserContext) : new CodeNode(start, name, template, captureOrbInternal(), start = cursor + 1);
                                break;
                            case Opcodes.EVAL:
                                n = markTextNode(n).next = codeCache ? new CompiledEvalNode(start, name, template, captureOrbInternal(), start = cursor + 1, parserContext) : new EvalNode(start, name, template, captureOrbInternal(), start = cursor + 1);
                                break;
                            case Opcodes.COMMENT:
                                n = markTextNode(n).next = new CommentNode(start, name, template, captureOrbInternal(), start = cursor + 1);
                                break;
                            case Opcodes.DECLARE:
                                stack.push(n = markTextNode(n).next = codeCache ? new CompiledDeclareNode(start, name, template, captureOrbInternal(), start = cursor + 1, parserContext) : new DeclareNode(start, name, template, captureOrbInternal(), start = cursor + 1));
                                n.setTerminus(new TerminalNode());
                                break;
                            case Opcodes.END:
                                n = markTextNode(n);
                                Node end = (Node) stack.pop();
                                Node terminal = end.getTerminus();
                                terminal.setCStart(captureOrbInternal());
                                terminal.setEnd((lastTextRangeEnding = start) - 1);
                                terminal.calculateContents(template);
                                if (end.demarcate(terminal, template))
                                    n = n.next = terminal;
                                else
                                    n = terminal;
                                break;
                            default:
                                if (name.length() == 0) {
                                    n = markTextNode(n).next = codeCache ? new CompiledExpressionNode(start, name, template, captureOrbInternal(), start = cursor + 1, parserContext) : new ExpressionNode(start, name, template, captureOrbInternal(), start = cursor + 1);
                                } else if (customNodes != null && customNodes.containsKey(name)) {
                                    Class<? extends Node> customNode = customNodes.get(name);
                                    try {
                                        (n = markTextNode(n).next = (customNode.newInstance())).setBegin(start);
                                        n.setName(name);
                                        n.setCStart(captureOrbInternal());
                                        n.setCEnd(start = cursor + 1);
                                        n.setEnd(n.getCEnd());
                                        n.setContents(subset(template, n.getCStart(), n.getCEnd() - n.getCStart() - 1));
                                        if (n.isOpenNode()) {
                                            stack.push(n);
                                        }
                                    } catch (InstantiationException e) {
                                        throw new RuntimeException("unable to instantiate custom node class: " + customNode.getName());
                                    } catch (IllegalAccessException e) {
                                        throw new RuntimeException("unable to instantiate custom node class: " + customNode.getName());
                                    }
                                } else {
                                    throw new RuntimeException("unknown token type: " + name);
                                }
                        }
                    }
                    break;
            }
            cursor++;
        }
    } catch (RuntimeException e) {
        CompileException ce = new CompileException(e.getMessage(), template, cursor, e);
        ce.setExpr(template);
        if (e instanceof CompileException) {
            CompileException ce2 = (CompileException) e;
            if (ce2.getCursor() != -1) {
                ce.setCursor(ce2.getCursor());
                if (ce2.getColumn() == -1)
                    ce.setColumn(ce.getCursor() - colStart);
                else
                    ce.setColumn(ce2.getColumn());
            }
        }
        ce.setLineNumber(line);
        throw ce;
    }
    if (!stack.isEmpty()) {
        CompileException ce = new CompileException("unclosed @" + ((Node) stack.peek()).getName() + "{} block. expected @end{}", template, cursor);
        ce.setColumn(cursor - colStart);
        ce.setLineNumber(line);
        throw ce;
    }
    if (start < template.length) {
        n = n.next = new TextNode(start, template.length);
    }
    n.next = new EndNode();
    n = root;
    do {
        if (n.getLength() != 0) {
            break;
        }
    } while ((n = n.getNext()) != null);
    if (n != null && n.getLength() == template.length - 1) {
        if (n instanceof ExpressionNode) {
            return codeCache ? new CompiledTerminalExpressionNode(n, parserContext) : new TerminalExpressionNode(n);
        } else {
            return n;
        }
    }
    return root;
}
Also used : CompileException(org.mvel2.CompileException)

Example 4 with IfNode

use of org.mvel2.ast.IfNode in project mvel by mvel.

the class AbstractParser method createBlockToken.

/**
 * Generate a code block token.
 *
 * @param condStart  the start offset for the condition
 * @param condEnd    the end offset for the condition
 * @param blockStart the start offset for the block
 * @param blockEnd   the end offset for the block
 * @param type       the type of block
 * @return and ast node
 */
private ASTNode createBlockToken(final int condStart, final int condEnd, final int blockStart, final int blockEnd, int type) {
    lastWasIdentifier = false;
    cursor++;
    if (isStatementNotManuallyTerminated()) {
        splitAccumulator.add(new EndOfStatement(pCtx));
    }
    int condOffset = condEnd - condStart;
    int blockOffset = blockEnd - blockStart;
    if (blockOffset < 0)
        blockOffset = 0;
    switch(type) {
        case ASTNode.BLOCK_IF:
            return new IfNode(expr, condStart, condOffset, blockStart, blockOffset, fields, pCtx);
        case ASTNode.BLOCK_FOR:
            for (int i = condStart; i < condEnd; i++) {
                if (expr[i] == ';')
                    return new ForNode(expr, condStart, condOffset, blockStart, blockOffset, fields, pCtx);
                else if (expr[i] == ':')
                    break;
            }
        case ASTNode.BLOCK_FOREACH:
            return new ForEachNode(expr, condStart, condOffset, blockStart, blockOffset, fields, pCtx);
        case ASTNode.BLOCK_WHILE:
            return new WhileNode(expr, condStart, condOffset, blockStart, blockOffset, fields, pCtx);
        case ASTNode.BLOCK_UNTIL:
            return new UntilNode(expr, condStart, condOffset, blockStart, blockOffset, fields, pCtx);
        case ASTNode.BLOCK_DO:
            return new DoNode(expr, condStart, condOffset, blockStart, blockOffset, fields, pCtx);
        case ASTNode.BLOCK_DO_UNTIL:
            return new DoUntilNode(expr, condStart, condOffset, blockStart, blockOffset, pCtx);
        default:
            return new WithNode(expr, condStart, condOffset, blockStart, blockOffset, fields, pCtx);
    }
}
Also used : UntilNode(org.mvel2.ast.UntilNode) DoUntilNode(org.mvel2.ast.DoUntilNode) ForNode(org.mvel2.ast.ForNode) EndOfStatement(org.mvel2.ast.EndOfStatement) DoNode(org.mvel2.ast.DoNode) WhileNode(org.mvel2.ast.WhileNode) ForEachNode(org.mvel2.ast.ForEachNode) IfNode(org.mvel2.ast.IfNode) DoUntilNode(org.mvel2.ast.DoUntilNode) WithNode(org.mvel2.ast.WithNode) ThisWithNode(org.mvel2.ast.ThisWithNode)

Example 5 with IfNode

use of org.mvel2.ast.IfNode in project mvel by mvel.

the class AbstractParser method captureCodeBlock.

/**
 * Capture a code block by type.
 *
 * @param type the block type
 * @return an ast node
 */
private ASTNode captureCodeBlock(int type) {
    boolean cond = true;
    ASTNode first = null;
    ASTNode tk = null;
    switch(type) {
        case ASTNode.BLOCK_IF:
            {
                do {
                    if (tk != null) {
                        captureToNextTokenJunction();
                        skipWhitespace();
                        cond = expr[cursor] != '{' && expr[cursor] == 'i' && expr[++cursor] == 'f' && expr[cursor = incNextNonBlank()] == '(';
                    }
                    if (((IfNode) (tk = _captureBlock(tk, expr, cond, type))).getElseBlock() != null) {
                        cursor++;
                        return first;
                    }
                    if (first == null)
                        first = tk;
                    if (cursor != end && expr[cursor] != ';') {
                        cursor++;
                    }
                } while (ifThenElseBlockContinues());
                return first;
            }
        case ASTNode.BLOCK_DO:
            skipWhitespace();
            return _captureBlock(null, expr, false, type);
        default:
            // either BLOCK_WITH or BLOCK_FOREACH
            captureToNextTokenJunction();
            skipWhitespace();
            return _captureBlock(null, expr, true, type);
    }
}
Also used : ASTNode(org.mvel2.ast.ASTNode) IfNode(org.mvel2.ast.IfNode)

Aggregations

CompileException (org.mvel2.CompileException)4 IfNode (org.mvel2.ast.IfNode)3 FunctionParser (org.mvel2.util.FunctionParser)2 ProtoParser (org.mvel2.util.ProtoParser)2 ASTNode (org.mvel2.ast.ASTNode)1 DoNode (org.mvel2.ast.DoNode)1 DoUntilNode (org.mvel2.ast.DoUntilNode)1 EndOfStatement (org.mvel2.ast.EndOfStatement)1 ForEachNode (org.mvel2.ast.ForEachNode)1 ForNode (org.mvel2.ast.ForNode)1 Function (org.mvel2.ast.Function)1 Proto (org.mvel2.ast.Proto)1 Stacklang (org.mvel2.ast.Stacklang)1 ThisWithNode (org.mvel2.ast.ThisWithNode)1 UntilNode (org.mvel2.ast.UntilNode)1 WhileNode (org.mvel2.ast.WhileNode)1 WithNode (org.mvel2.ast.WithNode)1