local scope vars indexed by number
[org.ibex.core.git] / src / org / ibex / js / Parser.java
index dce9a24..6293107 100644 (file)
@@ -69,7 +69,7 @@ class Parser extends Lexer implements ByteCodes {
 
     // Constructors //////////////////////////////////////////////////////
 
-    public Parser(Reader r, String sourceName, int line) throws IOException { super(r, sourceName, line); }
+    private Parser(Reader r, String sourceName, int line) throws IOException { super(r, sourceName, line); }
 
     /** for debugging */
     public static void main(String[] s) throws IOException {
@@ -78,7 +78,6 @@ class Parser extends Lexer implements ByteCodes {
         System.out.println(block);
     }
 
-
     // Statics ////////////////////////////////////////////////////////////
 
     static byte[] precedence = new byte[MAX_TOKEN + 1];
@@ -133,8 +132,68 @@ class Parser extends Lexer implements ByteCodes {
         precedence[DOT] = precedence[LB] = precedence[LP] =  precedence[INC] = precedence[DEC] = 15;
     }
 
-
+    // Local variable management
+    Vec scopeStack = new Vec();
+    static class ScopeInfo {
+        int base;
+        int end;
+        int newScopeInsn;
+        Hash mapping = new Hash();
+    }
+    Hash globalCache = new Hash();
+    JS scopeKey(String name) {
+        if(globalCache.get(name) != null) return null;
+        for(int i=scopeStack.size()-1;i>=0;i--) {
+            JS key = (JS)((ScopeInfo) scopeStack.elementAt(i)).mapping.get(name);
+            if(key != null) return key;
+        }
+        globalCache.put(name,Boolean.TRUE);
+        return null;
+    }
+    void scopeDeclare(String name) throws IOException {
+        ScopeInfo si = (ScopeInfo) scopeStack.lastElement();
+        if(si.mapping.get(name) != null) throw pe("" + name + " already declared in this scope");
+        si.mapping.put(name,JS.N(si.end++));
+        globalCache.put(name,null);
+    }
+    void scopePush(JSFunction b) {
+        ScopeInfo prev = (ScopeInfo) scopeStack.lastElement();
+        ScopeInfo si = new ScopeInfo();
+        si.base = prev.end;
+        si.end = si.base;
+        si.newScopeInsn = b.size;
+        scopeStack.push(si);
+        b.add(parserLine, NEWSCOPE);
+    }
+    void scopePop(JSFunction b) {
+        ScopeInfo si = (ScopeInfo) scopeStack.pop();
+        b.add(parserLine, OLDSCOPE);
+        b.set(si.newScopeInsn,JS.N((si.base<<16)|((si.end-si.base)<<0))); 
+    }
+    
+    
     // Parsing Logic /////////////////////////////////////////////////////////
+    
+    /** parse and compile a function */
+    public static JSFunction fromReader(String sourceName, int firstLine, Reader sourceCode) throws IOException {
+        JSFunction ret = new JSFunction(sourceName, firstLine, null);
+        if (sourceCode == null) return ret;
+        Parser p = new Parser(sourceCode, sourceName, firstLine);
+        p.scopeStack.setSize(0);
+        p.scopeStack.push(new ScopeInfo());
+        p.scopePush(ret);
+        while(true) {
+            //int s = ret.size;
+            if(p.peekToken() == -1) break; // FIXME: Check this logic one more time
+            p.parseStatement(ret, null);
+            //if (s == ret.size) break;
+        }
+        p.scopePop(ret);
+        if(p.scopeStack.size() != 1) throw new Error("scopeStack height mismatch");
+        ret.add(-1, LITERAL, null); 
+        ret.add(-1, RETURN);
+        return ret;
+    }
 
     /** gets a token and throws an exception if it is not <tt>code</tt> */
     private void consume(int code) throws IOException {
@@ -177,12 +236,10 @@ class Parser extends Lexer implements ByteCodes {
         // (.foo) syntax
         case DOT: {
             consume(NAME);
-            b.add(parserLine, TOPSCOPE);
-            b.add(parserLine, LITERAL, JSString.intern(""));
-            b.add(parserLine, GET);
-            b.add(parserLine, LITERAL, JSString.intern(string));
-            b.add(parserLine, GET);
-            continueExpr(b, minPrecedence);
+            b.add(parserLine, GLOBALSCOPE);
+            b.add(parserLine, GET, JS.S("",true));
+            b.add(parserLine, LITERAL, JS.S(string,true));
+            continueExprAfterAssignable(b,minPrecedence,null);
             break;
         }
 
@@ -227,18 +284,23 @@ class Parser extends Lexer implements ByteCodes {
         case INC: case DEC: {  // prefix (not postfix)
             startExpr(b, precedence[tok]);
             int prev = b.size - 1;
+            boolean sg = b.get(prev) == SCOPEGET;
             if (b.get(prev) == GET && b.getArg(prev) != null)
                 b.set(prev, LITERAL, b.getArg(prev));
             else if(b.get(prev) == GET)
                 b.pop();
-            else
+            else if(!sg)
                 throw pe("prefixed increment/decrement can only be performed on a valid assignment target");
-            b.add(parserLine, GET_PRESERVE, Boolean.TRUE);
+            if(!sg) b.add(parserLine, GET_PRESERVE, Boolean.TRUE);
             b.add(parserLine, LITERAL, JS.N(1));
             b.add(parserLine, tok == INC ? ADD : SUB, JS.N(2));
-            b.add(parserLine, PUT, null);
-            b.add(parserLine, SWAP, null);
-            b.add(parserLine, POP, null);
+            if(sg) {
+                b.add(parserLine, SCOPEPUT, b.getArg(prev));
+            } else {
+                b.add(parserLine, PUT, null);
+                b.add(parserLine, SWAP, null);
+                b.add(parserLine, POP, null);
+            }
             break;
         }
         case BANG: case BITNOT: case TYPEOF: {
@@ -266,11 +328,25 @@ class Parser extends Lexer implements ByteCodes {
             break;
         }
         case NAME: {
-            b.add(parserLine, TOPSCOPE);
-            b.add(parserLine, LITERAL, JSString.intern(string));
-            continueExprAfterAssignable(b,minPrecedence);
+            JS varKey = scopeKey(string);
+            if(varKey == null) {
+                b.add(parserLine, GLOBALSCOPE);
+                b.add(parserLine, LITERAL, JSString.intern(string));
+            }
+            continueExprAfterAssignable(b,minPrecedence,varKey);
+            break;
+        }
+        case CASCADE: {
+            if(peekToken() == ASSIGN) {
+                consume(ASSIGN);
+                startExpr(b, precedence[ASSIGN]);
+                b.add(parserLine, CASCADE, JS.T);
+            } else {
+                b.add(parserLine, CASCADE, JS.F);
+            }
             break;
         }
+                
         case FUNCTION: {
             consume(LP);
             int numArgs = 0;
@@ -278,27 +354,20 @@ class Parser extends Lexer implements ByteCodes {
             b.add(parserLine, NEWFUNCTION, b2);
 
             // function prelude; arguments array is already on the stack
-            b2.add(parserLine, TOPSCOPE);
-            b2.add(parserLine, SWAP);
-            b2.add(parserLine, DECLARE, JSString.intern("arguments"));    // declare arguments (equivalent to 'var arguments;')
-            b2.add(parserLine, SWAP);                                     // set this.arguments and leave the value on the stack
-            b2.add(parserLine, PUT);
+            scopePush(b2);
+            scopeDeclare("arguments");
+            b2.add(parserLine, SCOPEPUT,scopeKey("arguments"));
 
             while(peekToken() != RP) {                                    // run through the list of argument names
                 numArgs++;
                 if (peekToken() == NAME) {
                     consume(NAME);                                        // a named argument
-                    JS varName = JSString.intern(string);
                     
                     b2.add(parserLine, DUP);                              // dup the args array 
                     b2.add(parserLine, GET, JS.N(numArgs - 1));   // retrieve it from the arguments array
-                    b2.add(parserLine, TOPSCOPE);
-                    b2.add(parserLine, SWAP);
-                    b2.add(parserLine, DECLARE, varName);                  // declare the name
-                    b2.add(parserLine, SWAP);
-                    b2.add(parserLine, PUT); 
-                    b2.add(parserLine, POP);                               // pop the value
-                    b2.add(parserLine, POP);                               // pop the scope                  
+                    scopeDeclare(string);
+                    b2.add(parserLine, SCOPEPUT, scopeKey(string));
+                    b2.add(parserLine, POP);
                 }
                 if (peekToken() == RP) break;
                 consume(COMMA);
@@ -307,13 +376,13 @@ class Parser extends Lexer implements ByteCodes {
 
             b2.numFormalArgs = numArgs;
             b2.add(parserLine, POP);                                      // pop off the arguments array
-            b2.add(parserLine, POP);                                      // pop off TOPSCOPE
             
            if(peekToken() != LC)
                 throw pe("JSFunctions must have a block surrounded by curly brackets");
                 
             parseBlock(b2, null);                                   // the function body
-
+            
+            scopePop(b2);
             b2.add(parserLine, LITERAL, null);                        // in case we "fall out the bottom", return NULL
             b2.add(parserLine, RETURN);
 
@@ -364,12 +433,12 @@ class Parser extends Lexer implements ByteCodes {
      *  expression that modifies the assignable.  This method always
      *  decreases the stack depth by exactly one element.
      */
-    private void continueExprAfterAssignable(JSFunction b,int minPrecedence) throws IOException {
+    private void continueExprAfterAssignable(JSFunction b,int minPrecedence, JS varKey) throws IOException {
         int saveParserLine = parserLine;
-        _continueExprAfterAssignable(b,minPrecedence);
+        _continueExprAfterAssignable(b,minPrecedence,varKey);
         parserLine = saveParserLine;
     }
-    private void _continueExprAfterAssignable(JSFunction b,int minPrecedence) throws IOException {
+    private void _continueExprAfterAssignable(JSFunction b,int minPrecedence, JS varKey) throws IOException {
         if (b == null) throw new Error("got null b; this should never happen");
         int tok = getToken();
         if (minPrecedence != -1 && (precedence[tok] < minPrecedence || (precedence[tok] == minPrecedence && !isRightAssociative[tok])))
@@ -393,52 +462,71 @@ class Parser extends Lexer implements ByteCodes {
             */
         case ASSIGN_BITOR: case ASSIGN_BITXOR: case ASSIGN_BITAND: case ASSIGN_LSH: case ASSIGN_RSH: case ASSIGN_URSH:
         case ASSIGN_MUL: case ASSIGN_DIV: case ASSIGN_MOD: case ASSIGN_ADD: case ASSIGN_SUB: case ADD_TRAP: case DEL_TRAP: {
-            if (tok != ADD_TRAP && tok != DEL_TRAP) b.add(parserLine, GET_PRESERVE);
+            if (tok != ADD_TRAP && tok != DEL_TRAP) 
+                b.add(parserLine, varKey == null ? GET_PRESERVE : SCOPEGET, varKey);
             
             startExpr(b,  precedence[tok]);
             
             if (tok != ADD_TRAP && tok != DEL_TRAP) {
                 // tok-1 is always s/^ASSIGN_// (0 is BITOR, 1 is ASSIGN_BITOR, etc) 
                 b.add(parserLine, tok - 1, tok-1==ADD ? JS.N(2) : null);
-                b.add(parserLine, PUT);
-                b.add(parserLine, SWAP);
-                b.add(parserLine, POP);
+                if(varKey == null) {
+                    b.add(parserLine, PUT);
+                    b.add(parserLine, SWAP);
+                    b.add(parserLine, POP);
+                } else {
+                    b.add(parserLine, SCOPEPUT, varKey);
+                }
             } else {
+                if(varKey != null) throw pe("cannot place traps on local variables");
                 b.add(parserLine, tok);
             }
             break;
         }
         case INC: case DEC: { // postfix
-            b.add(parserLine, GET_PRESERVE, Boolean.TRUE);
-            b.add(parserLine, LITERAL, JS.N(1));
-            b.add(parserLine, tok == INC ? ADD : SUB, JS.N(2));
-            b.add(parserLine, PUT, null);
-            b.add(parserLine, SWAP, null);
-            b.add(parserLine, POP, null);
-            b.add(parserLine, LITERAL, JS.N(1));
-            b.add(parserLine, tok == INC ? SUB : ADD, JS.N(2));   // undo what we just did, since this is postfix
+            if(varKey == null) {
+                b.add(parserLine, GET_PRESERVE, Boolean.TRUE);
+                b.add(parserLine, LITERAL, JS.N(1));
+                b.add(parserLine, tok == INC ? ADD : SUB, JS.N(2));
+                b.add(parserLine, PUT, null);
+                b.add(parserLine, SWAP, null);
+                b.add(parserLine, POP, null);
+                b.add(parserLine, LITERAL, JS.N(1));
+                b.add(parserLine, tok == INC ? SUB : ADD, JS.N(2));   // undo what we just did, since this is postfix
+            } else {
+                b.add(parserLine, SCOPEGET, varKey);
+                b.add(parserLine, DUP);
+                b.add(parserLine, LITERAL, JS.ONE);
+                b.add(parserLine, tok == INC ? ADD : SUB, JS.N(2));
+                b.add(parserLine, SCOPEPUT, varKey);
+            }
             break;
         }
         case ASSIGN: {
             startExpr(b, precedence[tok]);
-            b.add(parserLine, PUT);
-            b.add(parserLine, SWAP);
-            b.add(parserLine, POP);
+            if(varKey == null) {
+                b.add(parserLine, PUT);
+                b.add(parserLine, SWAP);
+                b.add(parserLine, POP);
+            } else {
+                b.add(parserLine, SCOPEPUT, varKey);
+            }
             break;
         }
         case LP: {
-
             // Method calls are implemented by doing a GET_PRESERVE
             // first.  If the object supports method calls, it will
             // return JS.METHOD
-            b.add(parserLine, GET_PRESERVE);
+            b.add(parserLine, varKey == null ? GET_PRESERVE : SCOPEGET, varKey);
             int n = parseArgs(b);
-            b.add(parserLine, CALLMETHOD, JS.N(n));
+            b.add(parserLine, varKey == null ? CALLMETHOD : CALL, JS.N(n));
             break;
         }
         default: {
             pushBackToken();
-            if(b.get(b.size-1) == LITERAL && b.getArg(b.size-1) != null)
+            if(varKey != null)
+                b.add(parserLine, SCOPEGET, varKey);
+            else if(b.get(b.size-1) == LITERAL && b.getArg(b.size-1) != null)
                 b.set(b.size-1,GET,b.getArg(b.size-1));
             else
                 b.add(parserLine, GET);
@@ -516,13 +604,13 @@ class Parser extends Lexer implements ByteCodes {
                 consume(NAME);
             }
             b.add(parserLine, LITERAL, JSString.intern(string));
-            continueExprAfterAssignable(b,minPrecedence);
+            continueExprAfterAssignable(b,minPrecedence,null);
             break;
         }
         case LB: { // subscripting (not array constructor)
             startExpr(b, -1);
             consume(RB);
-            continueExprAfterAssignable(b,minPrecedence);
+            continueExprAfterAssignable(b,minPrecedence,null);
             break;
         }
         case HOOK: {
@@ -611,22 +699,19 @@ class Parser extends Lexer implements ByteCodes {
             break;
         }
         case VAR: {
-            b.add(parserLine, TOPSCOPE);                         // push the current scope
             while(true) {
                 consume(NAME);
-                b.add(parserLine, DECLARE, JSString.intern(string)); // declare it
+                String var = string;
+                scopeDeclare(var);
                 if (peekToken() == ASSIGN) {                     // if there is an '=' after the variable name
                     consume(ASSIGN);
                     startExpr(b, NO_COMMA);
-                    b.add(parserLine, PUT);                      // assign it
+                    b.add(parserLine, SCOPEPUT, scopeKey(var)); // assign it
                     b.add(parserLine, POP);                      // clean the stack
-                } else {
-                    b.add(parserLine, POP);                      // pop the string pushed by declare
-                }   
+                }
                 if (peekToken() != COMMA) break;
                 consume(COMMA);
             }
-            b.add(parserLine, POP);                              // pop off the topscope
             if ((mostRecentlyReadToken != RC || peekToken() == SEMI) && peekToken() != -1 && mostRecentlyReadToken != SEMI) consume(SEMI);
             break;
         }
@@ -780,17 +865,12 @@ class Parser extends Lexer implements ByteCodes {
                     }
                     consume(RP);
                     // the exception is on top of the stack; put it to the chosen name
-                    b.add(parserLine, NEWSCOPE);
-                    b.add(parserLine, TOPSCOPE);
-                    b.add(parserLine, SWAP);
-                    b.add(parserLine, LITERAL,JSString.intern(exceptionVar));
-                    b.add(parserLine, DECLARE);
-                    b.add(parserLine, SWAP);
-                    b.add(parserLine, PUT);
-                    b.add(parserLine, POP);
+                    scopePush(b);
+                    scopeDeclare(exceptionVar);
+                    b.add(parserLine, SCOPEPUT, scopeKey(exceptionVar));
                     b.add(parserLine, POP);
                     parseBlock(b, null);
-                    b.add(parserLine, OLDSCOPE);
+                    scopePop(b);
                     
                     b.add(parserLine, JMP);
                     catchEnds.addElement(new Integer(b.size-1));
@@ -863,20 +943,27 @@ class Parser extends Lexer implements ByteCodes {
                 b.add(parserLine,DUP);
                 b.add(parserLine,GET,JS.S("nextElement"));
 
-                b.add(parserLine, NEWSCOPE);
+                scopePush(b);
                 
-                b.add(parserLine,TOPSCOPE);
-                b.add(parserLine,SWAP);
-                b.add(parserLine, hadVar ? DECLARE : LITERAL, JSString.intern(varName));
-                b.add(parserLine,SWAP);
-                b.add(parserLine,PUT);
-                b.add(parserLine,POP);
-                b.add(parserLine,POP);
-                b.add(parserLine,SWAP);
+                if(hadVar) scopeDeclare(varName);
+                JS varKey = scopeKey(varName);
+                
+                if(varKey == null) {
+                    b.add(parserLine,GLOBALSCOPE);
+                    b.add(parserLine,SWAP);
+                    b.add(parserLine, LITERAL, JSString.intern(varName));
+                    b.add(parserLine,SWAP);
+                    b.add(parserLine,PUT);
+                    b.add(parserLine,POP);
+                } else {
+                    b.add(parserLine, SCOPEPUT, varKey);
+                }
+                b.add(parserLine,POP);  // pop the put'ed value
+                b.add(parserLine,SWAP); // put CallMarker back into place
                 
                 parseStatement(b, null);
                 
-                b.add(parserLine, OLDSCOPE);
+                scopePop(b);
                 b.add(parserLine, CONTINUE);
                 // jump here on break
                 b.set(size, JS.N(b.size - size));
@@ -884,7 +971,7 @@ class Parser extends Lexer implements ByteCodes {
                 b.add(parserLine, POP);
             } else {
                 if (hadVar) pushBackToken(VAR, null);                    // yeah, this actually matters
-                b.add(parserLine, NEWSCOPE);                             // grab a fresh scope
+                scopePush(b);                             // grab a fresh scope
                     
                 parseStatement(b, null);                                 // initializer
                 JSFunction e2 =                                    // we need to put the incrementor before the test
@@ -914,7 +1001,7 @@ class Parser extends Lexer implements ByteCodes {
                 b.add(parserLine, CONTINUE);                             // if we fall out the bottom, CONTINUE
                 b.set(size2 - 1, JS.N(b.size - size2 + 1));     // end of the loop
                     
-                b.add(parserLine, OLDSCOPE);                             // get our scope back
+                scopePop(b);                            // get our scope back
             }
             break;
         }
@@ -938,9 +1025,9 @@ class Parser extends Lexer implements ByteCodes {
 
         case LC: {  // blocks are statements too
             pushBackToken();
-            b.add(parserLine, NEWSCOPE);
+            scopePush(b);
             parseBlock(b, label);
-            b.add(parserLine, OLDSCOPE);
+            scopePop(b);
             break;
         }