jdk.nashorn.internal.ir.IdentNode Java Examples

The following examples show how to use jdk.nashorn.internal.ir.IdentNode. 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: OptimisticTypesCalculator.java    From openjdk-jdk8u-backup with GNU General Public License v2.0 6 votes vote down vote up
@Override
public Node leaveIdentNode(final IdentNode identNode) {
    final Symbol symbol = identNode.getSymbol();
    if(symbol == null) {
        assert identNode.isPropertyName();
        return identNode;
    } else if(symbol.isBytecodeLocal()) {
        // Identifiers accessing bytecode local variables will never be optimistic, as type calculation phase over
        // them will always assign them statically provable types. Note that access to function parameters can still
        // be optimistic if the parameter needs to be in scope as it's used by a nested function.
        return identNode;
    } else if(symbol.isParam() && lc.getCurrentFunction().isVarArg()) {
        // Parameters in vararg methods are not optimistic; we always access them using Object getters.
        return identNode.setType(identNode.getMostPessimisticType());
    } else {
        assert symbol.isScope();
        return leaveOptimistic(identNode);
    }
}
 
Example #2
Source File: Lower.java    From hottub with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Check whether a call node may be a call to eval. In that case we
 * clone the args in order to create the following construct in
 * {@link CodeGenerator}
 *
 * <pre>
 * if (calledFuntion == buildInEval) {
 *    eval(cloned arg);
 * } else {
 *    cloned arg;
 * }
 * </pre>
 *
 * @param callNode call node to check if it's an eval
 */
private CallNode checkEval(final CallNode callNode) {
    if (callNode.getFunction() instanceof IdentNode) {

        final List<Expression> args = callNode.getArgs();
        final IdentNode callee = (IdentNode)callNode.getFunction();

        // 'eval' call with at least one argument
        if (args.size() >= 1 && EVAL.symbolName().equals(callee.getName())) {
            final List<Expression> evalArgs = new ArrayList<>(args.size());
            for(final Expression arg: args) {
                evalArgs.add((Expression)ensureUniqueNamesIn(arg).accept(this));
            }
            return callNode.setEvalArgs(new CallNode.EvalArgs(evalArgs, evalLocation(callee)));
        }
    }

    return callNode;
}
 
Example #3
Source File: Parser.java    From TencentKona-8 with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Convert execString to a call to $EXEC.
 *
 * @param primaryToken Original string token.
 * @return callNode to $EXEC.
 */
CallNode execString(final int primaryLine, final long primaryToken) {
    // Synthesize an ident to call $EXEC.
    final IdentNode execIdent = new IdentNode(primaryToken, finish, ScriptingFunctions.EXEC_NAME);
    // Skip over EXECSTRING.
    next();
    // Set up argument list for call.
    // Skip beginning of edit string expression.
    expect(LBRACE);
    // Add the following expression to arguments.
    final List<Expression> arguments = Collections.singletonList(expression());
    // Skip ending of edit string expression.
    expect(RBRACE);

    return new CallNode(primaryLine, primaryToken, finish, execIdent, arguments, false);
}
 
Example #4
Source File: AssignSymbols.java    From openjdk-jdk8u with GNU General Public License v2.0 6 votes vote down vote up
private Node leaveTYPEOF(final UnaryNode unaryNode) {
    final Expression rhs = unaryNode.getExpression();

    final List<Expression> args = new ArrayList<>();
    if (rhs instanceof IdentNode && !isParamOrVar((IdentNode)rhs)) {
        args.add(compilerConstantIdentifier(SCOPE));
        args.add(LiteralNode.newInstance(rhs, ((IdentNode)rhs).getName())); //null
    } else {
        args.add(rhs);
        args.add(LiteralNode.newInstance(unaryNode)); //null, do not reuse token of identifier rhs, it can be e.g. 'this'
    }

    final Node runtimeNode = new RuntimeNode(unaryNode, Request.TYPEOF, args);

    end(unaryNode);

    return runtimeNode;
}
 
Example #5
Source File: Parser.java    From jdk8u_nashorn with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Make sure that in strict mode, the identifier name used is allowed.
 *
 * @param ident         Identifier that is verified
 * @param contextString String used in error message to give context to the user
 */
private void verifyStrictIdent(final IdentNode ident, final String contextString) {
    if (isStrictMode) {
        switch (ident.getName()) {
        case "eval":
        case "arguments":
            throw error(AbstractParser.message("strict.name", ident.getName(), contextString), ident.getToken());
        default:
            break;
        }

        if (ident.isFutureStrictName()) {
            throw error(AbstractParser.message("strict.name", ident.getName(), contextString), ident.getToken());
        }
    }
}
 
Example #6
Source File: TypeEvaluator.java    From TencentKona-8 with GNU General Public License v2.0 6 votes vote down vote up
private Object evaluateSafely(final Expression expr) {
    if (expr instanceof IdentNode) {
        return runtimeScope == null ? null : evaluatePropertySafely(runtimeScope, ((IdentNode)expr).getName());
    }

    if (expr instanceof AccessNode) {
        final AccessNode accessNode = (AccessNode)expr;
        final Object     base       = evaluateSafely(accessNode.getBase());
        if (!(base instanceof ScriptObject)) {
            return null;
        }
        return evaluatePropertySafely((ScriptObject)base, accessNode.getProperty());
    }

    return null;
}
 
Example #7
Source File: JSONWriter.java    From nashorn with GNU General Public License v2.0 6 votes vote down vote up
@Override
public boolean enterContinueNode(final ContinueNode continueNode) {
    enterDefault(continueNode);

    type("ContinueStatement");
    comma();

    final IdentNode label = continueNode.getLabel();
    property("label");
    if (label != null) {
        label.accept(this);
    } else {
        nullValue();
    }

    return leave();
}
 
Example #8
Source File: AssignSymbols.java    From openjdk-jdk8u-backup with GNU General Public License v2.0 6 votes vote down vote up
@Override
public boolean enterCatchNode(final CatchNode catchNode) {
    final IdentNode exception = catchNode.getException();
    final Block     block     = lc.getCurrentBlock();

    start(catchNode);

    // define block-local exception variable
    final String exname = exception.getName();
    // If the name of the exception starts with ":e", this is a synthetic catch block, likely a catch-all. Its
    // symbol is naturally internal, and should be treated as such.
    final boolean isInternal = exname.startsWith(EXCEPTION_PREFIX.symbolName());
    // IS_LET flag is required to make sure symbol is not visible outside catch block. However, we need to
    // clear the IS_LET flag after creation to allow redefinition of symbol inside the catch block.
    final Symbol symbol = defineSymbol(block, exname, catchNode, IS_VAR | IS_LET | (isInternal ? IS_INTERNAL : 0) | HAS_OBJECT_VALUE);
    symbol.clearFlag(IS_LET);

    return true;
}
 
Example #9
Source File: Parser.java    From nashorn with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Program :
 *      SourceElements?
 *
 * See 14
 *
 * Parse the top level script.
 */
private FunctionNode program(final String scriptName) {
    // Make a fake token for the script.
    final long functionToken = Token.toDesc(FUNCTION, 0, source.getLength());
    // Set up the script to append elements.

    FunctionNode script = newFunctionNode(
        functionToken,
        new IdentNode(functionToken, Token.descPosition(functionToken), scriptName),
        new ArrayList<IdentNode>(),
        FunctionNode.Kind.SCRIPT);

    functionDeclarations = new ArrayList<>();
    sourceElements();
    addFunctionDeclarations(script);
    functionDeclarations = null;

    expect(EOF);

    script.setFinish(source.getLength() - 1);

    script = restoreFunctionNode(script, token); //commit code
    script = script.setBody(lc, script.getBody().setNeedsScope(lc));

    return script;
}
 
Example #10
Source File: Lower.java    From openjdk-jdk8u with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Check whether a call node may be a call to eval. In that case we
 * clone the args in order to create the following construct in
 * {@link CodeGenerator}
 *
 * <pre>
 * if (calledFuntion == buildInEval) {
 *    eval(cloned arg);
 * } else {
 *    cloned arg;
 * }
 * </pre>
 *
 * @param callNode call node to check if it's an eval
 */
private CallNode checkEval(final CallNode callNode) {
    if (callNode.getFunction() instanceof IdentNode) {

        final List<Expression> args = callNode.getArgs();
        final IdentNode callee = (IdentNode)callNode.getFunction();

        // 'eval' call with at least one argument
        if (args.size() >= 1 && EVAL.symbolName().equals(callee.getName())) {
            final List<Expression> evalArgs = new ArrayList<>(args.size());
            for(final Expression arg: args) {
                evalArgs.add((Expression)ensureUniqueNamesIn(arg).accept(this));
            }
            return callNode.setEvalArgs(new CallNode.EvalArgs(evalArgs, evalLocation(callee)));
        }
    }

    return callNode;
}
 
Example #11
Source File: Parser.java    From openjdk-jdk8u-backup with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Parse and return the list of function parameter list. A comma
 * separated list of function parameter identifiers is expected to be parsed.
 * Errors will be thrown and the error manager will contain information
 * if parsing should fail. This method is used to check if parameter Strings
 * passed to "Function" constructor is a valid or not.
 *
 * @return the list of IdentNodes representing the formal parameter list
 */
public List<IdentNode> parseFormalParameterList() {
    try {
        stream = new TokenStream();
        lexer  = new Lexer(source, stream, scripting && !env._no_syntax_extensions);

        // Set up first token (skips opening EOL.)
        k = -1;
        next();

        return formalParameterList(TokenType.EOF);
    } catch (final Exception e) {
        handleParseException(e);
        return null;
    }
}
 
Example #12
Source File: JSONWriter.java    From openjdk-8 with GNU General Public License v2.0 6 votes vote down vote up
@Override
public boolean enterBreakNode(final BreakNode breakNode) {
    enterDefault(breakNode);

    type("BreakStatement");
    comma();

    final IdentNode label = breakNode.getLabel();
    property("label");
    if (label != null) {
        label.accept(this);
    } else {
        nullValue();
    }

    return leave();
}
 
Example #13
Source File: AssignSymbols.java    From jdk8u_nashorn with GNU General Public License v2.0 6 votes vote down vote up
private Node leaveTYPEOF(final UnaryNode unaryNode) {
    final Expression rhs = unaryNode.getExpression();

    final List<Expression> args = new ArrayList<>();
    if (rhs instanceof IdentNode && !isParamOrVar((IdentNode)rhs)) {
        args.add(compilerConstantIdentifier(SCOPE));
        args.add(LiteralNode.newInstance(rhs, ((IdentNode)rhs).getName())); //null
    } else {
        args.add(rhs);
        args.add(LiteralNode.newInstance(unaryNode)); //null, do not reuse token of identifier rhs, it can be e.g. 'this'
    }

    final Node runtimeNode = new RuntimeNode(unaryNode, Request.TYPEOF, args);

    end(unaryNode);

    return runtimeNode;
}
 
Example #14
Source File: AssignSymbols.java    From hottub with GNU General Public License v2.0 6 votes vote down vote up
private Symbol nameIsUsed(final String name, final IdentNode origin) {
    final Block block = lc.getCurrentBlock();

    Symbol symbol = findSymbol(block, name);

    //If an existing symbol with the name is found, use that otherwise, declare a new one
    if (symbol != null) {
        log.info("Existing symbol = ", symbol);
        if (symbol.isFunctionSelf()) {
            final FunctionNode functionNode = lc.getDefiningFunction(symbol);
            assert functionNode != null;
            assert lc.getFunctionBody(functionNode).getExistingSymbol(CALLEE.symbolName()) != null;
            lc.setFlag(functionNode, FunctionNode.USES_SELF_SYMBOL);
        }

        // if symbol is non-local or we're in a with block, we need to put symbol in scope (if it isn't already)
        maybeForceScope(symbol);
    } else {
        log.info("No symbol exists. Declare as global: ", name);
        symbol = defineSymbol(block, name, origin, IS_GLOBAL | IS_SCOPE);
    }

    functionUsesSymbol(symbol);
    return symbol;
}
 
Example #15
Source File: Lower.java    From openjdk-8-source with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Check whether a call node may be a call to eval. In that case we
 * clone the args in order to create the following construct in
 * {@link CodeGenerator}
 *
 * <pre>
 * if (calledFuntion == buildInEval) {
 *    eval(cloned arg);
 * } else {
 *    cloned arg;
 * }
 * </pre>
 *
 * @param callNode call node to check if it's an eval
 */
private CallNode checkEval(final CallNode callNode) {
    if (callNode.getFunction() instanceof IdentNode) {

        final List<Expression> args = callNode.getArgs();
        final IdentNode callee = (IdentNode)callNode.getFunction();

        // 'eval' call with at least one argument
        if (args.size() >= 1 && EVAL.symbolName().equals(callee.getName())) {
            final FunctionNode currentFunction = lc.getCurrentFunction();
            return callNode.setEvalArgs(
                new CallNode.EvalArgs(
                    (Expression)ensureUniqueNamesIn(args.get(0)).accept(this),
                    compilerConstant(THIS),
                    evalLocation(callee),
                    currentFunction.isStrict()));
        }
    }

    return callNode;
}
 
Example #16
Source File: Parser.java    From jdk8u60 with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Make sure that in strict mode, the identifier name used is allowed.
 *
 * @param ident         Identifier that is verified
 * @param contextString String used in error message to give context to the user
 */
private void verifyStrictIdent(final IdentNode ident, final String contextString) {
    if (isStrictMode) {
        switch (ident.getName()) {
        case "eval":
        case "arguments":
            throw error(AbstractParser.message("strict.name", ident.getName(), contextString), ident.getToken());
        default:
            break;
        }

        if (ident.isFutureStrictName()) {
            throw error(AbstractParser.message("strict.name", ident.getName(), contextString), ident.getToken());
        }
    }
}
 
Example #17
Source File: Lower.java    From openjdk-jdk8u-backup with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Given a function node that is a callee in a CallNode, replace it with
 * the appropriate marker function. This is used by {@link CodeGenerator}
 * for fast scope calls
 *
 * @param function function called by a CallNode
 * @return transformed node to marker function or identity if not ident/access/indexnode
 */
private static Expression markerFunction(final Expression function) {
    if (function instanceof IdentNode) {
        return ((IdentNode)function).setIsFunction();
    } else if (function instanceof BaseNode) {
        return ((BaseNode)function).setIsFunction();
    }
    return function;
}
 
Example #18
Source File: Lower.java    From openjdk-jdk9 with GNU General Public License v2.0 5 votes vote down vote up
@Override
public Node leaveVarNode(final VarNode varNode) {
    addStatement(varNode);
    if (varNode.getFlag(VarNode.IS_LAST_FUNCTION_DECLARATION)
            && lc.getCurrentFunction().isProgram()
            && ((FunctionNode) varNode.getInit()).isAnonymous()) {
        new ExpressionStatement(varNode.getLineNumber(), varNode.getToken(), varNode.getFinish(), new IdentNode(varNode.getName())).accept(this);
    }
    return varNode;
}
 
Example #19
Source File: JSONWriter.java    From openjdk-jdk8u with GNU General Public License v2.0 5 votes vote down vote up
@Override
public boolean enterIdentNode(final IdentNode identNode) {
    enterDefault(identNode);

    final String name = identNode.getName();
    if ("this".equals(name)) {
        type("ThisExpression");
    } else {
        type("Identifier");
        comma();
        property("name", identNode.getName());
    }

    return leave();
}
 
Example #20
Source File: AssignSymbols.java    From openjdk-jdk8u 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 (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 IdentNode) {
            final Symbol symbol = ((IdentNode)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: Parser.java    From openjdk-jdk8u with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Execute parse and return the resulting function node.
 * Errors will be thrown and the error manager will contain information
 * if parsing should fail. This method is used to check if code String
 * passed to "Function" constructor is a valid function body or not.
 *
 * @return function node resulting from successful parse
 */
public FunctionNode parseFunctionBody() {
    try {
        stream = new TokenStream();
        lexer  = new Lexer(source, stream, scripting && !env._no_syntax_extensions);
        final int functionLine = line;

        // Set up first token (skips opening EOL.)
        k = -1;
        next();

        // Make a fake token for the function.
        final long functionToken = Token.toDesc(FUNCTION, 0, source.getLength());
        // Set up the function to append elements.

        FunctionNode function = newFunctionNode(
            functionToken,
            new IdentNode(functionToken, Token.descPosition(functionToken), PROGRAM.symbolName()),
            new ArrayList<IdentNode>(),
            FunctionNode.Kind.NORMAL,
            functionLine);

        functionDeclarations = new ArrayList<>();
        sourceElements(false);
        addFunctionDeclarations(function);
        functionDeclarations = null;

        expect(EOF);

        function.setFinish(source.getLength() - 1);
        function = restoreFunctionNode(function, token); //commit code
        function = function.setBody(lc, function.getBody().setNeedsScope(lc));

        printAST(function);
        return function;
    } catch (final Exception e) {
        handleParseException(e);
        return null;
    }
}
 
Example #22
Source File: JSONWriter.java    From openjdk-jdk8u-backup with GNU General Public License v2.0 5 votes vote down vote up
@Override
public boolean enterIdentNode(final IdentNode identNode) {
    enterDefault(identNode);

    final String name = identNode.getName();
    if ("this".equals(name)) {
        type("ThisExpression");
    } else {
        type("Identifier");
        comma();
        property("name", identNode.getName());
    }

    return leave();
}
 
Example #23
Source File: AssignSymbols.java    From openjdk-jdk9 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 (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 IdentNode) {
            final Symbol symbol = ((IdentNode)node).getSymbol();
            if (symbol == null) {
                sb.append(" <NO SYMBOL>");
            } else {
                sb.append(" <symbol=").append(symbol).append('>');
            }
        }

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

    return node;
}
 
Example #24
Source File: Parser.java    From jdk8u_nashorn with GNU General Public License v2.0 5 votes vote down vote up
private PropertyFunction propertyGetterFunction(final long getSetToken, final int functionLine) {
    final PropertyKey getIdent = propertyName();
    final String getterName = getIdent.getPropertyName();
    final IdentNode getNameNode = createIdentNode(((Node)getIdent).getToken(), finish, NameCodec.encode("get " + getterName));
    expect(LPAREN);
    expect(RPAREN);
    final FunctionNode functionNode = functionBody(getSetToken, getNameNode, new ArrayList<IdentNode>(), FunctionNode.Kind.GETTER, functionLine);

    return new PropertyFunction(getIdent, functionNode);
}
 
Example #25
Source File: Parser.java    From jdk8u60 with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Execute parse and return the resulting function node.
 * Errors will be thrown and the error manager will contain information
 * if parsing should fail. This method is used to check if code String
 * passed to "Function" constructor is a valid function body or not.
 *
 * @return function node resulting from successful parse
 */
public FunctionNode parseFunctionBody() {
    try {
        stream = new TokenStream();
        lexer  = new Lexer(source, stream, scripting && !env._no_syntax_extensions);
        final int functionLine = line;

        // Set up first token (skips opening EOL.)
        k = -1;
        next();

        // Make a fake token for the function.
        final long functionToken = Token.toDesc(FUNCTION, 0, source.getLength());
        // Set up the function to append elements.

        FunctionNode function = newFunctionNode(
            functionToken,
            new IdentNode(functionToken, Token.descPosition(functionToken), PROGRAM.symbolName()),
            new ArrayList<IdentNode>(),
            FunctionNode.Kind.NORMAL,
            functionLine);

        functionDeclarations = new ArrayList<>();
        sourceElements(false);
        addFunctionDeclarations(function);
        functionDeclarations = null;

        expect(EOF);

        function.setFinish(source.getLength() - 1);
        function = restoreFunctionNode(function, token); //commit code
        function = function.setBody(lc, function.getBody().setNeedsScope(lc));

        printAST(function);
        return function;
    } catch (final Exception e) {
        handleParseException(e);
        return null;
    }
}
 
Example #26
Source File: ProgramPoints.java    From jdk8u_nashorn with GNU General Public License v2.0 5 votes vote down vote up
@Override
public Node leaveIdentNode(final IdentNode identNode) {
    if(identNode.isPropertyName()) {
        return identNode;
    }
    return setProgramPoint(identNode);
}
 
Example #27
Source File: AssignSymbols.java    From openjdk-jdk9 with GNU General Public License v2.0 5 votes vote down vote up
private void defineVarIdent(final VarNode varNode) {
    final IdentNode ident = varNode.getName();
    final int flags;
    if (!varNode.isBlockScoped() && lc.getCurrentFunction().isProgram()) {
        flags = IS_SCOPE;
    } else {
        flags = 0;
    }
    defineSymbol(lc.getCurrentBlock(), ident.getName(), ident, varNode.getSymbolFlags() | flags);
}
 
Example #28
Source File: MethodEmitter.java    From openjdk-jdk9 with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Load a key value in the proper form.
 *
 * @param key
 */
//TODO move this and break it apart
MethodEmitter loadKey(final Object key) {
    if (key instanceof IdentNode) {
        method.visitLdcInsn(((IdentNode) key).getName());
    } else if (key instanceof LiteralNode) {
        method.visitLdcInsn(((LiteralNode<?>)key).getString());
    } else {
        method.visitLdcInsn(JSType.toString(key));
    }
    pushType(Type.OBJECT); //STRING
    return this;
}
 
Example #29
Source File: AssignSymbols.java    From TencentKona-8 with GNU General Public License v2.0 5 votes vote down vote up
private void defineVarIdent(final VarNode varNode) {
    final IdentNode ident = varNode.getName();
    final int flags;
    if (!varNode.isBlockScoped() && lc.getCurrentFunction().isProgram()) {
        flags = IS_SCOPE;
    } else {
        flags = 0;
    }
    defineSymbol(lc.getCurrentBlock(), ident.getName(), ident, varNode.getSymbolFlags() | flags);
}
 
Example #30
Source File: Parser.java    From nashorn with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Make sure that in strict mode, the identifier name used is allowed.
 *
 * @param ident         Identifier that is verified
 * @param contextString String used in error message to give context to the user
 */
private void verifyStrictIdent(final IdentNode ident, final String contextString) {
    if (isStrictMode) {
        switch (ident.getName()) {
        case "eval":
        case "arguments":
            throw error(AbstractParser.message("strict.name", ident.getName(), contextString), ident.getToken());
        default:
            break;
        }
    }
}