2003/11/03 06:36:13
[org.ibex.core.git] / src / org / xwt / js / Parser.java
1 // Copyright 2003 Adam Megacz, see the COPYING file for licensing [GPL]
2 package org.xwt.js;
3
4 import org.xwt.util.*;
5 import java.io.*;
6
7 /**
8  *  Parses a stream of lexed tokens into a tree of Function's.
9  *
10  *  There are three kinds of things we parse: blocks, statements, and
11  *  expressions.
12  *
13  *  - Expressions are a special type of statement that evaluates to a
14  *    value (for example, "break" is not an expression, * but "3+2"
15  *    is).  Some tokens sequences start expressions (for * example,
16  *    literal numbers) and others continue an expression which * has
17  *    already been begun (for example, '+').  Finally, some *
18  *    expressions are valid targets for an assignment operation; after
19  *    * each of these expressions, continueExprAfterAssignable() is
20  *    called * to check for an assignment operation.
21  *
22  *  - A statement ends with a semicolon and does not return a value.
23  *
24  *  - A block is a single statement or a sequence of statements
25  *    surrounded by curly braces.
26  *
27  *  Each parsing method saves the parserLine before doing its actual
28  *  work and restores it afterwards.  This ensures that parsing a
29  *  subexpression does not modify the line number until a token
30  *  *after* the subexpression has been consumed by the parent
31  *  expression.
32  *
33  *  Technically it would be a better design for this class to build an
34  *  intermediate parse tree and use that to emit bytecode.  Here's the
35  *  tradeoff:
36  *
37  *  Advantages of building a parse tree:
38  *  - easier to apply optimizations
39  *  - would let us handle more sophisticated languages than JavaScript
40  *
41  *  Advantages of leaving out the parse tree
42  *  - faster compilation
43  *  - less load on the garbage collector
44  *  - much simpler code, easier to understand
45  *  - less error-prone
46  *
47  *  Fortunately JS is such a simple language that we can get away with
48  *  the half-assed approach and still produce a working, complete
49  *  compiler.
50  *
51  *  The bytecode language emitted doesn't really cause any appreciable
52  *  semantic loss, and is itself a parseable language very similar to
53  *  Forth or a postfix variant of LISP.  This means that the bytecode
54  *  can be transformed into a parse tree, which can be manipulated.
55  *  So if we ever want to add an optimizer, it could easily be done by
56  *  producing a parse tree from the bytecode, optimizing that tree,
57  *  and then re-emitting the bytecode.  The parse tree node class
58  *  would also be much simpler since the bytecode language has so few
59  *  operators.
60  *
61  *  Actually, the above paragraph is slightly inaccurate -- there are
62  *  places where we push a value and then perform an arbitrary number
63  *  of operations using it before popping it; this doesn't parse well.
64  *  But these cases are clearly marked and easy to change if we do
65  *  need to move to a parse tree format.
66  */
67 class Parser extends Lexer implements ByteCodes {
68
69
70     // Constructors //////////////////////////////////////////////////////
71
72     public Parser(Reader r, String sourceName, int line) throws IOException { super(r, sourceName, line); }
73
74     /** for debugging */
75     public static void main(String[] s) throws Exception {
76         Function block = new Function("stdin", 0, new InputStreamReader(System.in), null);
77         if (block == null) return;
78         System.out.println(block);
79     }
80
81
82     // Statics ////////////////////////////////////////////////////////////
83
84     static byte[] precedence = new byte[MAX_TOKEN + 1];
85     static boolean[] isRightAssociative = new boolean[MAX_TOKEN + 1];
86     // Use this as the precedence when we want anything up to the comma
87     private final static int NO_COMMA = 2;
88     static {
89         isRightAssociative[ASSIGN] =
90             isRightAssociative[ASSIGN_BITOR] =
91             isRightAssociative[ASSIGN_BITXOR] =
92             isRightAssociative[ASSIGN_BITAND] =
93             isRightAssociative[ASSIGN_LSH] =
94             isRightAssociative[ASSIGN_RSH] =
95             isRightAssociative[ASSIGN_URSH] =
96             isRightAssociative[ASSIGN_ADD] =
97             isRightAssociative[ASSIGN_SUB] =
98             isRightAssociative[ASSIGN_MUL] =
99             isRightAssociative[ASSIGN_DIV] =
100             isRightAssociative[ASSIGN_MOD] = true;
101
102         precedence[COMMA] = 1;
103         // 2 is intentionally left unassigned. we use minPrecedence==2 for comma separated lists
104         precedence[ASSIGN] =
105             precedence[ASSIGN_BITOR] =
106             precedence[ASSIGN_BITXOR] =
107             precedence[ASSIGN_BITAND] =
108             precedence[ASSIGN_LSH] =
109             precedence[ASSIGN_RSH] =
110             precedence[ASSIGN_URSH] =
111             precedence[ASSIGN_ADD] =
112             precedence[ASSIGN_SUB] =
113             precedence[ASSIGN_MUL] =
114             precedence[ASSIGN_DIV] =
115             precedence[ASSIGN_MOD] = 3;
116         precedence[HOOK] = 4;
117         precedence[OR] = 5;
118         precedence[AND] = 6;
119         precedence[BITOR] = 7;
120         precedence[BITXOR] = 8;
121         precedence[BITAND] = 9;
122         precedence[EQ] = precedence[NE] = precedence[SHEQ] = precedence[SHNE] = 10;
123         precedence[LT] = precedence[LE] = precedence[GT] = precedence[GE] = 11;
124         precedence[LSH] = precedence[RSH] = precedence[URSH] = 12;
125         precedence[ADD] = precedence[SUB] = 12;
126         precedence[MUL] = precedence[DIV] = precedence[MOD] = 13;
127         precedence[BITNOT] =  precedence[BANG] = precedence[TYPEOF] = 14;
128         precedence[DOT] = precedence[LB] = precedence[LP] =  precedence[INC] = precedence[DEC] = 15;
129     }
130
131
132     // Parsing Logic /////////////////////////////////////////////////////////
133
134     /** gets a token and throws an exception if it is not <tt>code</tt> */
135     private void consume(int code) throws IOException {
136         if (getToken() != code) throw pe("expected " + codeToString[code] + ", got " + (op == -1 ? "EOF" : codeToString[op]));
137     }
138
139     /**
140      *  Parse the largest possible expression containing no operators
141      *  of precedence below <tt>minPrecedence</tt> and append the
142      *  bytecodes for that expression to <tt>appendTo</tt>; the
143      *  appended bytecodes MUST grow the stack by exactly one element.
144      */ 
145     private void startExpr(Function appendTo, int minPrecedence) throws IOException {
146         int saveParserLine = parserLine;
147         _startExpr(appendTo, minPrecedence);
148         parserLine = saveParserLine;
149     }
150     private void _startExpr(Function appendTo, int minPrecedence) throws IOException {
151         int tok = getToken();
152         Function b = appendTo;
153
154         switch (tok) {
155         case -1: throw pe("expected expression");
156
157         // all of these simply push values onto the stack
158         case NUMBER: b.add(parserLine, LITERAL, number); break;
159         case STRING: b.add(parserLine, LITERAL, string); break;
160         case NULL: b.add(parserLine, LITERAL, null); break;
161         case TRUE: case FALSE: b.add(parserLine, LITERAL, new Boolean(tok == TRUE)); break;
162
163         case LB: {
164             b.add(parserLine, ARRAY, new Integer(0));                       // push an array onto the stack
165             int size0 = b.size;
166             int i = 0;
167             if (peekToken() != RB)
168                 while(true) {                                               // iterate over the initialization values
169                     int size = b.size;
170                     b.add(parserLine, LITERAL, new Integer(i++));           // push the index in the array to place it into
171                     if (peekToken() == COMMA || peekToken() == RB)
172                         b.add(parserLine, LITERAL, null);                   // for stuff like [1,,2,]
173                     else
174                         startExpr(b, NO_COMMA);                             // push the value onto the stack
175                     b.add(parserLine, PUT);                                 // put it into the array
176                     b.add(parserLine, POP);                                 // discard the value remaining on the stack
177                     if (peekToken() == RB) break;
178                     consume(COMMA);
179                 }
180             b.set(size0 - 1, new Integer(i));                               // back at the ARRAY instruction, write the size of the array
181             consume(RB);
182             break;
183         }
184         case SUB: {  // negative literal (like "3 * -1")
185             consume(NUMBER);
186             b.add(parserLine, LITERAL, new Double(number.doubleValue() * -1));
187             break;
188         }
189         case LP: {  // grouping (not calling)
190             startExpr(b, -1);
191             consume(RP);
192             break;
193         }
194         case INC: case DEC: {  // prefix (not postfix)
195             startExpr(b, precedence[tok]);
196             int prev = b.size - 1;
197             if (b.get(prev) == GET && b.getArg(prev) != null)
198                 b.set(prev, LITERAL, b.getArg(prev));
199             else if(b.get(prev) == GET)
200                 b.pop();
201             else
202                 throw pe("prefixed increment/decrement can only be performed on a valid assignment target");
203             b.add(parserLine, tok, Boolean.TRUE);
204             break;
205         }
206         case BANG: case BITNOT: case TYPEOF: {
207             startExpr(b, precedence[tok]);
208             b.add(parserLine, tok);
209             break;
210         }
211         case LC: { // object constructor
212             b.add(parserLine, OBJECT, null);                                     // put an object on the stack
213             if (peekToken() != RC)
214                 while(true) {
215                     if (peekToken() != NAME && peekToken() != STRING)
216                         throw pe("expected NAME or STRING");
217                     getToken();
218                     b.add(parserLine, LITERAL, string);                          // grab the key
219                     consume(COLON);
220                     startExpr(b, NO_COMMA);                                      // grab the value
221                     b.add(parserLine, PUT);                                      // put the value into the object
222                     b.add(parserLine, POP);                                      // discard the remaining value
223                     if (peekToken() == RC) break;
224                     consume(COMMA);
225                     if (peekToken() == RC) break;                                // we permit {,,} -- I'm not sure if ECMA does
226                 }
227             consume(RC);
228             break;
229         }
230         case NAME: {
231             b.add(parserLine, TOPSCOPE);
232             b.add(parserLine, LITERAL, string);
233             continueExprAfterAssignable(b,minPrecedence);
234             break;
235         }
236         case FUNCTION: {
237             consume(LP);
238             int numArgs = 0;
239             Function b2 = new Function(sourceName, parserLine, null, null);
240             b.add(parserLine, NEWFUNCTION, b2);
241
242             // function prelude; arguments array is already on the stack
243             b2.add(parserLine, TOPSCOPE);
244             b2.add(parserLine, SWAP);
245             b2.add(parserLine, DECLARE, "arguments");                     // declare arguments (equivalent to 'var arguments;')
246             b2.add(parserLine, SWAP);                                     // set this.arguments and leave the value on the stack
247             b2.add(parserLine, PUT);
248
249             while(peekToken() != RP) {                                    // run through the list of argument names
250                 numArgs++;
251                 if (peekToken() == NAME) {
252                     consume(NAME);                                        // a named argument
253                     String varName = string;
254                     
255                     b2.add(parserLine, DUP);                              // dup the args array 
256                     b2.add(parserLine, GET, new Integer(numArgs - 1));   // retrieve it from the arguments array
257                     b2.add(parserLine, TOPSCOPE);
258                     b2.add(parserLine, SWAP);
259                     b2.add(parserLine, DECLARE, varName);                  // declare the name
260                     b2.add(parserLine, SWAP);
261                     b2.add(parserLine, PUT); 
262                     b2.add(parserLine, POP);                               // pop the value
263                     b2.add(parserLine, POP);                               // pop the scope                  
264                 }
265                 if (peekToken() == RP) break;
266                 consume(COMMA);
267             }
268             consume(RP);
269
270             b2.numFormalArgs = numArgs;
271             b2.add(parserLine, POP);                                      // pop off the arguments array
272             b2.add(parserLine, POP);                                      // pop off TOPSCOPE
273             
274            if(peekToken() != LC)
275                 throw pe("Functions must have a block surrounded by curly brackets");
276                 
277             parseBlock(b2, null);                                   // the function body
278
279             b2.add(parserLine, LITERAL, null);                        // in case we "fall out the bottom", return NULL
280             b2.add(parserLine, RETURN);
281
282             break;
283         }
284         default: throw pe("expected expression, found " + codeToString[tok] + ", which cannot start an expression");
285         }
286
287         // attempt to continue the expression
288         continueExpr(b, minPrecedence);
289     }
290
291
292     /**
293      *  Assuming that a complete assignable (lvalue) has just been
294      *  parsed and the object and key are on the stack,
295      *  <tt>continueExprAfterAssignable</tt> will attempt to parse an
296      *  expression that modifies the assignable.  This method always
297      *  decreases the stack depth by exactly one element.
298      */
299     private void continueExprAfterAssignable(Function b,int minPrecedence) throws IOException {
300         int saveParserLine = parserLine;
301         _continueExprAfterAssignable(b,minPrecedence);
302         parserLine = saveParserLine;
303     }
304     private void _continueExprAfterAssignable(Function b,int minPrecedence) throws IOException {
305         if (b == null) throw new Error("got null b; this should never happen");
306         int tok = getToken();
307         if (minPrecedence != -1 && (precedence[tok] < minPrecedence || (precedence[tok] == minPrecedence && !isRightAssociative[tok])))
308             // force the default case
309             tok = -1;
310         switch(tok) {
311         case ASSIGN_BITOR: case ASSIGN_BITXOR: case ASSIGN_BITAND: case ASSIGN_LSH: case ASSIGN_RSH: case ASSIGN_URSH:
312         case ASSIGN_MUL: case ASSIGN_DIV: case ASSIGN_MOD: case ASSIGN_ADD: case ASSIGN_SUB: {
313             b.add(parserLine, GET_PRESERVE);
314             startExpr(b,  precedence[tok]);
315             int size = b.size;
316             if (tok == ASSIGN_ADD || tok == ASSIGN_SUB) {
317                 b.add(parserLine, tok);
318             }
319             // tok-1 is always s/^ASSIGN_// (0 is BITOR, 1 is ASSIGN_BITOR, etc) 
320             b.add(parserLine, tok - 1, tok-1==ADD ? new Integer(2) : null);
321             b.add(parserLine, PUT);
322             b.add(parserLine, SWAP);
323             b.add(parserLine, POP);
324             if (tok == ASSIGN_ADD || tok == ASSIGN_SUB) b.set(size, tok, new Integer(b.size - size));
325             break;
326         }
327         case INC: case DEC: { // postfix
328             b.add(parserLine, tok, Boolean.FALSE);
329             break;
330         }
331         case ASSIGN: {
332             startExpr(b, precedence[tok]);
333             b.add(parserLine, PUT);
334             b.add(parserLine, SWAP);
335             b.add(parserLine, POP);
336             break;
337         }
338         case LP: {
339             int n = parseArgs(b);
340
341             // if the object supports GETCALL, we use this, and jump over the following two instructions
342             b.add(parserLine,CALLMETHOD,new Integer(n));
343             b.add(parserLine,GET);
344             b.add(parserLine,CALL_REVERSED,new Integer(n));
345             break;
346         }
347         default: {
348             pushBackToken();
349             if(b.get(b.size-1) == LITERAL && b.getArg(b.size-1) != null)
350                 b.set(b.size-1,GET,b.getArg(b.size-1));
351             else
352                 b.add(parserLine, GET);
353             return;
354         }
355         }
356     }
357
358
359     /**
360      *  Assuming that a complete expression has just been parsed,
361      *  <tt>continueExpr</tt> will attempt to extend this expression by
362      *  parsing additional tokens and appending additional bytecodes.
363      *
364      *  No operators with precedence less than <tt>minPrecedence</tt>
365      *  will be parsed.
366      *
367      *  If any bytecodes are appended, they will not alter the stack
368      *  depth.
369      */
370     private void continueExpr(Function b, int minPrecedence) throws IOException {
371         int saveParserLine = parserLine;
372         _continueExpr(b, minPrecedence);
373         parserLine = saveParserLine;
374     }
375     private void _continueExpr(Function b, int minPrecedence) throws IOException {
376         if (b == null) throw new Error("got null b; this should never happen");
377         int tok = getToken();
378         if (tok == -1) return;
379         if (minPrecedence != -1 && (precedence[tok] < minPrecedence || (precedence[tok] == minPrecedence && !isRightAssociative[tok]))) {
380             pushBackToken();
381             return;
382         }
383
384         switch (tok) {
385         case LP: {  // invocation (not grouping)
386             int n = parseArgs(b);
387             b.add(parserLine, CALL, new Integer(n));
388             break;
389         }
390         case BITOR: case BITXOR: case BITAND: case SHEQ: case SHNE: case LSH:
391         case RSH: case URSH: case MUL: case DIV: case MOD:
392         case GT: case GE: case EQ: case NE: case LT: case LE: case SUB: {
393             startExpr(b, precedence[tok]);
394             b.add(parserLine, tok);
395             break;
396         }
397         case ADD: {
398             int count=1;
399             int nextTok;
400             do {
401                 startExpr(b,precedence[tok]);
402                 count++;
403                 nextTok = getToken();
404             } while(nextTok == tok);
405             pushBackToken();
406             b.add(parserLine, tok, new Integer(count));
407             break;
408         }
409         case OR: case AND: {
410             b.add(parserLine, tok == AND ? b.JF : b.JT, new Integer(0));       // test to see if we can short-circuit
411             int size = b.size;
412             startExpr(b, precedence[tok]);                                     // otherwise check the second value
413             b.add(parserLine, JMP, new Integer(2));                            // leave the second value on the stack and jump to the end
414             b.add(parserLine, LITERAL, tok == AND ?
415                   new Boolean(false) : new Boolean(true));                     // target of the short-circuit jump is here
416             b.set(size - 1, new Integer(b.size - size));                     // write the target of the short-circuit jump
417             break;
418         }
419         case DOT: {
420             // support foo..bar syntax for foo[""].bar
421             if (peekToken() == DOT) {
422                 string = "";
423             } else {
424                 consume(NAME);
425             }
426             b.add(parserLine, LITERAL, string);
427             continueExprAfterAssignable(b,minPrecedence);
428             break;
429         }
430         case LB: { // subscripting (not array constructor)
431             startExpr(b, -1);
432             consume(RB);
433             continueExprAfterAssignable(b,minPrecedence);
434             break;
435         }
436         case HOOK: {
437             b.add(parserLine, JF, new Integer(0));                // jump to the if-false expression
438             int size = b.size;
439             startExpr(b, minPrecedence);                          // write the if-true expression
440             b.add(parserLine, JMP, new Integer(0));               // if true, jump *over* the if-false expression     
441             b.set(size - 1, new Integer(b.size - size + 1));    // now we know where the target of the jump is
442             consume(COLON);
443             size = b.size;
444             startExpr(b, minPrecedence);                          // write the if-false expression
445             b.set(size - 1, new Integer(b.size - size + 1));    // this is the end; jump to here
446             break;
447         }
448         case COMMA: {
449             // pop the result of the previous expression, it is ignored
450             b.add(parserLine,POP);
451             startExpr(b,-1);
452             break;
453         }
454         default: {
455             pushBackToken();
456             return;
457         }
458         }
459
460         continueExpr(b, minPrecedence);                           // try to continue the expression
461     }
462     
463     // parse a set of comma separated function arguments, assume LP has already been consumed
464     private int parseArgs(Function b) throws IOException {
465         int i = 0;
466         while(peekToken() != RP) {
467             i++;
468             if (peekToken() != COMMA) {
469                 startExpr(b, NO_COMMA);
470                 if (peekToken() == RP) break;
471             }
472             consume(COMMA);
473         }
474         consume(RP);
475         return i;
476     }
477     
478     /** Parse a block of statements which must be surrounded by LC..RC. */
479     void parseBlock(Function b) throws IOException { parseBlock(b, null); }
480     void parseBlock(Function b, String label) throws IOException {
481         int saveParserLine = parserLine;
482         _parseBlock(b, label);
483         parserLine = saveParserLine;
484     }
485     void _parseBlock(Function b, String label) throws IOException {
486         if (peekToken() == -1) return;
487         else if (peekToken() != LC) parseStatement(b, null);
488         else {
489             consume(LC);
490             while(peekToken() != RC && peekToken() != -1) parseStatement(b, null);
491             consume(RC);
492         }
493     }
494
495     /** Parse a single statement, consuming the RC or SEMI which terminates it. */
496     void parseStatement(Function b, String label) throws IOException {
497         int saveParserLine = parserLine;
498         _parseStatement(b, label);
499         parserLine = saveParserLine;
500     }
501     void _parseStatement(Function b, String label) throws IOException {
502         int tok = peekToken();
503         if (tok == -1) return;
504         switch(tok = getToken()) {
505             
506         case THROW: case ASSERT: case RETURN: {
507             if (tok == RETURN && peekToken() == SEMI)
508                 b.add(parserLine, LITERAL, null);
509             else
510                 startExpr(b, -1);
511             b.add(parserLine, tok);
512             consume(SEMI);
513             break;
514         }
515         case BREAK: case CONTINUE: {
516             if (peekToken() == NAME) consume(NAME);
517             b.add(parserLine, tok, string);
518             consume(SEMI);
519             break;
520         }
521         case VAR: {
522             b.add(parserLine, TOPSCOPE);                         // push the current scope
523             while(true) {
524                 consume(NAME);
525                 b.add(parserLine, DECLARE, string);               // declare it
526                 if (peekToken() == ASSIGN) {                     // if there is an '=' after the variable name
527                     consume(ASSIGN);
528                     startExpr(b, NO_COMMA);
529                     b.add(parserLine, PUT);                      // assign it
530                     b.add(parserLine, POP);                      // clean the stack
531                 } else {
532                     b.add(parserLine, POP);                      // pop the string pushed by declare
533                 }   
534                 if (peekToken() != COMMA) break;
535                 consume(COMMA);
536             }
537             b.add(parserLine, POP);                              // pop off the topscope
538             if ((mostRecentlyReadToken != RC || peekToken() == SEMI) && peekToken() != -1 && mostRecentlyReadToken != SEMI) consume(SEMI);
539             break;
540         }
541         case IF: {
542             consume(LP);
543             startExpr(b, -1);
544             consume(RP);
545             
546             b.add(parserLine, JF, new Integer(0));                    // if false, jump to the else-block
547             int size = b.size;
548             parseStatement(b, null);
549             
550             if (peekToken() == ELSE) {
551                 consume(ELSE);
552                 b.add(parserLine, JMP, new Integer(0));               // if we took the true-block, jump over the else-block
553                 b.set(size - 1, new Integer(b.size - size + 1));
554                 size = b.size;
555                 parseStatement(b, null);
556             }
557             b.set(size - 1, new Integer(b.size - size + 1));        // regardless of which branch we took, b[size] needs to point here
558             break;
559         }
560         case WHILE: {
561             consume(LP);
562             if (label != null) b.add(parserLine, LABEL, label);
563             b.add(parserLine, LOOP);
564             int size = b.size;
565             b.add(parserLine, POP);                                   // discard the first-iteration indicator
566             startExpr(b, -1);
567             b.add(parserLine, JT, new Integer(2));                    // if the while() clause is true, jump over the BREAK
568             b.add(parserLine, BREAK);
569             consume(RP);
570             parseStatement(b, null);
571             b.add(parserLine, CONTINUE);                              // if we fall out of the end, definately continue
572             b.set(size - 1, new Integer(b.size - size + 1));        // end of the loop
573             break;
574         }
575         case SWITCH: {
576             consume(LP);
577             if (label != null) b.add(parserLine, LABEL, label);
578             b.add(parserLine, LOOP);
579             int size0 = b.size;
580             startExpr(b, -1);
581             consume(RP);
582             consume(LC);
583             while(true)
584                 if (peekToken() == CASE) {                         // we compile CASE statements like a bunch of if..else's
585                     consume(CASE);
586                     b.add(parserLine, DUP);                        // duplicate the switch() value; we'll consume one copy
587                     startExpr(b, -1);
588                     consume(COLON);
589                     b.add(parserLine, EQ);                         // check if we should do this case-block
590                     b.add(parserLine, JF, new Integer(0));         // if not, jump to the next one
591                     int size = b.size;
592                     while(peekToken() != CASE && peekToken() != DEFAULT && peekToken() != RC) parseStatement(b, null);
593                     b.set(size - 1, new Integer(1 + b.size - size));
594                 } else if (peekToken() == DEFAULT) {
595                     consume(DEFAULT);
596                     consume(COLON);
597                     while(peekToken() != CASE && peekToken() != DEFAULT && peekToken() != RC) parseStatement(b, null);
598                 } else if (peekToken() == RC) {
599                     consume(RC);
600                     b.add(parserLine, BREAK);                      // break out of the loop if we 'fall through'
601                     break;
602                 } else {
603                     throw pe("expected CASE, DEFAULT, or RC; got " + codeToString[peekToken()]);
604                 }
605             b.set(size0 - 1, new Integer(b.size - size0 + 1));      // end of the loop
606             break;
607         }
608             
609         case DO: {
610             if (label != null) b.add(parserLine, LABEL, label);
611             b.add(parserLine, LOOP);
612             int size = b.size;
613             parseStatement(b, null);
614             consume(WHILE);
615             consume(LP);
616             startExpr(b, -1);
617             b.add(parserLine, JT, new Integer(2));                  // check the while() clause; jump over the BREAK if true
618             b.add(parserLine, BREAK);
619             b.add(parserLine, CONTINUE);
620             consume(RP);
621             consume(SEMI);
622             b.set(size - 1, new Integer(b.size - size + 1));      // end of the loop; write this location to the LOOP instruction
623             break;
624         }
625             
626         case TRY: {
627             b.add(parserLine, TRY); // try bytecode causes a TryMarker to be pushed
628             int tryInsn = b.size - 1;
629             // parse the expression to be TRYed
630             parseStatement(b, null); 
631             // pop the try  marker. this is pushed when the TRY bytecode is executed                              
632             b.add(parserLine, POP);
633             // jump forward to the end of the catch block, start of the finally block                             
634             b.add(parserLine, JMP);                                  
635             int successJMPInsn = b.size - 1;
636             
637             if (peekToken() != CATCH && peekToken() != FINALLY)
638                 throw pe("try without catch or finally");
639             
640             int catchJMPDistance = -1;
641             if (peekToken() == CATCH) {
642                 catchJMPDistance = b.size - tryInsn;
643                 String exceptionVar;
644                 getToken();
645                 consume(LP);
646                 consume(NAME);
647                 exceptionVar = string;
648                 consume(RP);
649                 b.add(parserLine, TOPSCOPE);                        // the exception is on top of the stack; put it to the chosen name
650                 b.add(parserLine, SWAP);
651                 b.add(parserLine, LITERAL,exceptionVar);
652                 b.add(parserLine, SWAP);
653                 b.add(parserLine, PUT);
654                 b.add(parserLine, POP);
655                 b.add(parserLine, POP);
656                 parseStatement(b, null);
657                 // pop the try and catch markers
658                 b.add(parserLine,POP);
659                 b.add(parserLine,POP);
660             }
661             
662             // jump here if no exception was thrown
663             b.set(successJMPInsn, new Integer(b.size - successJMPInsn)); 
664                         
665             int finallyJMPDistance = -1;
666             if (peekToken() == FINALLY) {
667                 b.add(parserLine, LITERAL, null); // null FinallyData
668                 finallyJMPDistance = b.size - tryInsn;
669                 consume(FINALLY);
670                 parseStatement(b, null);
671                 b.add(parserLine,FINALLY_DONE); 
672             }
673             
674             // setup the TRY arguments
675             b.set(tryInsn, new int[] { catchJMPDistance, finallyJMPDistance });
676             
677             break;
678         }
679             
680         case FOR: {
681             consume(LP);
682             
683             tok = getToken();
684             boolean hadVar = false;                                      // if it's a for..in, we ignore the VAR
685             if (tok == VAR) { hadVar = true; tok = getToken(); }
686             String varName = string;
687             boolean forIn = peekToken() == IN;                           // determine if this is a for..in loop or not
688             pushBackToken(tok, varName);
689             
690             if (forIn) {
691                 b.add(parserLine, NEWSCOPE);                             // for-loops always create new scopes
692                 b.add(parserLine, LITERAL, varName);                     // declare the new variable
693                 b.add(parserLine, DECLARE);
694                     
695                 b.add(parserLine, LOOP);                                 // we actually only add this to ensure that BREAK works
696                 b.add(parserLine, POP);                                  // discard the first-iteration indicator
697                 int size = b.size;
698                 consume(NAME);
699                 consume(IN);
700                 startExpr(b, -1);
701                 b.add(parserLine, PUSHKEYS);                             // push the keys as an array; check the length
702                 b.add(parserLine, LITERAL, "length");
703                 b.add(parserLine, GET);
704                 consume(RP);
705                     
706                 b.add(parserLine, LITERAL, new Integer(1));              // decrement the length
707                 b.add(parserLine, SUB);
708                 b.add(parserLine, DUP);
709                 b.add(parserLine, LITERAL, new Integer(0));              // see if we've exhausted all the elements
710                 b.add(parserLine, LT);
711                 b.add(parserLine, JF, new Integer(2));
712                 b.add(parserLine, BREAK);                                // if we have, then BREAK
713                 b.add(parserLine, GET_PRESERVE);                         // get the key out of the keys array
714                 b.add(parserLine, LITERAL, varName);
715                 b.add(parserLine, PUT);                                  // write it to this[varName]                          
716                 parseStatement(b, null);                                 // do some stuff
717                 b.add(parserLine, CONTINUE);                             // continue if we fall out the bottom
718
719                 b.set(size - 1, new Integer(b.size - size + 1));       // BREAK to here
720                 b.add(parserLine, OLDSCOPE);                             // restore the scope
721                     
722             } else {
723                 if (hadVar) pushBackToken(VAR, null);                    // yeah, this actually matters
724                 b.add(parserLine, NEWSCOPE);                             // grab a fresh scope
725                     
726                 parseStatement(b, null);                                 // initializer
727                 Function e2 =                                    // we need to put the incrementor before the test
728                     new Function(sourceName, parserLine, null, null);  // so we save the test here
729                 if (peekToken() != SEMI)
730                     startExpr(e2, -1);
731                 else
732                     e2.add(parserLine, b.LITERAL, Boolean.TRUE);         // handle the for(foo;;foo) case
733                 consume(SEMI);
734                 if (label != null) b.add(parserLine, LABEL, label);
735                 b.add(parserLine, LOOP);
736                 int size2 = b.size;
737                     
738                 b.add(parserLine, JT, new Integer(0));                   // if we're on the first iteration, jump over the incrementor
739                 int size = b.size;
740                 if (peekToken() != RP) {                                 // do the increment thing
741                     startExpr(b, -1);
742                     b.add(parserLine, POP);
743                 }
744                 b.set(size - 1, new Integer(b.size - size + 1));
745                 consume(RP);
746                     
747                 b.paste(e2);                                             // ok, *now* test if we're done yet
748                 b.add(parserLine, JT, new Integer(2));                   // break out if we don't meet the test
749                 b.add(parserLine, BREAK);
750                 parseStatement(b, null);
751                 b.add(parserLine, CONTINUE);                             // if we fall out the bottom, CONTINUE
752                 b.set(size2 - 1, new Integer(b.size - size2 + 1));     // end of the loop
753                     
754                 b.add(parserLine, OLDSCOPE);                             // get our scope back
755             }
756             break;
757         }
758                 
759         case NAME: {  // either a label or an identifier; this is the one place we're not LL(1)
760             String possiblyTheLabel = string;
761             if (peekToken() == COLON) {      // label
762                 consume(COLON);
763                 parseStatement(b, possiblyTheLabel);
764                 break;
765             } else {                         // expression
766                 pushBackToken(NAME, possiblyTheLabel);  
767                 startExpr(b, -1);
768                 b.add(parserLine, POP);
769                 if ((mostRecentlyReadToken != RC || peekToken() == SEMI) && peekToken() != -1 && mostRecentlyReadToken != SEMI) consume(SEMI);
770                 break;
771             }
772         }
773
774         case SEMI: return;                                               // yep, the null statement is valid
775
776         case LC: {  // blocks are statements too
777             pushBackToken();
778             b.add(parserLine, NEWSCOPE);
779             parseBlock(b, label);
780             b.add(parserLine, OLDSCOPE);
781             break;
782         }
783
784         default: {  // hope that it's an expression
785             pushBackToken();
786             startExpr(b, -1);
787             b.add(parserLine, POP);
788             if ((mostRecentlyReadToken != RC || peekToken() == SEMI) && peekToken() != -1 && mostRecentlyReadToken != SEMI) consume(SEMI);
789             break;
790         }
791         }
792     }
793
794
795     // ParserException //////////////////////////////////////////////////////////////////////
796     private IOException pe(String s) { return new IOException(sourceName + ":" + parserLine + " " + s); }
797     
798 }
799