jdk.nashorn.internal.ir.Statement Java Examples

The following examples show how to use jdk.nashorn.internal.ir.Statement. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: JSONWriter.java    From TencentKona-8 with GNU General Public License v2.0 6 votes vote down vote up
private boolean emitProgram(final FunctionNode functionNode) {
    enterDefault(functionNode);
    type("Program");
    comma();

    // body consists of nested functions and statements
    final List<Statement> stats = functionNode.getBody().getStatements();
    final int size = stats.size();
    int idx = 0;
    arrayStart("body");

    for (final Node stat : stats) {
        stat.accept(this);
        if (idx != (size - 1)) {
            comma();
        }
        idx++;
    }
    arrayEnd();

    return leave();
}
 
Example #2
Source File: FoldConstants.java    From hottub with GNU General Public License v2.0 6 votes vote down vote up
/**
 * When we eliminate dead code, we must preserve var declarations as they are scoped to the whole
 * function. This method gathers var nodes from code passed to it, removing their initializers.
 *
 * @param deadCodeRoot the root node of eliminated dead code
 * @param statements a list that will be receiving the var nodes from the dead code, with their
 * initializers removed.
 */
static void extractVarNodesFromDeadCode(final Node deadCodeRoot, final List<Statement> statements) {
    deadCodeRoot.accept(new SimpleNodeVisitor() {
        @Override
        public boolean enterVarNode(final VarNode varNode) {
            statements.add(varNode.setInit(null));
            return false;
        }

        @Override
        public boolean enterFunctionNode(final FunctionNode functionNode) {
            // Don't descend into nested functions
            return false;
        }
    });
}
 
Example #3
Source File: FoldConstants.java    From hottub with GNU General Public License v2.0 6 votes vote down vote up
@Override
public Node leaveIfNode(final IfNode ifNode) {
    final Node test = ifNode.getTest();
    if (test instanceof LiteralNode.PrimitiveLiteralNode) {
        final boolean isTrue = ((LiteralNode.PrimitiveLiteralNode<?>)test).isTrue();
        final Block executed = isTrue ? ifNode.getPass() : ifNode.getFail();
        final Block dropped  = isTrue ? ifNode.getFail() : ifNode.getPass();
        final List<Statement> statements = new ArrayList<>();

        if (executed != null) {
            statements.addAll(executed.getStatements()); // Get statements form executed branch
        }
        if (dropped != null) {
            extractVarNodesFromDeadCode(dropped, statements); // Get var-nodes from non-executed branch
        }
        if (statements.isEmpty()) {
            return new EmptyNode(ifNode);
        }
        return BlockStatement.createReplacement(ifNode, ifNode.getFinish(), statements);
    }
    return ifNode;
}
 
Example #4
Source File: JSONWriter.java    From jdk8u60 with GNU General Public License v2.0 6 votes vote down vote up
private boolean emitProgram(final FunctionNode functionNode) {
    enterDefault(functionNode);
    type("Program");
    comma();

    // body consists of nested functions and statements
    final List<Statement> stats = functionNode.getBody().getStatements();
    final int size = stats.size();
    int idx = 0;
    arrayStart("body");

    for (final Node stat : stats) {
        stat.accept(this);
        if (idx != (size - 1)) {
            comma();
        }
        idx++;
    }
    arrayEnd();

    return leave();
}
 
Example #5
Source File: FoldConstants.java    From openjdk-jdk9 with GNU General Public License v2.0 6 votes vote down vote up
/**
 * When we eliminate dead code, we must preserve var declarations as they are scoped to the whole
 * function. This method gathers var nodes from code passed to it, removing their initializers.
 *
 * @param deadCodeRoot the root node of eliminated dead code
 * @param statements a list that will be receiving the var nodes from the dead code, with their
 * initializers removed.
 */
static void extractVarNodesFromDeadCode(final Node deadCodeRoot, final List<Statement> statements) {
    deadCodeRoot.accept(new SimpleNodeVisitor() {
        @Override
        public boolean enterVarNode(final VarNode varNode) {
            statements.add(varNode.setInit(null));
            return false;
        }

        @Override
        public boolean enterFunctionNode(final FunctionNode functionNode) {
            // Don't descend into nested functions
            return false;
        }
    });
}
 
Example #6
Source File: JSONWriter.java    From openjdk-8 with GNU General Public License v2.0 6 votes vote down vote up
private boolean emitProgram(final FunctionNode functionNode) {
    enterDefault(functionNode);
    type("Program");
    comma();

    // body consists of nested functions and statements
    final List<Statement> stats = functionNode.getBody().getStatements();
    final int size = stats.size();
    int idx = 0;
    arrayStart("body");

    for (final Node stat : stats) {
        stat.accept(this);
        if (idx != (size - 1)) {
            comma();
        }
        idx++;
    }
    arrayEnd();

    return leave();
}
 
Example #7
Source File: FoldConstants.java    From openjdk-jdk8u-backup with GNU General Public License v2.0 6 votes vote down vote up
/**
 * When we eliminate dead code, we must preserve var declarations as they are scoped to the whole
 * function. This method gathers var nodes from code passed to it, removing their initializers.
 *
 * @param deadCodeRoot the root node of eliminated dead code
 * @param statements a list that will be receiving the var nodes from the dead code, with their
 * initializers removed.
 */
static void extractVarNodesFromDeadCode(final Node deadCodeRoot, final List<Statement> statements) {
    deadCodeRoot.accept(new SimpleNodeVisitor() {
        @Override
        public boolean enterVarNode(final VarNode varNode) {
            statements.add(varNode.setInit(null));
            return false;
        }

        @Override
        public boolean enterFunctionNode(final FunctionNode functionNode) {
            // Don't descend into nested functions
            return false;
        }
    });
}
 
Example #8
Source File: Lower.java    From openjdk-8-source with GNU General Public License v2.0 6 votes vote down vote up
@Override
public Node leaveBlock(final Block block) {
    //now we have committed the entire statement list to the block, but we need to truncate
    //whatever is after the last terminal. block append won't append past it


    if (lc.isFunctionBody()) {
        final FunctionNode currentFunction = lc.getCurrentFunction();
        final boolean isProgram = currentFunction.isProgram();
        final Statement last = lc.getLastStatement();
        final ReturnNode returnNode = new ReturnNode(
            last == null ? currentFunction.getLineNumber() : last.getLineNumber(), //TODO?
            currentFunction.getToken(),
            currentFunction.getFinish(),
            isProgram ?
                compilerConstant(RETURN) :
                LiteralNode.newInstance(block, ScriptRuntime.UNDEFINED));

        returnNode.accept(this);
    }

    return block;
}
 
Example #9
Source File: FoldConstants.java    From jdk8u60 with GNU General Public License v2.0 6 votes vote down vote up
@Override
public Node leaveIfNode(final IfNode ifNode) {
    final Node test = ifNode.getTest();
    if (test instanceof LiteralNode.PrimitiveLiteralNode) {
        final boolean isTrue = ((LiteralNode.PrimitiveLiteralNode<?>)test).isTrue();
        final Block executed = isTrue ? ifNode.getPass() : ifNode.getFail();
        final Block dropped  = isTrue ? ifNode.getFail() : ifNode.getPass();
        final List<Statement> statements = new ArrayList<>();

        if (executed != null) {
            statements.addAll(executed.getStatements()); // Get statements form executed branch
        }
        if (dropped != null) {
            extractVarNodes(dropped, statements); // Get var-nodes from non-executed branch
        }
        if (statements.isEmpty()) {
            return new EmptyNode(ifNode);
        }
        return BlockStatement.createReplacement(ifNode, ifNode.getFinish(), statements);
    }
    return ifNode;
}
 
Example #10
Source File: JSONWriter.java    From openjdk-jdk8u-backup with GNU General Public License v2.0 6 votes vote down vote up
private boolean emitProgram(final FunctionNode functionNode) {
    enterDefault(functionNode);
    type("Program");
    comma();

    // body consists of nested functions and statements
    final List<Statement> stats = functionNode.getBody().getStatements();
    final int size = stats.size();
    int idx = 0;
    arrayStart("body");

    for (final Node stat : stats) {
        stat.accept(this);
        if (idx != (size - 1)) {
            comma();
        }
        idx++;
    }
    arrayEnd();

    return leave();
}
 
Example #11
Source File: Lower.java    From jdk8u_nashorn with GNU General Public License v2.0 5 votes vote down vote up
private static Block prependFinally(final Block finallyBlock, final Statement statement) {
    final Block inlinedFinally = ensureUniqueNamesIn(finallyBlock);
    if (isTerminalFinally(finallyBlock)) {
        return inlinedFinally;
    }
    final List<Statement> stmts = inlinedFinally.getStatements();
    final List<Statement> newStmts = new ArrayList<>(stmts.size() + 1);
    newStmts.addAll(stmts);
    newStmts.add(statement);
    return new Block(inlinedFinally.getToken(), statement.getFinish(), newStmts);
}
 
Example #12
Source File: Parser.java    From TencentKona-8 with GNU General Public License v2.0 5 votes vote down vote up
private void addFunctionDeclarations(final FunctionNode functionNode) {
    VarNode lastDecl = null;
    for (int i = functionDeclarations.size() - 1; i >= 0; i--) {
        Statement decl = functionDeclarations.get(i);
        if (lastDecl == null && decl instanceof VarNode) {
            decl = lastDecl = ((VarNode)decl).setFlag(VarNode.IS_LAST_FUNCTION_DECLARATION);
            lc.setFlag(functionNode, FunctionNode.HAS_FUNCTION_DECLARATIONS);
        }
        prependStatement(decl);
    }
}
 
Example #13
Source File: SplitIntoFunctions.java    From openjdk-jdk8u-backup with GNU General Public License v2.0 5 votes vote down vote up
@Override
protected Node leaveDefault(final Node node) {
    if (node instanceof Statement) {
        appendStatement((Statement)node);
    }
    return node;
}
 
Example #14
Source File: Lower.java    From hottub with GNU General Public License v2.0 5 votes vote down vote up
private static Block createFinallyBlock(final Block finallyBody) {
    final List<Statement> newStatements = new ArrayList<>();
    for (final Statement statement : finallyBody.getStatements()) {
        newStatements.add(statement);
        if (statement.hasTerminalFlags()) {
            break;
        }
    }
    return finallyBody.setStatements(null, newStatements);
}
 
Example #15
Source File: InstagramRipper.java    From ripme with MIT License 5 votes vote down vote up
private String getHashValue(String javaScriptData, String keyword, int offset) {
    List<Statement> statements = getJsBodyBlock(javaScriptData).getStatements();
    return statements.stream()
                     .flatMap(statement -> filterItems(statement, ExpressionStatement.class))
                     .map(ExpressionStatement::getExpression)
                     .flatMap(expression -> filterItems(expression, CallNode.class))
                     .map(CallNode::getArgs)
                     .map(expressions -> expressions.get(0))
                     .flatMap(expression -> filterItems(expression, FunctionNode.class))
                     .map(FunctionNode::getBody)
                     .map(Block::getStatements)
                     .map(statementList -> lookForHash(statementList, keyword, offset))
                     .filter(Objects::nonNull)
                     .findFirst().orElse(null);
}
 
Example #16
Source File: Lower.java    From openjdk-jdk8u-backup with GNU General Public License v2.0 5 votes vote down vote up
private void addStatementEnclosedInBlock(final Statement stmt) {
    BlockStatement b = BlockStatement.createReplacement(stmt, Collections.<Statement>singletonList(stmt));
    if(stmt.isTerminal()) {
        b = b.setBlock(b.getBlock().setIsTerminal(null, true));
    }
    addStatement(b);
}
 
Example #17
Source File: Lower.java    From openjdk-jdk8u-backup with GNU General Public License v2.0 5 votes vote down vote up
private static Block prependFinally(final Block finallyBlock, final Statement statement) {
    final Block inlinedFinally = ensureUniqueNamesIn(finallyBlock);
    if (isTerminalFinally(finallyBlock)) {
        return inlinedFinally;
    }
    final List<Statement> stmts = inlinedFinally.getStatements();
    final List<Statement> newStmts = new ArrayList<>(stmts.size() + 1);
    newStmts.addAll(stmts);
    newStmts.add(statement);
    return new Block(inlinedFinally.getToken(), statement.getFinish(), newStmts);
}
 
Example #18
Source File: FoldConstants.java    From openjdk-8-source with GNU General Public License v2.0 5 votes vote down vote up
private static void extractVarNodes(final Block block, final List<Statement> statements) {
    final LexicalContext lc = new LexicalContext();
    block.accept(lc, new NodeVisitor<LexicalContext>(lc) {
        @Override
        public boolean enterVarNode(VarNode varNode) {
            statements.add(varNode.setInit(null));
            return false;
        }
    });
}
 
Example #19
Source File: SplitIntoFunctions.java    From openjdk-jdk8u-backup with GNU General Public License v2.0 5 votes vote down vote up
private static IfNode makeIfStateEquals(final int lineNumber, final long token, final int finish,
        final int value, final Block pass, final Statement fail) {
    return new IfNode(lineNumber, token, finish,
            new BinaryNode(Token.recast(token, TokenType.EQ_STRICT),
                    GetSplitState.INSTANCE, intLiteral(value)),
            pass,
            fail == null ? null : new Block(NO_TOKEN, NO_FINISH, fail));
}
 
Example #20
Source File: Attr.java    From openjdk-8 with GNU General Public License v2.0 5 votes vote down vote up
private <T extends Node> T end(final T node, final boolean printNode) {
    if(node instanceof Statement) {
        // If we're done with a statement, all temporaries can be reused.
        temporarySymbols.reuse();
    }
    if (DEBUG) {
        final StringBuilder sb = new StringBuilder();

        sb.append("[LEAVE ").
            append(name(node)).
            append("] ").
            append(printNode ? node.toString() : "").
            append(" in '").
            append(lc.getCurrentFunction().getName()).
            append('\'');

        if (node instanceof Expression) {
            final Symbol symbol = ((Expression)node).getSymbol();
            if (symbol == null) {
                sb.append(" <NO SYMBOL>");
            } else {
                sb.append(" <symbol=").append(symbol).append('>');
            }
        }

        LOG.unindent();
        LOG.info(sb);
    }

    return node;
}
 
Example #21
Source File: IRTranslator.java    From openjdk-jdk9 with GNU General Public License v2.0 5 votes vote down vote up
private List<? extends StatementTree> translateStats(final List<? extends Statement> stats) {
    if (stats == null) {
        return null;
    }
    final List<StatementTreeImpl> statTrees = new ArrayList<>(stats.size());
    for (final Statement stat : stats) {
        curStat = null;
        stat.accept(this);
        assert curStat != null;
        statTrees.add(curStat);
    }
    return statTrees;
}
 
Example #22
Source File: Splitter.java    From openjdk-jdk8u with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Split a block into sub methods.
 *
 * @param block Block or function to split.
 *
 * @return new weight for the resulting block.
 */
private Block splitBlock(final Block block, final FunctionNode function) {

    final List<Statement> splits = new ArrayList<>();
    List<Statement> statements = new ArrayList<>();
    long statementsWeight = 0;

    for (final Statement statement : block.getStatements()) {
        final long weight = WeighNodes.weigh(statement, weightCache);

        if (statementsWeight + weight >= SPLIT_THRESHOLD || statement.isTerminal()) {
            if (!statements.isEmpty()) {
                splits.add(createBlockSplitNode(block, function, statements, statementsWeight));
                statements = new ArrayList<>();
                statementsWeight = 0;
            }
        }

        if (statement.isTerminal()) {
            splits.add(statement);
        } else {
            statements.add(statement);
            statementsWeight += weight;
        }
    }

    if (!statements.isEmpty()) {
        splits.add(createBlockSplitNode(block, function, statements, statementsWeight));
    }

    return block.setStatements(lc, splits);
}
 
Example #23
Source File: CacheAst.java    From openjdk-jdk8u with GNU General Public License v2.0 5 votes vote down vote up
@Override
public Node leaveFunctionNode(final FunctionNode functionNode) {
    final RecompilableScriptFunctionData data = dataStack.pop();
    if (functionNode.isSplit()) {
        // NOTE: cache only split function ASTs from eager pass. Caching non-split functions would require
        // some additional work, namely creating the concept of "uncacheable" function and reworking
        // ApplySpecialization to ensure that functions undergoing apply-to-call transformations are not
        // cacheable as well as recomputing Symbol.useCount when caching the eagerly parsed AST.
        // Recomputing Symbol.useCount would be needed so it will only reflect uses from within the
        // function being cached (and not reflect uses from its own nested functions or functions it is
        // nested in). This is consistent with the count an on-demand recompilation of the function would
        // produce. This is important as the decision to emit shared scope calls is based on this count,
        // and if it is not matched between a previous version of the code and its deoptimizing rest-of
        // compilation, it can result in rest-of not emitting a shared scope call where a previous version
        // of the code (compiled from a cached eager pre-pass seeing higher (global) useCount) would emit
        // it, causing a mismatch in stack shapes between previous code and its rest-of.
        data.setCachedAst(functionNode);
    }

    if (!dataStack.isEmpty() && ((dataStack.peek().getFunctionFlags() & FunctionNode.IS_SPLIT) != 0)) {
        // Return a function node with no body so that caching outer functions doesn't hold on to nested
        // functions' bodies. Note we're doing this only for functions directly nested inside split
        // functions, since we're only caching the split ones. It is not necessary to limit body removal
        // to just these functions, but it's a cheap way to prevent unnecessary AST mutations.
        return functionNode.setBody(lc, functionNode.getBody().setStatements(null, Collections.<Statement>emptyList()));
    }
    return functionNode;
}
 
Example #24
Source File: Lower.java    From openjdk-jdk8u with GNU General Public License v2.0 5 votes vote down vote up
private static Block createFinallyBlock(final Block finallyBody) {
    final List<Statement> newStatements = new ArrayList<>();
    for (final Statement statement : finallyBody.getStatements()) {
        newStatements.add(statement);
        if (statement.hasTerminalFlags()) {
            break;
        }
    }
    return finallyBody.setStatements(null, newStatements);
}
 
Example #25
Source File: Lower.java    From hottub with GNU General Public License v2.0 5 votes vote down vote up
private void addStatementEnclosedInBlock(final Statement stmt) {
    BlockStatement b = BlockStatement.createReplacement(stmt, Collections.<Statement>singletonList(stmt));
    if(stmt.isTerminal()) {
        b = b.setBlock(b.getBlock().setIsTerminal(null, true));
    }
    addStatement(b);
}
 
Example #26
Source File: Splitter.java    From openjdk-jdk9 with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Split a block into sub methods.
 *
 * @param block Block or function to split.
 *
 * @return new weight for the resulting block.
 */
private Block splitBlock(final Block block, final FunctionNode function) {

    final List<Statement> splits = new ArrayList<>();
    List<Statement> statements = new ArrayList<>();
    long statementsWeight = 0;

    for (final Statement statement : block.getStatements()) {
        final long weight = WeighNodes.weigh(statement, weightCache);

        if (statementsWeight + weight >= SPLIT_THRESHOLD || statement.isTerminal()) {
            if (!statements.isEmpty()) {
                splits.add(createBlockSplitNode(block, function, statements, statementsWeight));
                statements = new ArrayList<>();
                statementsWeight = 0;
            }
        }

        if (statement.isTerminal()) {
            splits.add(statement);
        } else {
            statements.add(statement);
            statementsWeight += weight;
        }
    }

    if (!statements.isEmpty()) {
        splits.add(createBlockSplitNode(block, function, statements, statementsWeight));
    }

    return block.setStatements(lc, splits);
}
 
Example #27
Source File: Parser.java    From hottub with GNU General Public License v2.0 5 votes vote down vote up
private void addFunctionDeclarations(final FunctionNode functionNode) {
    VarNode lastDecl = null;
    for (int i = functionDeclarations.size() - 1; i >= 0; i--) {
        Statement decl = functionDeclarations.get(i);
        if (lastDecl == null && decl instanceof VarNode) {
            decl = lastDecl = ((VarNode)decl).setFlag(VarNode.IS_LAST_FUNCTION_DECLARATION);
            lc.setFlag(functionNode, FunctionNode.HAS_FUNCTION_DECLARATIONS);
        }
        prependStatement(decl);
    }
}
 
Example #28
Source File: LocalVariableTypesCalculator.java    From jdk8u60 with GNU General Public License v2.0 5 votes vote down vote up
private void createSyntheticReturn(final Block body) {
    final FunctionNode functionNode = lc.getCurrentFunction();
    final long token = functionNode.getToken();
    final int finish = functionNode.getFinish();
    final List<Statement> statements = body.getStatements();
    final int lineNumber = statements.isEmpty() ? functionNode.getLineNumber() : statements.get(statements.size() - 1).getLineNumber();
    final IdentNode returnExpr;
    if(functionNode.isProgram()) {
        returnExpr = new IdentNode(token, finish, RETURN.symbolName()).setSymbol(getCompilerConstantSymbol(functionNode, RETURN));
    } else {
        returnExpr = null;
    }
    syntheticReturn = new ReturnNode(lineNumber, token, finish, returnExpr);
    syntheticReturn.accept(this);
}
 
Example #29
Source File: Lower.java    From openjdk-8 with GNU General Public License v2.0 5 votes vote down vote up
private static List<Statement> copyFinally(final Block finallyBody) {
    final List<Statement> newStatements = new ArrayList<>();
    for (final Statement statement : finallyBody.getStatements()) {
        newStatements.add((Statement)ensureUniqueNamesIn(statement));
        if (statement.hasTerminalFlags()) {
            return newStatements;
        }
    }
    return newStatements;
}
 
Example #30
Source File: Splitter.java    From jdk8u60 with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Create a new split node from statements contained in a parent block.
 *
 * @param parent     Parent block.
 * @param statements Statements to include.
 *
 * @return New split node.
 */
private SplitNode createBlockSplitNode(final Block parent, final FunctionNode function, final List<Statement> statements, final long weight) {
    final long   token      = parent.getToken();
    final int    finish     = parent.getFinish();
    final String name       = function.uniqueName(SPLIT_PREFIX.symbolName());

    final Block newBlock = new Block(token, finish, statements);

    return new SplitNode(name, newBlock, compiler.findUnit(weight + WeighNodes.FUNCTION_WEIGHT));
}