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