remove obsolete grammar stuff
[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     /**
403      *  Assuming that a complete assignable (lvalue) has just been
404      *  parsed and the object and key are on the stack,
405      *  <tt>continueExprAfterAssignable</tt> will attempt to parse an
406      *  expression that modifies the assignable.  This method always
407      *  decreases the stack depth by exactly one element.
408      */
409     private void continueExprAfterAssignable(JSFunction b,int minPrecedence, JS varKey) throws IOException {
410         int saveParserLine = parserLine;
411         _continueExprAfterAssignable(b,minPrecedence,varKey);
412         parserLine = saveParserLine;
413     }
414     private void _continueExprAfterAssignable(JSFunction b,int minPrecedence, JS varKey) throws IOException {
415         if (b == null) throw new Error("got null b; this should never happen");
416         int tok = getToken();
417         if (minPrecedence != -1 && (precedence[tok] < minPrecedence || (precedence[tok] == minPrecedence && !isRightAssociative[tok])))
418             // force the default case
419             tok = -1;
420         switch(tok) {
421         case ASSIGN_BITOR: case ASSIGN_BITXOR: case ASSIGN_BITAND: case ASSIGN_LSH: case ASSIGN_RSH: case ASSIGN_URSH:
422         case ASSIGN_MUL: case ASSIGN_DIV: case ASSIGN_MOD: case ASSIGN_ADD: case ASSIGN_SUB: case ADD_TRAP: case DEL_TRAP: {
423             if (tok != ADD_TRAP && tok != DEL_TRAP) 
424                 b.add(parserLine, varKey == null ? GET_PRESERVE : SCOPEGET, varKey);
425             
426             startExpr(b,  precedence[tok]);
427             
428             if (tok != ADD_TRAP && tok != DEL_TRAP) {
429                 // tok-1 is always s/^ASSIGN_// (0 is BITOR, 1 is ASSIGN_BITOR, etc) 
430                 b.add(parserLine, tok - 1, tok-1==ADD ? JSU.N(2) : null);
431                 if(varKey == null) {
432                     b.add(parserLine, PUT);
433                     b.add(parserLine, SWAP);
434                     b.add(parserLine, POP);
435                 } else {
436                     b.add(parserLine, SCOPEPUT, varKey);
437                 }
438             } else {
439                 if(varKey != null) throw pe("cannot place traps on local variables");
440                 b.add(parserLine, tok);
441             }
442             break;
443         }
444         case INC: case DEC: { // postfix
445             if(varKey == null) {
446                 b.add(parserLine, GET_PRESERVE, Boolean.TRUE);
447                 b.add(parserLine, LITERAL, JSU.N(1));
448                 b.add(parserLine, tok == INC ? ADD : SUB, JSU.N(2));
449                 b.add(parserLine, PUT, null);
450                 b.add(parserLine, SWAP, null);
451                 b.add(parserLine, POP, null);
452                 b.add(parserLine, LITERAL, JSU.N(1));
453                 b.add(parserLine, tok == INC ? SUB : ADD, JSU.N(2));   // undo what we just did, since this is postfix
454             } else {
455                 b.add(parserLine, SCOPEGET, varKey);
456                 b.add(parserLine, DUP);
457                 b.add(parserLine, LITERAL, JSU.ONE);
458                 b.add(parserLine, tok == INC ? ADD : SUB, JSU.N(2));
459                 b.add(parserLine, SCOPEPUT, varKey);
460             }
461             break;
462         }
463         case ASSIGN: {
464             startExpr(b, precedence[tok]);
465             if(varKey == null) {
466                 b.add(parserLine, PUT);
467                 b.add(parserLine, SWAP);
468                 b.add(parserLine, POP);
469             } else {
470                 b.add(parserLine, SCOPEPUT, varKey);
471             }
472             break;
473         }
474         case LP: {
475             // Method calls are implemented by doing a GET_PRESERVE
476             // first.  If the object supports method calls, it will
477             // return JS.METHOD
478             b.add(parserLine, varKey == null ? GET_PRESERVE : SCOPEGET, varKey);
479             int n = parseArgs(b);
480             b.add(parserLine, varKey == null ? CALLMETHOD : CALL, JSU.N(n));
481             break;
482         }
483         default: {
484             pushBackToken();
485             if(varKey != null)
486                 b.add(parserLine, SCOPEGET, varKey);
487             else if(b.get(b.size-1) == LITERAL && b.getArg(b.size-1) != null)
488                 b.set(b.size-1,GET,b.getArg(b.size-1));
489             else
490                 b.add(parserLine, GET);
491             return;
492         }
493         }
494     }
495
496
497     /**
498      *  Assuming that a complete expression has just been parsed,
499      *  <tt>continueExpr</tt> will attempt to extend this expression by
500      *  parsing additional tokens and appending additional bytecodes.
501      *
502      *  No operators with precedence less than <tt>minPrecedence</tt>
503      *  will be parsed.
504      *
505      *  If any bytecodes are appended, they will not alter the stack
506      *  depth.
507      */
508     private void continueExpr(JSFunction b, int minPrecedence) throws IOException {
509         int saveParserLine = parserLine;
510         _continueExpr(b, minPrecedence);
511         parserLine = saveParserLine;
512     }
513     private void _continueExpr(JSFunction b, int minPrecedence) throws IOException {
514         if (b == null) throw new Error("got null b; this should never happen");
515         int tok = getToken();
516         if (tok == -1) return;
517         if (minPrecedence != -1 && (precedence[tok] < minPrecedence || (precedence[tok] == minPrecedence && !isRightAssociative[tok]))) {
518             pushBackToken();
519             return;
520         }
521
522         switch (tok) {
523         case LP: {  // invocation (not grouping)
524             int n = parseArgs(b);
525             b.add(parserLine, CALL, JSU.N(n));
526             break;
527         }
528         case BITOR: case BITXOR: case BITAND: case SHEQ: case SHNE: case LSH:
529         case RSH: case URSH: case MUL: case DIV: case MOD:
530         case GT: case GE: case EQ: case NE: case LT: case LE: case SUB: {
531             startExpr(b, precedence[tok]);
532             b.add(parserLine, tok);
533             break;
534         }
535         case ADD: {
536             int count=1;
537             int nextTok;
538             do {
539                 startExpr(b,precedence[tok]);
540                 count++;
541                 nextTok = getToken();
542             } while(nextTok == tok);
543             pushBackToken();
544             b.add(parserLine, tok, JSU.N(count));
545             break;
546         }
547         case OR: case AND: {
548             b.add(parserLine, tok == AND ? JSFunction.JF : JSFunction.JT, JSU.ZERO);       // test to see if we can short-circuit
549             int size = b.size;
550             startExpr(b, precedence[tok]);                                     // otherwise check the second value
551             b.add(parserLine, JMP, JSU.N(2));                            // leave the second value on the stack and jump to the end
552             b.add(parserLine, LITERAL, tok == AND ?
553                   JSU.B(false) : JSU.B(true));                     // target of the short-circuit jump is here
554             b.set(size - 1, JSU.N(b.size - size));                     // write the target of the short-circuit jump
555             break;
556         }
557         case DOT: {
558             // support foo..bar syntax for foo[""].bar
559             if (peekToken() == DOT) {
560                 string = "";
561             } else {
562                 consume(NAME);
563             }
564             b.add(parserLine, LITERAL, JSString.intern(string));
565             continueExprAfterAssignable(b,minPrecedence,null);
566             break;
567         }
568         case LB: { // subscripting (not array constructor)
569             startExpr(b, -1);
570             consume(RB);
571             continueExprAfterAssignable(b,minPrecedence,null);
572             break;
573         }
574         case HOOK: {
575             b.add(parserLine, JF, JSU.ZERO);                // jump to the if-false expression
576             int size = b.size;
577             startExpr(b, minPrecedence);                          // write the if-true expression
578             b.add(parserLine, JMP, JSU.ZERO);               // if true, jump *over* the if-false expression     
579             b.set(size - 1, JSU.N(b.size - size + 1));    // now we know where the target of the jump is
580             consume(COLON);
581             size = b.size;
582             startExpr(b, minPrecedence);                          // write the if-false expression
583             b.set(size - 1, JSU.N(b.size - size + 1));    // this is the end; jump to here
584             break;
585         }
586         case COMMA: {
587             // pop the result of the previous expression, it is ignored
588             b.add(parserLine,POP);
589             startExpr(b,-1);
590             break;
591         }
592         default: {
593             pushBackToken();
594             return;
595         }
596         }
597
598         continueExpr(b, minPrecedence);                           // try to continue the expression
599     }
600     
601     // parse a set of comma separated function arguments, assume LP has already been consumed
602     private int parseArgs(JSFunction b) throws IOException {
603         int i = 0;
604         while(peekToken() != RP) {
605             i++;
606             if (peekToken() != COMMA) {
607                 startExpr(b, NO_COMMA);
608                 if (peekToken() == RP) break;
609             }
610             consume(COMMA);
611         }
612         consume(RP);
613         return i;
614     }
615     
616     /** Parse a block of statements which must be surrounded by LC..RC. */
617     void parseBlock(JSFunction b) throws IOException { parseBlock(b, null); }
618     void parseBlock(JSFunction b, String label) throws IOException {
619         int saveParserLine = parserLine;
620         _parseBlock(b, label);
621         parserLine = saveParserLine;
622     }
623     void _parseBlock(JSFunction b, String label) throws IOException {
624         if (peekToken() == -1) return;
625         else if (peekToken() != LC) parseStatement(b, null);
626         else {
627             consume(LC);
628             while(peekToken() != RC && peekToken() != -1) parseStatement(b, null);
629             consume(RC);
630         }
631     }
632
633     /** Parse a single statement, consuming the RC or SEMI which terminates it. */
634     void parseStatement(JSFunction b, String label) throws IOException {
635         int saveParserLine = parserLine;
636         _parseStatement(b, label);
637         parserLine = saveParserLine;
638     }
639     void _parseStatement(JSFunction b, String label) throws IOException {
640         int tok = peekToken();
641         if (tok == -1) return;
642         switch(tok = getToken()) {
643             
644         case THROW: case ASSERT: case RETURN: {
645             if (tok == RETURN && peekToken() == SEMI)
646                 b.add(parserLine, LITERAL, null);
647             else
648                 startExpr(b, -1);
649             b.add(parserLine, tok);
650             consume(SEMI);
651             break;
652         }
653         case BREAK: case CONTINUE: {
654             if (peekToken() == NAME) consume(NAME);
655             b.add(parserLine, tok, string);
656             consume(SEMI);
657             break;
658         }
659         case VAR: {
660             while(true) {
661                 consume(NAME);
662                 String var = string;
663                 scopeDeclare(var);
664                 if (peekToken() == ASSIGN) {                     // if there is an '=' after the variable name
665                     consume(ASSIGN);
666                     startExpr(b, NO_COMMA);
667                     b.add(parserLine, SCOPEPUT, scopeKey(var)); // assign it
668                     b.add(parserLine, POP);                      // clean the stack
669                 }
670                 if (peekToken() != COMMA) break;
671                 consume(COMMA);
672             }
673             if ((mostRecentlyReadToken != RC || peekToken() == SEMI) && peekToken() != -1 && mostRecentlyReadToken != SEMI) consume(SEMI);
674             break;
675         }
676         case IF: {
677             consume(LP);
678             startExpr(b, -1);
679             consume(RP);
680             
681             b.add(parserLine, JF, JSU.ZERO);                    // if false, jump to the else-block
682             int size = b.size;
683             parseStatement(b, null);
684             
685             if (peekToken() == ELSE) {
686                 consume(ELSE);
687                 b.add(parserLine, JMP, JSU.ZERO);               // if we took the true-block, jump over the else-block
688                 b.set(size - 1, JSU.N(b.size - size + 1));
689                 size = b.size;
690                 parseStatement(b, null);
691             }
692             b.set(size - 1, JSU.N(b.size - size + 1));        // regardless of which branch we took, b[size] needs to point here
693             break;
694         }
695         case WHILE: {
696             consume(LP);
697             if (label != null) b.add(parserLine, LABEL, label);
698             b.add(parserLine, LOOP);
699             int size = b.size;
700             b.add(parserLine, POP);                                   // discard the first-iteration indicator
701             startExpr(b, -1);
702             b.add(parserLine, JT, JSU.N(2));                    // if the while() clause is true, jump over the BREAK
703             b.add(parserLine, BREAK);
704             consume(RP);
705             parseStatement(b, null);
706             b.add(parserLine, CONTINUE);                              // if we fall out of the end, definately continue
707             b.set(size - 1, JSU.N(b.size - size + 1));        // end of the loop
708             break;
709         }
710         case SWITCH: {
711             consume(LP);
712             if (label != null) b.add(parserLine, LABEL, label);
713             b.add(parserLine, LOOP);
714             int size0 = b.size;
715             startExpr(b, -1);
716             consume(RP);
717             consume(LC);
718             while(true)
719                 if (peekToken() == CASE) {                         // we compile CASE statements like a bunch of if..else's
720                     consume(CASE);
721                     b.add(parserLine, DUP);                        // duplicate the switch() value; we'll consume one copy
722                     startExpr(b, -1);
723                     consume(COLON);
724                     b.add(parserLine, EQ);                         // check if we should do this case-block
725                     b.add(parserLine, JF, JSU.ZERO);         // if not, jump to the next one
726                     int size = b.size;
727                     while(peekToken() != CASE && peekToken() != DEFAULT && peekToken() != RC) parseStatement(b, null);
728                     b.set(size - 1, JSU.N(1 + b.size - size));
729                 } else if (peekToken() == DEFAULT) {
730                     consume(DEFAULT);
731                     consume(COLON);
732                     while(peekToken() != CASE && peekToken() != DEFAULT && peekToken() != RC) parseStatement(b, null);
733                 } else if (peekToken() == RC) {
734                     consume(RC);
735                     b.add(parserLine, BREAK);                      // break out of the loop if we 'fall through'
736                     break;
737                 } else {
738                     throw pe("expected CASE, DEFAULT, or RC; got " + codeToString[peekToken()]);
739                 }
740             b.set(size0 - 1, JSU.N(b.size - size0 + 1));      // end of the loop
741             break;
742         }
743             
744         case DO: {
745             if (label != null) b.add(parserLine, LABEL, label);
746             b.add(parserLine, LOOP);
747             int size = b.size;
748             parseStatement(b, null);
749             consume(WHILE);
750             consume(LP);
751             startExpr(b, -1);
752             b.add(parserLine, JT, JSU.N(2));                  // check the while() clause; jump over the BREAK if true
753             b.add(parserLine, BREAK);
754             b.add(parserLine, CONTINUE);
755             consume(RP);
756             consume(SEMI);
757             b.set(size - 1, JSU.N(b.size - size + 1));      // end of the loop; write this location to the LOOP instruction
758             break;
759         }
760             
761         case TRY: {
762             b.add(parserLine, TRY); // try bytecode causes a TryMarker to be pushed
763             int tryInsn = b.size - 1;
764             // parse the expression to be TRYed
765             parseStatement(b, null); 
766             // pop the try  marker. this is pushed when the TRY bytecode is executed                              
767             b.add(parserLine, POP);
768             // jump forward to the end of the catch block, start of the finally block                             
769             b.add(parserLine, JMP);                                  
770             int successJMPInsn = b.size - 1;
771             
772             if (peekToken() != CATCH && peekToken() != FINALLY)
773                 throw pe("try without catch or finally");
774             
775             int catchJMPDistance = -1;
776             if (peekToken() == CATCH) {
777                 Basket.List catchEnds = new Basket.Array();
778                 boolean catchAll = false;
779                 
780                 catchJMPDistance = b.size - tryInsn;
781                 
782                 while(peekToken() == CATCH && !catchAll) {
783                     String exceptionVar;
784                     getToken();
785                     consume(LP);
786                     consume(NAME);
787                     exceptionVar = string;
788                     int[] writebacks = new int[] { -1, -1, -1 };
789                     if (peekToken() != RP) {
790                         // extended Ibex catch block: catch(e faultCode "foo.bar.baz")
791                         consume(NAME);
792                         b.add(parserLine, DUP);
793                         b.add(parserLine, LITERAL, JSString.intern(string));
794                         b.add(parserLine, GET);
795                         b.add(parserLine, DUP);
796                         b.add(parserLine, LITERAL, null);
797                         b.add(parserLine, EQ);
798                         b.add(parserLine, JT);
799                         writebacks[0] = b.size - 1;
800                         if (peekToken() == STRING) {
801                             consume(STRING);
802                             b.add(parserLine, DUP);
803                             b.add(parserLine, LITERAL, string);
804                             b.add(parserLine, LT);
805                             b.add(parserLine, JT);
806                             writebacks[1] = b.size - 1;
807                             b.add(parserLine, DUP);
808                             b.add(parserLine, LITERAL, string + "/");   // (slash is ASCII after dot)
809                             b.add(parserLine, GE);
810                             b.add(parserLine, JT);
811                             writebacks[2] = b.size - 1;
812                         } else {
813                             consume(NUMBER);
814                             b.add(parserLine, DUP);
815                             b.add(parserLine, LITERAL, number);
816                             b.add(parserLine, EQ);
817                             b.add(parserLine, JF);
818                             writebacks[1] = b.size - 1;
819                         }
820                         b.add(parserLine, POP);  // pop the element thats on the stack from the compare
821                     } else {
822                         catchAll = true;
823                     }
824                     consume(RP);
825                     // the exception is on top of the stack; put it to the chosen name
826                     scopePush(b);
827                     scopeDeclare(exceptionVar);
828                     b.add(parserLine, SCOPEPUT, scopeKey(exceptionVar));
829                     b.add(parserLine, POP);
830                     parseBlock(b, null);
831                     scopePop(b);
832                     
833                     b.add(parserLine, JMP);
834                     catchEnds.add(new Integer(b.size-1));
835                     
836                     for(int i=0; i<3; i++) if (writebacks[i] != -1) b.set(writebacks[i], JSU.N(b.size-writebacks[i]));
837                     b.add(parserLine, POP); // pop the element thats on the stack from the compare
838                 }
839                 
840                 if(!catchAll)
841                     b.add(parserLine, THROW);
842                 
843                 for(int i=0;i<catchEnds.size();i++) {
844                     int n = ((Integer)catchEnds.get(i)).intValue();
845                     b.set(n, JSU.N(b.size-n));
846                 }
847                 
848                 // pop the try and catch markers
849                 b.add(parserLine,POP);
850                 b.add(parserLine,POP);
851             }
852                         
853             // jump here if no exception was thrown
854             b.set(successJMPInsn, JSU.N(b.size - successJMPInsn)); 
855                         
856             int finallyJMPDistance = -1;
857             if (peekToken() == FINALLY) {
858                 b.add(parserLine, LITERAL, null); // null FinallyData
859                 finallyJMPDistance = b.size - tryInsn;
860                 consume(FINALLY);
861                 parseStatement(b, null);
862                 b.add(parserLine,FINALLY_DONE); 
863             }
864             
865             // setup the TRY arguments
866             b.set(tryInsn, new int[] { catchJMPDistance, finallyJMPDistance });
867             
868             break;
869         }
870             
871         case FOR: {
872             consume(LP);
873             
874             tok = getToken();
875             boolean hadVar = false;                                      // if it's a for..in, we ignore the VAR
876             if (tok == VAR) { hadVar = true; tok = getToken(); }
877             String varName = string;
878             boolean forIn = peekToken() == IN;                           // determine if this is a for..in loop or not
879             pushBackToken(tok, varName);
880             
881             if (forIn) {
882                 consume(NAME);
883                 consume(IN);
884                 startExpr(b,-1);
885                 consume(RP);
886                 
887                 b.add(parserLine, PUSHKEYS);
888                 
889                 int size = b.size;
890                 b.add(parserLine, LOOP);
891                 b.add(parserLine, POP);
892                 
893                 b.add(parserLine,SWAP); // get the keys enumeration object on top
894                 b.add(parserLine,DUP);
895                 b.add(parserLine,GET,JSU.S("hasMoreElements"));
896                 int size2 = b.size;
897                 b.add(parserLine,JT);
898                 b.add(parserLine,SWAP);
899                 b.add(parserLine,BREAK);
900                 b.set(size2, JSU.N(b.size - size2));
901                 b.add(parserLine,DUP);
902                 b.add(parserLine,GET,JSU.S("nextElement"));
903
904                 scopePush(b);
905                 
906                 if(hadVar) scopeDeclare(varName);
907                 JS varKey = scopeKey(varName);
908                 
909                 if(varKey == null) {
910                     b.add(parserLine,GLOBALSCOPE);
911                     b.add(parserLine,SWAP);
912                     b.add(parserLine, LITERAL, JSString.intern(varName));
913                     b.add(parserLine,SWAP);
914                     b.add(parserLine,PUT);
915                     b.add(parserLine,POP);
916                 } else {
917                     b.add(parserLine, SCOPEPUT, varKey);
918                 }
919                 b.add(parserLine,POP);  // pop the put'ed value
920                 b.add(parserLine,SWAP); // put CallMarker back into place
921                 
922                 parseStatement(b, null);
923                 
924                 scopePop(b);
925                 b.add(parserLine, CONTINUE);
926                 // jump here on break
927                 b.set(size, JSU.N(b.size - size));
928                 
929                 b.add(parserLine, POP);
930             } else {
931                 if (hadVar) pushBackToken(VAR, null);                    // yeah, this actually matters
932                 scopePush(b);                             // grab a fresh scope
933                     
934                 parseStatement(b, null);                                 // initializer
935                 JSFunction e2 =                                    // we need to put the incrementor before the test
936                     new JSFunction(sourceName, parserLine, null);  // so we save the test here
937                 if (peekToken() != SEMI)
938                     startExpr(e2, -1);
939                 else
940                     e2.add(parserLine, JSFunction.LITERAL, JSU.T);         // handle the for(foo;;foo) case
941                 consume(SEMI);
942                 if (label != null) b.add(parserLine, LABEL, label);
943                 b.add(parserLine, LOOP);
944                 int size2 = b.size;
945                     
946                 b.add(parserLine, JT, JSU.ZERO);                   // if we're on the first iteration, jump over the incrementor
947                 int size = b.size;
948                 if (peekToken() != RP) {                                 // do the increment thing
949                     startExpr(b, -1);
950                     b.add(parserLine, POP);
951                 }
952                 b.set(size - 1, JSU.N(b.size - size + 1));
953                 consume(RP);
954                     
955                 b.paste(e2);                                             // ok, *now* test if we're done yet
956                 b.add(parserLine, JT, JSU.N(2));                   // break out if we don't meet the test
957                 b.add(parserLine, BREAK);
958                 parseStatement(b, null);
959                 b.add(parserLine, CONTINUE);                             // if we fall out the bottom, CONTINUE
960                 b.set(size2 - 1, JSU.N(b.size - size2 + 1));     // end of the loop
961                     
962                 scopePop(b);                            // get our scope back
963             }
964             break;
965         }
966                 
967         case NAME: {  // either a label or an identifier; this is the one place we're not LL(1)
968             String possiblyTheLabel = string;
969             if (peekToken() == COLON) {      // label
970                 consume(COLON);
971                 parseStatement(b, possiblyTheLabel);
972                 break;
973             } else {                         // expression
974                 pushBackToken(NAME, possiblyTheLabel);  
975                 startExpr(b, -1);
976                 b.add(parserLine, POP);
977                 if ((mostRecentlyReadToken != RC || peekToken() == SEMI) && peekToken() != -1 && mostRecentlyReadToken != SEMI) consume(SEMI);
978                 break;
979             }
980         }
981
982         case SEMI: return;                                               // yep, the null statement is valid
983
984         case LC: {  // blocks are statements too
985             pushBackToken();
986             scopePush(b);
987             parseBlock(b, label);
988             scopePop(b);
989             break;
990         }
991
992         default: {  // hope that it's an expression
993             pushBackToken();
994             startExpr(b, -1);
995             b.add(parserLine, POP);
996             if ((mostRecentlyReadToken != RC || peekToken() == SEMI) && peekToken() != -1 && mostRecentlyReadToken != SEMI) consume(SEMI);
997             break;
998         }
999         }
1000     }
1001
1002
1003     // ParserException //////////////////////////////////////////////////////////////////////
1004     private IOException pe(String s) { return new IOException(sourceName + ":" + line + " " + s); }
1005     
1006 }
1007