Search in sources :

Example 6 with AstRoot

use of org.mozilla.javascript.ast.AstRoot in project HL4A by HL4A.

the class ClassCompiler method compileToClassFiles.

/**
 * Compile JavaScript source into one or more Java class files.
 * The first compiled class will have name mainClassName.
 * If the results of {@link #getTargetExtends()} or
 * {@link #getTargetImplements()} are not null, then the first compiled
 * class will extend the specified super class and implement
 * specified interfaces.
 *
 * @return array where elements with even indexes specifies class name
 *         and the following odd index gives class file body as byte[]
 *         array. The initial element of the array always holds
 *         mainClassName and array[1] holds its byte code.
 */
public Object[] compileToClassFiles(String source, String sourceLocation, int lineno, String mainClassName) {
    Parser p = new Parser(compilerEnv);
    AstRoot ast = p.parse(source, sourceLocation, lineno);
    IRFactory irf = new IRFactory(compilerEnv);
    ScriptNode tree = irf.transformTree(ast);
    // release reference to original parse tree & parser
    irf = null;
    ast = null;
    p = null;
    Class<?> superClass = getTargetExtends();
    Class<?>[] interfaces = getTargetImplements();
    String scriptClassName;
    boolean isPrimary = (interfaces == null && superClass == null);
    if (isPrimary) {
        scriptClassName = mainClassName;
    } else {
        scriptClassName = makeAuxiliaryClassName(mainClassName, "1");
    }
    Codegen codegen = new Codegen();
    codegen.setMainMethodClass(mainMethodClassName);
    byte[] scriptClassBytes = codegen.compileToClassFile(compilerEnv, scriptClassName, tree, tree.getEncodedSource(), false);
    if (isPrimary) {
        return new Object[] { scriptClassName, scriptClassBytes };
    }
    int functionCount = tree.getFunctionCount();
    ObjToIntMap functionNames = new ObjToIntMap(functionCount);
    for (int i = 0; i != functionCount; ++i) {
        FunctionNode ofn = tree.getFunctionNode(i);
        String name = ofn.getName();
        if (name != null && name.length() != 0) {
            functionNames.put(name, ofn.getParamCount());
        }
    }
    if (superClass == null) {
        superClass = ScriptRuntime.ObjectClass;
    }
    byte[] mainClassBytes = JavaAdapter.createAdapterCode(functionNames, mainClassName, superClass, interfaces, scriptClassName);
    return new Object[] { mainClassName, mainClassBytes, scriptClassName, scriptClassBytes };
}
Also used : FunctionNode(org.mozilla.javascript.ast.FunctionNode) ScriptNode(org.mozilla.javascript.ast.ScriptNode) AstRoot(org.mozilla.javascript.ast.AstRoot)

Example 7 with AstRoot

use of org.mozilla.javascript.ast.AstRoot in project HL4A by HL4A.

the class Context method compileImpl.

private Object compileImpl(Scriptable scope, Reader sourceReader, String sourceString, String sourceName, int lineno, Object securityDomain, boolean returnFunction, Evaluator compiler, ErrorReporter compilationErrorReporter) throws IOException {
    if (sourceName == null) {
        sourceName = "未命名 代码";
    }
    if (securityDomain != null && getSecurityController() == null) {
        throw new IllegalArgumentException("securityDomain should be null if setSecurityController() was never called");
    }
    // One of sourceReader or sourceString has to be null
    if (!(sourceReader == null ^ sourceString == null))
        Kit.codeBug();
    // scope should be given if and only if compiling function
    if (!(scope == null ^ returnFunction))
        Kit.codeBug();
    CompilerEnvirons compilerEnv = new CompilerEnvirons();
    compilerEnv.initFromContext(this);
    if (compilationErrorReporter == null) {
        compilationErrorReporter = compilerEnv.getErrorReporter();
    }
    if (debugger != null) {
        if (sourceReader != null) {
            sourceString = Kit.readReader(sourceReader);
            sourceReader = null;
        }
    }
    Parser p = new Parser(compilerEnv, compilationErrorReporter);
    if (returnFunction) {
        p.calledByCompileFunction = true;
    }
    if (isStrictMode()) {
        p.setDefaultUseStrictDirective(true);
    }
    AstRoot ast;
    if (sourceString != null) {
        ast = p.parse(sourceString, sourceName, lineno);
    } else {
        ast = p.parse(sourceReader, sourceName, lineno);
    }
    if (returnFunction) {
        // parser no longer adds function to script node
        if (!(ast.getFirstChild() != null && ast.getFirstChild().getType() == Token.FUNCTION)) {
            // with sources like function() {};;;
            throw new IllegalArgumentException("compileFunction only accepts source with single JS function: " + sourceString);
        }
    }
    IRFactory irf = new IRFactory(compilerEnv, compilationErrorReporter);
    ScriptNode tree = irf.transformTree(ast);
    // discard everything but the IR tree
    p = null;
    ast = null;
    irf = null;
    if (compiler == null) {
        compiler = createCompiler();
    }
    Object bytecode = compiler.compile(compilerEnv, tree, tree.getEncodedSource(), returnFunction);
    if (debugger != null) {
        if (sourceString == null)
            Kit.codeBug();
        if (bytecode instanceof DebuggableScript) {
            DebuggableScript dscript = (DebuggableScript) bytecode;
            notifyDebugger_r(this, dscript, sourceString);
        } else {
            throw new RuntimeException("NOT SUPPORTED");
        }
    }
    Object result;
    if (returnFunction) {
        result = compiler.createFunctionObject(this, scope, bytecode, securityDomain);
    } else {
        result = compiler.createScriptObject(bytecode, securityDomain);
    }
    return result;
}
Also used : DebuggableScript(org.mozilla.javascript.debug.DebuggableScript) ScriptNode(org.mozilla.javascript.ast.ScriptNode) AstRoot(org.mozilla.javascript.ast.AstRoot)

Example 8 with AstRoot

use of org.mozilla.javascript.ast.AstRoot in project pmd by pmd.

the class EcmascriptParser method parseEcmascript.

protected AstRoot parseEcmascript(final String sourceCode, final List<ParseProblem> parseProblems) throws ParseException {
    final CompilerEnvirons compilerEnvirons = new CompilerEnvirons();
    compilerEnvirons.setRecordingComments(parserOptions.isRecordingComments());
    compilerEnvirons.setRecordingLocalJsDocComments(parserOptions.isRecordingLocalJsDocComments());
    compilerEnvirons.setLanguageVersion(parserOptions.getRhinoLanguageVersion().getVersion());
    // Scope's don't appear to get set right without this
    compilerEnvirons.setIdeMode(true);
    compilerEnvirons.setWarnTrailingComma(true);
    // see bug #1150 "EmptyExpression" for valid statements!
    compilerEnvirons.setReservedKeywordAsIdentifier(true);
    // TODO We should do something with Rhino errors...
    final ErrorCollector errorCollector = new ErrorCollector();
    final Parser parser = new Parser(compilerEnvirons, errorCollector);
    // TODO Fix hardcode
    final String sourceURI = "unknown";
    final int beginLineno = 1;
    AstRoot astRoot = parser.parse(sourceCode, sourceURI, beginLineno);
    parseProblems.addAll(errorCollector.getErrors());
    return astRoot;
}
Also used : CompilerEnvirons(org.mozilla.javascript.CompilerEnvirons) ErrorCollector(org.mozilla.javascript.ast.ErrorCollector) Parser(org.mozilla.javascript.Parser) AstRoot(org.mozilla.javascript.ast.AstRoot)

Example 9 with AstRoot

use of org.mozilla.javascript.ast.AstRoot in project HL4A by HL4A.

the class Parser method parse.

private AstRoot parse() throws IOException {
    int pos = 0;
    AstRoot root = new AstRoot(pos);
    currentScope = currentScriptOrFn = root;
    // line number where source starts
    int baseLineno = ts.lineno;
    // in case source is empty
    int end = pos;
    boolean inDirectivePrologue = true;
    boolean savedStrictMode = inUseStrictDirective;
    inUseStrictDirective = defaultUseStrictDirective;
    if (inUseStrictDirective) {
        root.setInStrictMode(true);
    }
    try {
        for (; ; ) {
            int tt = peekToken();
            if (tt <= Token.EOF) {
                break;
            }
            AstNode n;
            if (tt == Token.FUNCTION) {
                consumeToken();
                try {
                    n = function(calledByCompileFunction ? FunctionNode.FUNCTION_EXPRESSION : FunctionNode.FUNCTION_STATEMENT);
                } catch (ParserException e) {
                    break;
                }
            } else {
                n = statement();
                if (inDirectivePrologue) {
                    String directive = getDirective(n);
                    if (directive == null) {
                        inDirectivePrologue = false;
                    } else if (directive.equals("严格模式")) {
                        inUseStrictDirective = true;
                        root.setInStrictMode(true);
                    }
                }
            }
            end = getNodeEnd(n);
            root.addChildToBack(n);
            n.setParent(root);
        }
    } catch (StackOverflowError ex) {
        String msg = lookupMessage("msg.too.deep.parser.recursion");
        if (!compilerEnv.isIdeMode())
            throw Context.reportRuntimeError(msg, sourceURI, ts.lineno, null, 0);
    } finally {
        inUseStrictDirective = savedStrictMode;
    }
    if (this.syntaxErrorCount != 0) {
        String msg = String.valueOf(this.syntaxErrorCount);
        msg = lookupMessage("msg.got.syntax.errors", msg);
        if (!compilerEnv.isIdeMode())
            throw errorReporter.runtimeError(msg, sourceURI, baseLineno, null, 0);
    }
    // add comments to root in lexical order
    if (scannedComments != null) {
        // If we find a comment beyond end of our last statement or
        // function, extend the root bounds to the end of that comment.
        int last = scannedComments.size() - 1;
        end = Math.max(end, getNodeEnd(scannedComments.get(last)));
        for (Comment c : scannedComments) {
            root.addComment(c);
        }
    }
    root.setLength(end - pos);
    root.setSourceName(sourceURI);
    root.setBaseLineno(baseLineno);
    root.setEndLineno(ts.lineno);
    return root;
}
Also used : Comment(org.mozilla.javascript.ast.Comment) XmlString(org.mozilla.javascript.ast.XmlString) AstNode(org.mozilla.javascript.ast.AstNode) AstRoot(org.mozilla.javascript.ast.AstRoot)

Aggregations

AstRoot (org.mozilla.javascript.ast.AstRoot)9 ScriptNode (org.mozilla.javascript.ast.ScriptNode)4 ArrayList (java.util.ArrayList)2 Node (net.sourceforge.pmd.lang.ast.Node)2 Test (org.junit.Test)2 Comment (org.mozilla.javascript.ast.Comment)2 FunctionNode (org.mozilla.javascript.ast.FunctionNode)2 DebuggableScript (org.mozilla.javascript.debug.DebuggableScript)2 IOException (java.io.IOException)1 ParseException (net.sourceforge.pmd.lang.ast.ParseException)1 CompilerEnvirons (org.mozilla.javascript.CompilerEnvirons)1 Parser (org.mozilla.javascript.Parser)1 AstNode (org.mozilla.javascript.ast.AstNode)1 ErrorCollector (org.mozilla.javascript.ast.ErrorCollector)1 ParseProblem (org.mozilla.javascript.ast.ParseProblem)1 XmlString (org.mozilla.javascript.ast.XmlString)1