local scope vars indexed by number
[org.ibex.core.git] / src / org / ibex / js / Parser.java
1 // Copyright 2004 Adam Megacz, see the COPYING file for licensing [GPL]
2 package org.ibex.js;
3
4 import org.ibex.util.*;
5 import java.io.*;
6
7 /**
8  *  Parses a stream of lexed tokens into a tree of JSFunction's.
9  *
10  *  There are three kinds of things we parse: blocks, statements, and
11  *  expressions.
12  *
13  *  - Expressions are a special type of statement that evaluates to a
14  *    value (for example, "break" is not an expression, * but "3+2"
15  *    is).  Some tokens sequences start expressions (for * example,
16  *    literal numbers) and others continue an expression which * has
17  *    already been begun (for example, '+').  Finally, some *
18  *    expressions are valid targets for an assignment operation; after
19  *    * each of these expressions, continueExprAfterAssignable() is
20  *    called * to check for an assignment operation.
21  *
22  *  - A statement ends with a semicolon and does not return a value.
23  *
24  *  - A block is a single statement or a sequence of statements
25  *    surrounded by curly braces.
26  *
27  *  Each parsing method saves the parserLine before doing its actual
28  *  work and restores it afterwards.  This ensures that parsing a
29  *  subexpression does not modify the line number until a token
30  *  *after* the subexpression has been consumed by the parent
31  *  expression.
32  *
33  *  Technically it would be a better design for this class to build an
34  *  intermediate parse tree and use that to emit bytecode.  Here's the
35  *  tradeoff:
36  *
37  *  Advantages of building a parse tree:
38  *  - easier to apply optimizations
39  *  - would let us handle more sophisticated languages than JavaScript
40  *
41  *  Advantages of leaving out the parse tree
42  *  - faster compilation
43  *  - less load on the garbage collector
44  *  - much simpler code, easier to understand
45  *  - less error-prone
46  *
47  *  Fortunately JS is such a simple language that we can get away with
48  *  the half-assed approach and still produce a working, complete
49  *  compiler.
50  *
51  *  The bytecode language emitted doesn't really cause any appreciable
52  *  semantic loss, and is itself a parseable language very similar to
53  *  Forth or a postfix variant of LISP.  This means that the bytecode
54  *  can be transformed into a parse tree, which can be manipulated.
55  *  So if we ever want to add an optimizer, it could easily be done by
56  *  producing a parse tree from the bytecode, optimizing that tree,
57  *  and then re-emitting the bytecode.  The parse tree node class
58  *  would also be much simpler since the bytecode language has so few
59  *  operators.
60  *
61  *  Actually, the above paragraph is slightly inaccurate -- there are
62  *  places where we push a value and then perform an arbitrary number
63  *  of operations using it before popping it; this doesn't parse well.
64  *  But these cases are clearly marked and easy to change if we do
65  *  need to move to a parse tree format.
66  */
67 class Parser extends Lexer implements ByteCodes {
68
69
70     // Constructors //////////////////////////////////////////////////////
71
72     private Parser(Reader r, String sourceName, int line) throws IOException { super(r, sourceName, line); }
73
74     /** for debugging */
75     public static void main(String[] s) throws IOException {
76         JS block = JS.fromReader("stdin", 0, new InputStreamReader(System.in));
77         if (block == null) return;
78         System.out.println(block);
79     }
80
81     // Statics ////////////////////////////////////////////////////////////
82
83     static byte[] precedence = new byte[MAX_TOKEN + 1];
84     static boolean[] isRightAssociative = new boolean[MAX_TOKEN + 1];
85     // Use this as the precedence when we want anything up to the comma
86     private final static int NO_COMMA = 2;
87     static {
88         isRightAssociative[ASSIGN] =
89             isRightAssociative[ASSIGN_BITOR] =
90             isRightAssociative[ASSIGN_BITXOR] =
91             isRightAssociative[ASSIGN_BITAND] =
92             isRightAssociative[ASSIGN_LSH] =
93             isRightAssociative[ASSIGN_RSH] =
94             isRightAssociative[ASSIGN_URSH] =
95             isRightAssociative[ASSIGN_ADD] =
96             isRightAssociative[ASSIGN_SUB] =
97             isRightAssociative[ASSIGN_MUL] =
98             isRightAssociative[ASSIGN_DIV] =
99             isRightAssociative[ASSIGN_MOD] =
100             isRightAssociative[ADD_TRAP] =
101             isRightAssociative[DEL_TRAP] =
102             true;
103
104         precedence[COMMA] = 1;
105         // 2 is intentionally left unassigned. we use minPrecedence==2 for comma separated lists
106         precedence[ASSIGN] =
107             precedence[ASSIGN_BITOR] =
108             precedence[ASSIGN_BITXOR] =
109             precedence[ASSIGN_BITAND] =
110             precedence[ASSIGN_LSH] =
111             precedence[ASSIGN_RSH] =
112             precedence[ASSIGN_URSH] =
113             precedence[ASSIGN_ADD] =
114             precedence[ASSIGN_SUB] =
115             precedence[ASSIGN_MUL] =
116             precedence[ASSIGN_DIV] =
117             precedence[ADD_TRAP] =
118             precedence[DEL_TRAP] =
119             precedence[ASSIGN_MOD] = 3;
120         precedence[HOOK] = 4;
121         precedence[OR] = 5;
122         precedence[AND] = 6;
123         precedence[BITOR] = 7;
124         precedence[BITXOR] = 8;
125         precedence[BITAND] = 9;
126         precedence[EQ] = precedence[NE] = precedence[SHEQ] = precedence[SHNE] = 10;
127         precedence[LT] = precedence[LE] = precedence[GT] = precedence[GE] = 11;
128         precedence[LSH] = precedence[RSH] = precedence[URSH] = 12;
129         precedence[ADD] = precedence[SUB] = 12;
130         precedence[MUL] = precedence[DIV] = precedence[MOD] = 13;
131         precedence[BITNOT] =  precedence[BANG] = precedence[TYPEOF] = 14;
132         precedence[DOT] = precedence[LB] = precedence[LP] =  precedence[INC] = precedence[DEC] = 15;
133     }
134
135     // Local variable management
136     Vec scopeStack = new Vec();
137     static class ScopeInfo {
138         int base;
139         int end;
140         int newScopeInsn;
141         Hash mapping = new Hash();
142     }
143     Hash globalCache = new Hash();
144     JS scopeKey(String name) {
145         if(globalCache.get(name) != null) return null;
146         for(int i=scopeStack.size()-1;i>=0;i--) {
147             JS key = (JS)((ScopeInfo) scopeStack.elementAt(i)).mapping.get(name);
148             if(key != null) return key;
149         }
150         globalCache.put(name,Boolean.TRUE);
151         return null;
152     }
153     void scopeDeclare(String name) throws IOException {
154         ScopeInfo si = (ScopeInfo) scopeStack.lastElement();
155         if(si.mapping.get(name) != null) throw pe("" + name + " already declared in this scope");
156         si.mapping.put(name,JS.N(si.end++));
157         globalCache.put(name,null);
158     }
159     void scopePush(JSFunction b) {
160         ScopeInfo prev = (ScopeInfo) scopeStack.lastElement();
161         ScopeInfo si = new ScopeInfo();
162         si.base = prev.end;
163         si.end = si.base;
164         si.newScopeInsn = b.size;
165         scopeStack.push(si);
166         b.add(parserLine, NEWSCOPE);
167     }
168     void scopePop(JSFunction b) {
169         ScopeInfo si = (ScopeInfo) scopeStack.pop();
170         b.add(parserLine, OLDSCOPE);
171         b.set(si.newScopeInsn,JS.N((si.base<<16)|((si.end-si.base)<<0))); 
172     }
173     
174     
175     // Parsing Logic /////////////////////////////////////////////////////////
176     
177     /** parse and compile a function */
178     public static JSFunction fromReader(String sourceName, int firstLine, Reader sourceCode) throws IOException {
179         JSFunction ret = new JSFunction(sourceName, firstLine, null);
180         if (sourceCode == null) return ret;
181         Parser p = new Parser(sourceCode, sourceName, firstLine);
182         p.scopeStack.setSize(0);
183         p.scopeStack.push(new ScopeInfo());
184         p.scopePush(ret);
185         while(true) {
186             //int s = ret.size;
187             if(p.peekToken() == -1) break; // FIXME: Check this logic one more time
188             p.parseStatement(ret, null);
189             //if (s == ret.size) break;
190         }
191         p.scopePop(ret);
192         if(p.scopeStack.size() != 1) throw new Error("scopeStack height mismatch");
193         ret.add(-1, LITERAL, null); 
194         ret.add(-1, RETURN);
195         return ret;
196     }
197
198     /** gets a token and throws an exception if it is not <tt>code</tt> */
199     private void consume(int code) throws IOException {
200         if (getToken() != code) {
201             if(code == NAME) switch(op) {
202                 case RETURN: case TYPEOF: case BREAK: case CONTINUE: case TRY: case THROW:
203                 case ASSERT: case NULL: case TRUE: case FALSE: case IN: case IF: case ELSE:
204                 case SWITCH: case CASE: case DEFAULT: case WHILE: case VAR: case WITH:
205                 case CATCH: case FINALLY:
206                     throw pe("Bad variable name; '" + codeToString[op].toLowerCase() + "' is a javascript keyword");
207             }
208             throw pe("expected " + codeToString[code] + ", got " + (op == -1 ? "EOF" : codeToString[op]));
209         }
210     }
211
212     /**
213      *  Parse the largest possible expression containing no operators
214      *  of precedence below <tt>minPrecedence</tt> and append the
215      *  bytecodes for that expression to <tt>appendTo</tt>; the
216      *  appended bytecodes MUST grow the stack by exactly one element.
217      */ 
218     private void startExpr(JSFunction appendTo, int minPrecedence) throws IOException {
219         int saveParserLine = parserLine;
220         _startExpr(appendTo, minPrecedence);
221         parserLine = saveParserLine;
222     }
223     private void _startExpr(JSFunction appendTo, int minPrecedence) throws IOException {
224         int tok = getToken();
225         JSFunction b = appendTo;
226
227         switch (tok) {
228         case -1: throw pe("expected expression");
229
230         // all of these simply push values onto the stack
231         case NUMBER: b.add(parserLine, LITERAL, JS.N(number)); break;
232         case STRING: b.add(parserLine, LITERAL, JSString.intern(string)); break;
233         case NULL: b.add(parserLine, LITERAL, null); break;
234         case TRUE: case FALSE: b.add(parserLine, LITERAL, tok == TRUE ? JS.T : JS.F); break;
235
236         // (.foo) syntax
237         case DOT: {
238             consume(NAME);
239             b.add(parserLine, GLOBALSCOPE);
240             b.add(parserLine, GET, JS.S("",true));
241             b.add(parserLine, LITERAL, JS.S(string,true));
242             continueExprAfterAssignable(b,minPrecedence,null);
243             break;
244         }
245
246         case LB: {
247             b.add(parserLine, ARRAY, JS.ZERO);                       // push an array onto the stack
248             int size0 = b.size;
249             int i = 0;
250             if (peekToken() != RB)
251                 while(true) {                                               // iterate over the initialization values
252                     b.add(parserLine, LITERAL, JS.N(i++));           // push the index in the array to place it into
253                     if (peekToken() == COMMA || peekToken() == RB)
254                         b.add(parserLine, LITERAL, null);                   // for stuff like [1,,2,]
255                     else
256                         startExpr(b, NO_COMMA);                             // push the value onto the stack
257                     b.add(parserLine, PUT);                                 // put it into the array
258                     b.add(parserLine, POP);                                 // discard the value remaining on the stack
259                     if (peekToken() == RB) break;
260                     consume(COMMA);
261                 }
262             b.set(size0 - 1, JS.N(i));                               // back at the ARRAY instruction, write the size of the array
263             consume(RB);
264             break;
265         }
266         case SUB: case ADD: {
267             if(peekToken() == NUMBER) {   // literal
268                 consume(NUMBER);
269                 b.add(parserLine, LITERAL, JS.N(number.doubleValue() * (tok == SUB ? -1 : 1)));
270             } else { // unary +/- operator
271                 if(tok == SUB) b.add(parserLine, LITERAL, JS.ZERO);
272                 // BITNOT has the same precedence as the unary +/- operators
273                 startExpr(b,precedence[BITNOT]);
274                 if(tok == ADD) b.add(parserLine, LITERAL, JS.ZERO); // HACK to force expr into a numeric context
275                 b.add(parserLine, SUB);
276             }
277             break;
278         }
279         case LP: {  // grouping (not calling)
280             startExpr(b, -1);
281             consume(RP);
282             break;
283         }
284         case INC: case DEC: {  // prefix (not postfix)
285             startExpr(b, precedence[tok]);
286             int prev = b.size - 1;
287             boolean sg = b.get(prev) == SCOPEGET;
288             if (b.get(prev) == GET && b.getArg(prev) != null)
289                 b.set(prev, LITERAL, b.getArg(prev));
290             else if(b.get(prev) == GET)
291                 b.pop();
292             else if(!sg)
293                 throw pe("prefixed increment/decrement can only be performed on a valid assignment target");
294             if(!sg) b.add(parserLine, GET_PRESERVE, Boolean.TRUE);
295             b.add(parserLine, LITERAL, JS.N(1));
296             b.add(parserLine, tok == INC ? ADD : SUB, JS.N(2));
297             if(sg) {
298                 b.add(parserLine, SCOPEPUT, b.getArg(prev));
299             } else {
300                 b.add(parserLine, PUT, null);
301                 b.add(parserLine, SWAP, null);
302                 b.add(parserLine, POP, null);
303             }
304             break;
305         }
306         case BANG: case BITNOT: case TYPEOF: {
307             startExpr(b, precedence[tok]);
308             b.add(parserLine, tok);
309             break;
310         }
311         case LC: { // object constructor
312             b.add(parserLine, OBJECT, null);                                     // put an object on the stack
313             if (peekToken() != RC)
314                 while(true) {
315                     if (peekToken() != NAME && peekToken() != STRING)
316                         throw pe("expected NAME or STRING");
317                     getToken();
318                     b.add(parserLine, LITERAL, JSString.intern(string));                          // grab the key
319                     consume(COLON);
320                     startExpr(b, NO_COMMA);                                      // grab the value
321                     b.add(parserLine, PUT);                                      // put the value into the object
322                     b.add(parserLine, POP);                                      // discard the remaining value
323                     if (peekToken() == RC) break;
324                     consume(COMMA);
325                     if (peekToken() == RC) break;                                // we permit {,,} -- I'm not sure if ECMA does
326                 }
327             consume(RC);
328             break;
329         }
330         case NAME: {
331             JS varKey = scopeKey(string);
332             if(varKey == null) {
333                 b.add(parserLine, GLOBALSCOPE);
334                 b.add(parserLine, LITERAL, JSString.intern(string));
335             }
336             continueExprAfterAssignable(b,minPrecedence,varKey);
337             break;
338         }
339         case CASCADE: {
340             if(peekToken() == ASSIGN) {
341                 consume(ASSIGN);
342                 startExpr(b, precedence[ASSIGN]);
343                 b.add(parserLine, CASCADE, JS.T);
344             } else {
345                 b.add(parserLine, CASCADE, JS.F);
346             }
347             break;
348         }
349                 
350         case FUNCTION: {
351             consume(LP);
352             int numArgs = 0;
353             JSFunction b2 = new JSFunction(sourceName, parserLine, null);
354             b.add(parserLine, NEWFUNCTION, b2);
355
356             // function prelude; arguments array is already on the stack
357             scopePush(b2);
358             scopeDeclare("arguments");
359             b2.add(parserLine, SCOPEPUT,scopeKey("arguments"));
360
361             while(peekToken() != RP) {                                    // run through the list of argument names
362                 numArgs++;
363                 if (peekToken() == NAME) {
364                     consume(NAME);                                        // a named argument
365                     
366                     b2.add(parserLine, DUP);                              // dup the args array 
367                     b2.add(parserLine, GET, JS.N(numArgs - 1));   // retrieve it from the arguments array
368                     scopeDeclare(string);
369                     b2.add(parserLine, SCOPEPUT, scopeKey(string));
370                     b2.add(parserLine, POP);
371                 }
372                 if (peekToken() == RP) break;
373                 consume(COMMA);
374             }
375             consume(RP);
376
377             b2.numFormalArgs = numArgs;
378             b2.add(parserLine, POP);                                      // pop off the arguments array
379             
380            if(peekToken() != LC)
381                 throw pe("JSFunctions must have a block surrounded by curly brackets");
382                 
383             parseBlock(b2, null);                                   // the function body
384             
385             scopePop(b2);
386             b2.add(parserLine, LITERAL, null);                        // in case we "fall out the bottom", return NULL
387             b2.add(parserLine, RETURN);
388
389             break;
390         }
391         default: throw pe("expected expression, found " + codeToString[tok] + ", which cannot start an expression");
392         }
393
394         // attempt to continue the expression
395         continueExpr(b, minPrecedence);
396     }
397     /*
398     private Grammar parseGrammar(Grammar g) throws IOException {
399         int tok = getToken();
400         if (g != null)
401             switch(tok) {
402                 case BITOR: return new Grammar.Alternative(g, parseGrammar(null));
403                 case ADD:   return parseGrammar(new Grammar.Repetition(g, 1, Integer.MAX_VALUE));
404                 case MUL:   return parseGrammar(new Grammar.Repetition(g, 0, Integer.MAX_VALUE));
405                 case HOOK:  return parseGrammar(new Grammar.Repetition(g, 0, 1));
406             }
407         Grammar g0 = null;
408         switch(tok) {
409             //case NUMBER: g0 = new Grammar.Literal(number); break;
410             case NAME: g0 = new Grammar.Reference(string); break;
411             case STRING:
412                 g0 = new Grammar.Literal(string);
413                 if (peekToken() == DOT) {
414                     String old = string;
415                     consume(DOT);
416                     consume(DOT);
417                     consume(STRING);
418                     if (old.length() != 1 || string.length() != 1) throw pe("literal ranges must be single-char strings");
419                     g0 = new Grammar.Range(old.charAt(0), string.charAt(0));
420                 }
421                 break;
422             case LP:     g0 = parseGrammar(null); consume(RP); break;
423             default:     pushBackToken(); return g;
424         }
425         if (g == null) return parseGrammar(g0);
426         return parseGrammar(new Grammar.Juxtaposition(g, g0));
427     }
428     */
429     /**
430      *  Assuming that a complete assignable (lvalue) has just been
431      *  parsed and the object and key are on the stack,
432      *  <tt>continueExprAfterAssignable</tt> will attempt to parse an
433      *  expression that modifies the assignable.  This method always
434      *  decreases the stack depth by exactly one element.
435      */
436     private void continueExprAfterAssignable(JSFunction b,int minPrecedence, JS varKey) throws IOException {
437         int saveParserLine = parserLine;
438         _continueExprAfterAssignable(b,minPrecedence,varKey);
439         parserLine = saveParserLine;
440     }
441     private void _continueExprAfterAssignable(JSFunction b,int minPrecedence, JS varKey) throws IOException {
442         if (b == null) throw new Error("got null b; this should never happen");
443         int tok = getToken();
444         if (minPrecedence != -1 && (precedence[tok] < minPrecedence || (precedence[tok] == minPrecedence && !isRightAssociative[tok])))
445             // force the default case
446             tok = -1;
447         switch(tok) {
448             /*
449         case GRAMMAR: {
450             b.add(parserLine, GET_PRESERVE);
451             Grammar g = parseGrammar(null);
452             if (peekToken() == LC) {
453                 g.action = new JSFunction(sourceName, parserLine, null);
454                 parseBlock((JSFunction)g.action);
455                 ((JSFunction)g.action).add(parserLine, LITERAL, null);         // in case we "fall out the bottom", return NULL              
456                 ((JSFunction)g.action).add(parserLine, RETURN);
457             }
458             b.add(parserLine, MAKE_GRAMMAR, g);
459             b.add(parserLine, PUT);
460             break;
461         }
462             */
463         case ASSIGN_BITOR: case ASSIGN_BITXOR: case ASSIGN_BITAND: case ASSIGN_LSH: case ASSIGN_RSH: case ASSIGN_URSH:
464         case ASSIGN_MUL: case ASSIGN_DIV: case ASSIGN_MOD: case ASSIGN_ADD: case ASSIGN_SUB: case ADD_TRAP: case DEL_TRAP: {
465             if (tok != ADD_TRAP && tok != DEL_TRAP) 
466                 b.add(parserLine, varKey == null ? GET_PRESERVE : SCOPEGET, varKey);
467             
468             startExpr(b,  precedence[tok]);
469             
470             if (tok != ADD_TRAP && tok != DEL_TRAP) {
471                 // tok-1 is always s/^ASSIGN_// (0 is BITOR, 1 is ASSIGN_BITOR, etc) 
472                 b.add(parserLine, tok - 1, tok-1==ADD ? JS.N(2) : null);
473                 if(varKey == null) {
474                     b.add(parserLine, PUT);
475                     b.add(parserLine, SWAP);
476                     b.add(parserLine, POP);
477                 } else {
478                     b.add(parserLine, SCOPEPUT, varKey);
479                 }
480             } else {
481                 if(varKey != null) throw pe("cannot place traps on local variables");
482                 b.add(parserLine, tok);
483             }
484             break;
485         }
486         case INC: case DEC: { // postfix
487             if(varKey == null) {
488                 b.add(parserLine, GET_PRESERVE, Boolean.TRUE);
489                 b.add(parserLine, LITERAL, JS.N(1));
490                 b.add(parserLine, tok == INC ? ADD : SUB, JS.N(2));
491                 b.add(parserLine, PUT, null);
492                 b.add(parserLine, SWAP, null);
493                 b.add(parserLine, POP, null);
494                 b.add(parserLine, LITERAL, JS.N(1));
495                 b.add(parserLine, tok == INC ? SUB : ADD, JS.N(2));   // undo what we just did, since this is postfix
496             } else {
497                 b.add(parserLine, SCOPEGET, varKey);
498                 b.add(parserLine, DUP);
499                 b.add(parserLine, LITERAL, JS.ONE);
500                 b.add(parserLine, tok == INC ? ADD : SUB, JS.N(2));
501                 b.add(parserLine, SCOPEPUT, varKey);
502             }
503             break;
504         }
505         case ASSIGN: {
506             startExpr(b, precedence[tok]);
507             if(varKey == null) {
508                 b.add(parserLine, PUT);
509                 b.add(parserLine, SWAP);
510                 b.add(parserLine, POP);
511             } else {
512                 b.add(parserLine, SCOPEPUT, varKey);
513             }
514             break;
515         }
516         case LP: {
517             // Method calls are implemented by doing a GET_PRESERVE
518             // first.  If the object supports method calls, it will
519             // return JS.METHOD
520             b.add(parserLine, varKey == null ? GET_PRESERVE : SCOPEGET, varKey);
521             int n = parseArgs(b);
522             b.add(parserLine, varKey == null ? CALLMETHOD : CALL, JS.N(n));
523             break;
524         }
525         default: {
526             pushBackToken();
527             if(varKey != null)
528                 b.add(parserLine, SCOPEGET, varKey);
529             else if(b.get(b.size-1) == LITERAL && b.getArg(b.size-1) != null)
530                 b.set(b.size-1,GET,b.getArg(b.size-1));
531             else
532                 b.add(parserLine, GET);
533             return;
534         }
535         }
536     }
537
538
539     /**
540      *  Assuming that a complete expression has just been parsed,
541      *  <tt>continueExpr</tt> will attempt to extend this expression by
542      *  parsing additional tokens and appending additional bytecodes.
543      *
544      *  No operators with precedence less than <tt>minPrecedence</tt>
545      *  will be parsed.
546      *
547      *  If any bytecodes are appended, they will not alter the stack
548      *  depth.
549      */
550     private void continueExpr(JSFunction b, int minPrecedence) throws IOException {
551         int saveParserLine = parserLine;
552         _continueExpr(b, minPrecedence);
553         parserLine = saveParserLine;
554     }
555     private void _continueExpr(JSFunction b, int minPrecedence) throws IOException {
556         if (b == null) throw new Error("got null b; this should never happen");
557         int tok = getToken();
558         if (tok == -1) return;
559         if (minPrecedence != -1 && (precedence[tok] < minPrecedence || (precedence[tok] == minPrecedence && !isRightAssociative[tok]))) {
560             pushBackToken();
561             return;
562         }
563
564         switch (tok) {
565         case LP: {  // invocation (not grouping)
566             int n = parseArgs(b);
567             b.add(parserLine, CALL, JS.N(n));
568             break;
569         }
570         case BITOR: case BITXOR: case BITAND: case SHEQ: case SHNE: case LSH:
571         case RSH: case URSH: case MUL: case DIV: case MOD:
572         case GT: case GE: case EQ: case NE: case LT: case LE: case SUB: {
573             startExpr(b, precedence[tok]);
574             b.add(parserLine, tok);
575             break;
576         }
577         case ADD: {
578             int count=1;
579             int nextTok;
580             do {
581                 startExpr(b,precedence[tok]);
582                 count++;
583                 nextTok = getToken();
584             } while(nextTok == tok);
585             pushBackToken();
586             b.add(parserLine, tok, JS.N(count));
587             break;
588         }
589         case OR: case AND: {
590             b.add(parserLine, tok == AND ? JSFunction.JF : JSFunction.JT, JS.ZERO);       // test to see if we can short-circuit
591             int size = b.size;
592             startExpr(b, precedence[tok]);                                     // otherwise check the second value
593             b.add(parserLine, JMP, JS.N(2));                            // leave the second value on the stack and jump to the end
594             b.add(parserLine, LITERAL, tok == AND ?
595                   JS.B(false) : JS.B(true));                     // target of the short-circuit jump is here
596             b.set(size - 1, JS.N(b.size - size));                     // write the target of the short-circuit jump
597             break;
598         }
599         case DOT: {
600             // support foo..bar syntax for foo[""].bar
601             if (peekToken() == DOT) {
602                 string = "";
603             } else {
604                 consume(NAME);
605             }
606             b.add(parserLine, LITERAL, JSString.intern(string));
607             continueExprAfterAssignable(b,minPrecedence,null);
608             break;
609         }
610         case LB: { // subscripting (not array constructor)
611             startExpr(b, -1);
612             consume(RB);
613             continueExprAfterAssignable(b,minPrecedence,null);
614             break;
615         }
616         case HOOK: {
617             b.add(parserLine, JF, JS.ZERO);                // jump to the if-false expression
618             int size = b.size;
619             startExpr(b, minPrecedence);                          // write the if-true expression
620             b.add(parserLine, JMP, JS.ZERO);               // if true, jump *over* the if-false expression     
621             b.set(size - 1, JS.N(b.size - size + 1));    // now we know where the target of the jump is
622             consume(COLON);
623             size = b.size;
624             startExpr(b, minPrecedence);                          // write the if-false expression
625             b.set(size - 1, JS.N(b.size - size + 1));    // this is the end; jump to here
626             break;
627         }
628         case COMMA: {
629             // pop the result of the previous expression, it is ignored
630             b.add(parserLine,POP);
631             startExpr(b,-1);
632             break;
633         }
634         default: {
635             pushBackToken();
636             return;
637         }
638         }
639
640         continueExpr(b, minPrecedence);                           // try to continue the expression
641     }
642     
643     // parse a set of comma separated function arguments, assume LP has already been consumed
644     private int parseArgs(JSFunction b) throws IOException {
645         int i = 0;
646         while(peekToken() != RP) {
647             i++;
648             if (peekToken() != COMMA) {
649                 startExpr(b, NO_COMMA);
650                 if (peekToken() == RP) break;
651             }
652             consume(COMMA);
653         }
654         consume(RP);
655         return i;
656     }
657     
658     /** Parse a block of statements which must be surrounded by LC..RC. */
659     void parseBlock(JSFunction b) throws IOException { parseBlock(b, null); }
660     void parseBlock(JSFunction b, String label) throws IOException {
661         int saveParserLine = parserLine;
662         _parseBlock(b, label);
663         parserLine = saveParserLine;
664     }
665     void _parseBlock(JSFunction b, String label) throws IOException {
666         if (peekToken() == -1) return;
667         else if (peekToken() != LC) parseStatement(b, null);
668         else {
669             consume(LC);
670             while(peekToken() != RC && peekToken() != -1) parseStatement(b, null);
671             consume(RC);
672         }
673     }
674
675     /** Parse a single statement, consuming the RC or SEMI which terminates it. */
676     void parseStatement(JSFunction b, String label) throws IOException {
677         int saveParserLine = parserLine;
678         _parseStatement(b, label);
679         parserLine = saveParserLine;
680     }
681     void _parseStatement(JSFunction b, String label) throws IOException {
682         int tok = peekToken();
683         if (tok == -1) return;
684         switch(tok = getToken()) {
685             
686         case THROW: case ASSERT: case RETURN: {
687             if (tok == RETURN && peekToken() == SEMI)
688                 b.add(parserLine, LITERAL, null);
689             else
690                 startExpr(b, -1);
691             b.add(parserLine, tok);
692             consume(SEMI);
693             break;
694         }
695         case BREAK: case CONTINUE: {
696             if (peekToken() == NAME) consume(NAME);
697             b.add(parserLine, tok, string);
698             consume(SEMI);
699             break;
700         }
701         case VAR: {
702             while(true) {
703                 consume(NAME);
704                 String var = string;
705                 scopeDeclare(var);
706                 if (peekToken() == ASSIGN) {                     // if there is an '=' after the variable name
707                     consume(ASSIGN);
708                     startExpr(b, NO_COMMA);
709                     b.add(parserLine, SCOPEPUT, scopeKey(var)); // assign it
710                     b.add(parserLine, POP);                      // clean the stack
711                 }
712                 if (peekToken() != COMMA) break;
713                 consume(COMMA);
714             }
715             if ((mostRecentlyReadToken != RC || peekToken() == SEMI) && peekToken() != -1 && mostRecentlyReadToken != SEMI) consume(SEMI);
716             break;
717         }
718         case IF: {
719             consume(LP);
720             startExpr(b, -1);
721             consume(RP);
722             
723             b.add(parserLine, JF, JS.ZERO);                    // if false, jump to the else-block
724             int size = b.size;
725             parseStatement(b, null);
726             
727             if (peekToken() == ELSE) {
728                 consume(ELSE);
729                 b.add(parserLine, JMP, JS.ZERO);               // if we took the true-block, jump over the else-block
730                 b.set(size - 1, JS.N(b.size - size + 1));
731                 size = b.size;
732                 parseStatement(b, null);
733             }
734             b.set(size - 1, JS.N(b.size - size + 1));        // regardless of which branch we took, b[size] needs to point here
735             break;
736         }
737         case WHILE: {
738             consume(LP);
739             if (label != null) b.add(parserLine, LABEL, label);
740             b.add(parserLine, LOOP);
741             int size = b.size;
742             b.add(parserLine, POP);                                   // discard the first-iteration indicator
743             startExpr(b, -1);
744             b.add(parserLine, JT, JS.N(2));                    // if the while() clause is true, jump over the BREAK
745             b.add(parserLine, BREAK);
746             consume(RP);
747             parseStatement(b, null);
748             b.add(parserLine, CONTINUE);                              // if we fall out of the end, definately continue
749             b.set(size - 1, JS.N(b.size - size + 1));        // end of the loop
750             break;
751         }
752         case SWITCH: {
753             consume(LP);
754             if (label != null) b.add(parserLine, LABEL, label);
755             b.add(parserLine, LOOP);
756             int size0 = b.size;
757             startExpr(b, -1);
758             consume(RP);
759             consume(LC);
760             while(true)
761                 if (peekToken() == CASE) {                         // we compile CASE statements like a bunch of if..else's
762                     consume(CASE);
763                     b.add(parserLine, DUP);                        // duplicate the switch() value; we'll consume one copy
764                     startExpr(b, -1);
765                     consume(COLON);
766                     b.add(parserLine, EQ);                         // check if we should do this case-block
767                     b.add(parserLine, JF, JS.ZERO);         // if not, jump to the next one
768                     int size = b.size;
769                     while(peekToken() != CASE && peekToken() != DEFAULT && peekToken() != RC) parseStatement(b, null);
770                     b.set(size - 1, JS.N(1 + b.size - size));
771                 } else if (peekToken() == DEFAULT) {
772                     consume(DEFAULT);
773                     consume(COLON);
774                     while(peekToken() != CASE && peekToken() != DEFAULT && peekToken() != RC) parseStatement(b, null);
775                 } else if (peekToken() == RC) {
776                     consume(RC);
777                     b.add(parserLine, BREAK);                      // break out of the loop if we 'fall through'
778                     break;
779                 } else {
780                     throw pe("expected CASE, DEFAULT, or RC; got " + codeToString[peekToken()]);
781                 }
782             b.set(size0 - 1, JS.N(b.size - size0 + 1));      // end of the loop
783             break;
784         }
785             
786         case DO: {
787             if (label != null) b.add(parserLine, LABEL, label);
788             b.add(parserLine, LOOP);
789             int size = b.size;
790             parseStatement(b, null);
791             consume(WHILE);
792             consume(LP);
793             startExpr(b, -1);
794             b.add(parserLine, JT, JS.N(2));                  // check the while() clause; jump over the BREAK if true
795             b.add(parserLine, BREAK);
796             b.add(parserLine, CONTINUE);
797             consume(RP);
798             consume(SEMI);
799             b.set(size - 1, JS.N(b.size - size + 1));      // end of the loop; write this location to the LOOP instruction
800             break;
801         }
802             
803         case TRY: {
804             b.add(parserLine, TRY); // try bytecode causes a TryMarker to be pushed
805             int tryInsn = b.size - 1;
806             // parse the expression to be TRYed
807             parseStatement(b, null); 
808             // pop the try  marker. this is pushed when the TRY bytecode is executed                              
809             b.add(parserLine, POP);
810             // jump forward to the end of the catch block, start of the finally block                             
811             b.add(parserLine, JMP);                                  
812             int successJMPInsn = b.size - 1;
813             
814             if (peekToken() != CATCH && peekToken() != FINALLY)
815                 throw pe("try without catch or finally");
816             
817             int catchJMPDistance = -1;
818             if (peekToken() == CATCH) {
819                 Vec catchEnds = new Vec();
820                 boolean catchAll = false;
821                 
822                 catchJMPDistance = b.size - tryInsn;
823                 
824                 while(peekToken() == CATCH && !catchAll) {
825                     String exceptionVar;
826                     getToken();
827                     consume(LP);
828                     consume(NAME);
829                     exceptionVar = string;
830                     int[] writebacks = new int[] { -1, -1, -1 };
831                     if (peekToken() != RP) {
832                         // extended Ibex catch block: catch(e faultCode "foo.bar.baz")
833                         consume(NAME);
834                         b.add(parserLine, DUP);
835                         b.add(parserLine, LITERAL, JSString.intern(string));
836                         b.add(parserLine, GET);
837                         b.add(parserLine, DUP);
838                         b.add(parserLine, LITERAL, null);
839                         b.add(parserLine, EQ);
840                         b.add(parserLine, JT);
841                         writebacks[0] = b.size - 1;
842                         if (peekToken() == STRING) {
843                             consume(STRING);
844                             b.add(parserLine, DUP);
845                             b.add(parserLine, LITERAL, string);
846                             b.add(parserLine, LT);
847                             b.add(parserLine, JT);
848                             writebacks[1] = b.size - 1;
849                             b.add(parserLine, DUP);
850                             b.add(parserLine, LITERAL, string + "/");   // (slash is ASCII after dot)
851                             b.add(parserLine, GE);
852                             b.add(parserLine, JT);
853                             writebacks[2] = b.size - 1;
854                         } else {
855                             consume(NUMBER);
856                             b.add(parserLine, DUP);
857                             b.add(parserLine, LITERAL, number);
858                             b.add(parserLine, EQ);
859                             b.add(parserLine, JF);
860                             writebacks[1] = b.size - 1;
861                         }
862                         b.add(parserLine, POP);  // pop the element thats on the stack from the compare
863                     } else {
864                         catchAll = true;
865                     }
866                     consume(RP);
867                     // the exception is on top of the stack; put it to the chosen name
868                     scopePush(b);
869                     scopeDeclare(exceptionVar);
870                     b.add(parserLine, SCOPEPUT, scopeKey(exceptionVar));
871                     b.add(parserLine, POP);
872                     parseBlock(b, null);
873                     scopePop(b);
874                     
875                     b.add(parserLine, JMP);
876                     catchEnds.addElement(new Integer(b.size-1));
877                     
878                     for(int i=0; i<3; i++) if (writebacks[i] != -1) b.set(writebacks[i], JS.N(b.size-writebacks[i]));
879                     b.add(parserLine, POP); // pop the element thats on the stack from the compare
880                 }
881                 
882                 if(!catchAll)
883                     b.add(parserLine, THROW);
884                 
885                 for(int i=0;i<catchEnds.size();i++) {
886                     int n = ((Integer)catchEnds.elementAt(i)).intValue();
887                     b.set(n, JS.N(b.size-n));
888                 }
889                 
890                 // pop the try and catch markers
891                 b.add(parserLine,POP);
892                 b.add(parserLine,POP);
893             }
894                         
895             // jump here if no exception was thrown
896             b.set(successJMPInsn, JS.N(b.size - successJMPInsn)); 
897                         
898             int finallyJMPDistance = -1;
899             if (peekToken() == FINALLY) {
900                 b.add(parserLine, LITERAL, null); // null FinallyData
901                 finallyJMPDistance = b.size - tryInsn;
902                 consume(FINALLY);
903                 parseStatement(b, null);
904                 b.add(parserLine,FINALLY_DONE); 
905             }
906             
907             // setup the TRY arguments
908             b.set(tryInsn, new int[] { catchJMPDistance, finallyJMPDistance });
909             
910             break;
911         }
912             
913         case FOR: {
914             consume(LP);
915             
916             tok = getToken();
917             boolean hadVar = false;                                      // if it's a for..in, we ignore the VAR
918             if (tok == VAR) { hadVar = true; tok = getToken(); }
919             String varName = string;
920             boolean forIn = peekToken() == IN;                           // determine if this is a for..in loop or not
921             pushBackToken(tok, varName);
922             
923             if (forIn) {
924                 consume(NAME);
925                 consume(IN);
926                 startExpr(b,-1);
927                 consume(RP);
928                 
929                 b.add(parserLine, PUSHKEYS);
930                 
931                 int size = b.size;
932                 b.add(parserLine, LOOP);
933                 b.add(parserLine, POP);
934                 
935                 b.add(parserLine,SWAP); // get the keys enumeration object on top
936                 b.add(parserLine,DUP);
937                 b.add(parserLine,GET,JS.S("hasMoreElements"));
938                 int size2 = b.size;
939                 b.add(parserLine,JT);
940                 b.add(parserLine,SWAP);
941                 b.add(parserLine,BREAK);
942                 b.set(size2, JS.N(b.size - size2));
943                 b.add(parserLine,DUP);
944                 b.add(parserLine,GET,JS.S("nextElement"));
945
946                 scopePush(b);
947                 
948                 if(hadVar) scopeDeclare(varName);
949                 JS varKey = scopeKey(varName);
950                 
951                 if(varKey == null) {
952                     b.add(parserLine,GLOBALSCOPE);
953                     b.add(parserLine,SWAP);
954                     b.add(parserLine, LITERAL, JSString.intern(varName));
955                     b.add(parserLine,SWAP);
956                     b.add(parserLine,PUT);
957                     b.add(parserLine,POP);
958                 } else {
959                     b.add(parserLine, SCOPEPUT, varKey);
960                 }
961                 b.add(parserLine,POP);  // pop the put'ed value
962                 b.add(parserLine,SWAP); // put CallMarker back into place
963                 
964                 parseStatement(b, null);
965                 
966                 scopePop(b);
967                 b.add(parserLine, CONTINUE);
968                 // jump here on break
969                 b.set(size, JS.N(b.size - size));
970                 
971                 b.add(parserLine, POP);
972             } else {
973                 if (hadVar) pushBackToken(VAR, null);                    // yeah, this actually matters
974                 scopePush(b);                             // grab a fresh scope
975                     
976                 parseStatement(b, null);                                 // initializer
977                 JSFunction e2 =                                    // we need to put the incrementor before the test
978                     new JSFunction(sourceName, parserLine, null);  // so we save the test here
979                 if (peekToken() != SEMI)
980                     startExpr(e2, -1);
981                 else
982                     e2.add(parserLine, JSFunction.LITERAL, JS.T);         // handle the for(foo;;foo) case
983                 consume(SEMI);
984                 if (label != null) b.add(parserLine, LABEL, label);
985                 b.add(parserLine, LOOP);
986                 int size2 = b.size;
987                     
988                 b.add(parserLine, JT, JS.ZERO);                   // if we're on the first iteration, jump over the incrementor
989                 int size = b.size;
990                 if (peekToken() != RP) {                                 // do the increment thing
991                     startExpr(b, -1);
992                     b.add(parserLine, POP);
993                 }
994                 b.set(size - 1, JS.N(b.size - size + 1));
995                 consume(RP);
996                     
997                 b.paste(e2);                                             // ok, *now* test if we're done yet
998                 b.add(parserLine, JT, JS.N(2));                   // break out if we don't meet the test
999                 b.add(parserLine, BREAK);
1000                 parseStatement(b, null);
1001                 b.add(parserLine, CONTINUE);                             // if we fall out the bottom, CONTINUE
1002                 b.set(size2 - 1, JS.N(b.size - size2 + 1));     // end of the loop
1003                     
1004                 scopePop(b);                            // get our scope back
1005             }
1006             break;
1007         }
1008                 
1009         case NAME: {  // either a label or an identifier; this is the one place we're not LL(1)
1010             String possiblyTheLabel = string;
1011             if (peekToken() == COLON) {      // label
1012                 consume(COLON);
1013                 parseStatement(b, possiblyTheLabel);
1014                 break;
1015             } else {                         // expression
1016                 pushBackToken(NAME, possiblyTheLabel);  
1017                 startExpr(b, -1);
1018                 b.add(parserLine, POP);
1019                 if ((mostRecentlyReadToken != RC || peekToken() == SEMI) && peekToken() != -1 && mostRecentlyReadToken != SEMI) consume(SEMI);
1020                 break;
1021             }
1022         }
1023
1024         case SEMI: return;                                               // yep, the null statement is valid
1025
1026         case LC: {  // blocks are statements too
1027             pushBackToken();
1028             scopePush(b);
1029             parseBlock(b, label);
1030             scopePop(b);
1031             break;
1032         }
1033
1034         default: {  // hope that it's an expression
1035             pushBackToken();
1036             startExpr(b, -1);
1037             b.add(parserLine, POP);
1038             if ((mostRecentlyReadToken != RC || peekToken() == SEMI) && peekToken() != -1 && mostRecentlyReadToken != SEMI) consume(SEMI);
1039             break;
1040         }
1041         }
1042     }
1043
1044
1045     // ParserException //////////////////////////////////////////////////////////////////////
1046     private IOException pe(String s) { return new IOException(sourceName + ":" + line + " " + s); }
1047     
1048 }
1049