Package org.mozilla.javascript.ast

Examples of org.mozilla.javascript.ast.AstRoot


                }
            }
        }
       
        // first time parsing - compute scopes and variable declarations
        AstRoot root = createParser().parse(_document.get(_region.getOffset(), _region.getLength()), null, 0);

        root.visit(new NodeVisitor() {

            public boolean visit(AstNode node) {
               
                Scope scope = node.getEnclosingScope();
                List<Integer> scopePath = new ArrayList<Integer>();
                while (scope != null) {
                    scopePath.add(scope.getAbsolutePosition());
                    scope = scope.getParentScope();
                }

                Collections.reverse(scopePath);
                String path = WGUtils.serializeCollection(scopePath, ".");
               
                TMLScriptScope tmlScriptScope = _scopes.get(path);
                if (tmlScriptScope == null && node.getEnclosingScope() != null) {                   
                    tmlScriptScope = new TMLScriptScope(path, node.getEnclosingScope().getAbsolutePosition(), node.getEnclosingScope().getLength());                       
                    _scopes.put(path, tmlScriptScope);
                }
               
                if (node instanceof VariableDeclaration || node instanceof ExpressionStatement) {

                   
                    if (node instanceof VariableDeclaration) {
                        VariableDeclaration declaration = (VariableDeclaration) node;
                        String source = declaration.toSource();
                        String name = source.substring(0, source.indexOf("=")).trim();
                        name = name.substring(name.indexOf("var") + 3).trim();
                        String value = source.substring(source.indexOf("=") + 1).trim();
                       
                        TMLScriptVariableDeclaration tmlScriptVarDec = new TMLScriptVariableDeclaration(tmlScriptScope, name);
                        tmlScriptVarDec.setValue(value);
                        tmlScriptVarDec.setOffset(declaration.getAbsolutePosition());
                       
                        tmlScriptScope.getVariableDeclarations().add(tmlScriptVarDec);
                    } else if (node instanceof ExpressionStatement) {
                        ExpressionStatement expressionStatement = (ExpressionStatement) node;
                        String source = expressionStatement.getExpression().toSource();
                        if (source != null && source.contains("=")) {
                            String name = source.substring(0, source.indexOf("=")).trim();
                            String value = source.substring(source.indexOf("=") + 1).trim();
                           
                            TMLScriptVariableDeclaration tmlScriptVarDec = new TMLScriptVariableDeclaration(tmlScriptScope, name);
                            tmlScriptVarDec.setValue(value);
                            tmlScriptVarDec.setOffset(expressionStatement.getAbsolutePosition());
                            tmlScriptVarDec.setTmlVariable(true);
                           
                            tmlScriptScope.getVariableDeclarations().add(tmlScriptVarDec);
                        }
                    }
                   
                }               
                return true;
            }
        });
       
        // second parsing run - compute type of variables
        Iterator<TMLScriptScope> scopes = _scopes.values().iterator();
        while (scopes.hasNext()) {
            TMLScriptScope scope = scopes.next();
            Iterator<TMLScriptVariableDeclaration> vars = scope.getVariableDeclarations().iterator();
            while (vars.hasNext()) {
                final TMLScriptVariableDeclaration fVar = vars.next();
                Map<String,TMLScriptVariableDeclaration> visibleVars = retrieveVisibleVars(fVar);               
               
               
                String currentEnvironmentObject = ReflectionManager.GLOBAL_SCOPE_CLASSNAME;
               
                String[] varValues = splitVariableValue(fVar.getValue(), false);
                if (fVar.getValue().startsWith("Packages") || (fVar.getValue().startsWith("new") && fVar.getValue().contains("Packages"))) {
                    fVar.setType(resolvePackageOrConstructorCall(fVar.getValue(), false));
                } else {                                       
                    for (String value : varValues) {
                        AstRoot valueAst = createParser().parse(value, "", 0);
                        TypeVisitor visitor = new TypeVisitor(currentEnvironmentObject, visibleVars, _versionCompliance, _envFlags);
                        valueAst.visit(visitor);
                       
                        currentEnvironmentObject = visitor.getType();
                       
                        if (currentEnvironmentObject == null)  {
                            break;
                        }
                    }
                    //fVar.setType(ReflectionManager.jsWrap(currentEnvironmentObject));
                    fVar.setType(currentEnvironmentObject);
                }
            }
        }

        // compute user input
        IRegion lineRegion = _document.getLineInformationOfOffset(_cursorInDocument);
       
        if (lineRegion.getOffset() < _region.getOffset()) {
            // stay in parsion region
            lineRegion = _region;
        }
       
        // read backwards until open bracket / line start or control character
        int numClosedBrackets = 0;
        int pos =_cursorInDocument -1;
        while (pos >= lineRegion.getOffset()) {
            char c = _document.getChar(pos);
            if (c == ')') {
                numClosedBrackets++;
            }
            if (c =='(') {
                if (numClosedBrackets == 0) {
                    break;
                } else {
                    numClosedBrackets--;
                }
            }
            if (c == '=' || c==';' || c=='>' || c=='<' || c == '|') {
                break;
            }
            if (c == ',' && numClosedBrackets == 0) {
                break;
            }
            pos--;
        }       
        _typed = _document.get(pos + 1, _cursorInDocument - pos - 1).trim();

        // compute object in context
        _env = ReflectionManager.GLOBAL_SCOPE_CLASSNAME;       
        if (_typed != null) {
            String[] tokens = splitVariableValue(_typed, true);  
            if (_typed.startsWith("Packages") || (_typed.startsWith("new") && _typed.contains("Packages"))) {                           
                _env = resolvePackageOrConstructorCall(_typed, true);
            } else {
                for (int i = 0; i < tokens.length; i++) {
                    String value = tokens[i];
                    if (!value.equals(".") && (i < tokens.length - 1)) {
                        AstRoot valueAst = createParser().parse(value, "", 0);
                        TypeVisitor visitor = new TypeVisitor(_env, retrieveVisibleVars(), _versionCompliance, _envFlags);
                        valueAst.visit(visitor);
                        _env = visitor.getType();
//                        if ((i == tokens.length - 3) || (i == tokens.length - 2)) {
//                            // last token - check if we have to wrap
//                            if (!visitor.skipJSWrapping()) {
//                                _env = ReflectionManager.jsWrap(_env);
View Full Code Here


                }
                String currentEnvironmentObject = "$N$" + type;
                for (int i = tokenIndex; i < length; i++) {
                    if (!tokens[i].equals(".")) {
                        // further tokens to parse for method calls
                        AstRoot valueAst = createParser().parse(tokens[i], "", 0);
                        TypeVisitor visitor = new TypeVisitor(currentEnvironmentObject, new HashMap<String, TMLScriptVariableDeclaration>(), _versionCompliance, _envFlags);
                        valueAst.visit(visitor);
   
                        currentEnvironmentObject = visitor.getType();
   
                        if (currentEnvironmentObject == null) {
                            break;
View Full Code Here

                            for (AstNode paramNode : call.getArguments()) {
                               
                                String currentEnvironmentObject = ReflectionManager.GLOBAL_SCOPE_CLASSNAME;
                                String[] values = splitVariableValue(paramNode.toSource(), false);
                                for (String value : values) {
                                    AstRoot valueAst = createParser().parse(value, "", 0);
                                    TypeVisitor visitor = new TypeVisitor(currentEnvironmentObject, _visibleVars, _versionCompliance, _envFlags);
                                    valueAst.visit(visitor);
                                      
                                    currentEnvironmentObject = visitor.getType();
                                       
                                    if (currentEnvironmentObject == null)  {
                                        break;
View Full Code Here

public class JavascriptParsingTest extends TestCase {

  public void testThatParsingIsPossible() throws Exception {
    String js = "function a() {};";
    Parser parser = new Parser();
    AstRoot ast = parser.parse(js, "source.js", 1);
    assertEquals("a", ((FunctionNode)ast.getFirstChild()).getFunctionName().getIdentifier());
  }
View Full Code Here

  public void testParseComplexStuff() throws Exception {
    Reader source = new InputStreamReader(
        this.getClass().getResourceAsStream("browser_debug.js"));
    Parser parser = new Parser();
    AstRoot ast = parser.parse(source, "browser_debug.js", 1);
    String debugString = ast.debugPrint();
    assertTrue(debugString.contains("getRequiresAndProvides"));
    assertTrue(debugString.contains("ARRAYLIT"));
  }
View Full Code Here

        Parser p = new Parser(compilerEnv, compilationErrorReporter);
        if (returnFunction) {
            p.calledByCompileFunction = 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))
            {
                // XXX: the check just looks for the first child
                // and allows for more nodes after it for compatibility
                // with sources like function() {};;;
                throw new IllegalArgumentException(
View Full Code Here

                                        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;
View Full Code Here

        assertThat((Double) coverageData.get("evalFalse", coverageData), equalTo(1d));
        assertThat((Boolean) coveredFn.call(context, scope, coverageData, new Object[0]), equalTo(true));
    }

    private Object runScript(String script) {
        AstRoot astRoot = parser.parse(script, null, 1);
        branchInstrumentor.setAstRoot(astRoot);
        astRoot.visitAll(branchInstrumentor);
        branchInstrumentor.postProcess();

        context = Context.enter();
        scope = context.initStandardObjects();
        String source = branchObjectHeader + header + branchInstrumentor.getJsLineInitialization() + astRoot.toSource();
        //System.out.println("--------------------------------------");
        //System.out.println("source = " + source);

        return context.evaluateString(scope, source, "test.js", 1, null);
    }
View Full Code Here

    protected String instrumentSource(String source) {
        return instrumentSource(uri, source);
    }

    protected String instrumentSource(String sourceURI, String source) {
        AstRoot astRoot = parser.parse(source , sourceURI, 1);
        astRoot.visitAll(instrumenter);
        if (includeBranchCoverage) {
            branchInstrumentor.setAstRoot(astRoot);
            astRoot.visitAll(branchInstrumentor);
            branchInstrumentor.postProcess();
        }
        return astRoot.toSource();
    }
View Full Code Here

    env.setErrorReporter(errorReporter);

    Parser parser = new Parser(env, errorReporter);
    Reader reader = new BufferedReader(new FileReader(source));
    try {
      AstRoot root = parser.parse(reader, source.getAbsolutePath(), 0);
      DependencyAccumulator visitor = new DependencyAccumulator(source);
      root.visit(visitor);

      // complain if no def was found in this source
      if (visitor.current == null) {
        log.warn("No class definition was found while processing: " + source);
      }
View Full Code Here

TOP

Related Classes of org.mozilla.javascript.ast.AstRoot

Copyright © 2018 www.massapicom. All rights reserved.
All source code are property of their respective owners. Java is a trademark of Sun Microsystems, Inc and owned by ORACLE Inc. Contact coftware#gmail.com.