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