2003/07/06 13:42:15
[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 CompiledFunctionImpl'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         CompiledFunctionImpl block = new JS.CompiledFunction("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     static {
87         isRightAssociative[ASSIGN] =
88             isRightAssociative[ASSIGN_BITOR] =
89             isRightAssociative[ASSIGN_BITXOR] =
90             isRightAssociative[ASSIGN_BITAND] =
91             isRightAssociative[ASSIGN_LSH] =
92             isRightAssociative[ASSIGN_RSH] =
93             isRightAssociative[ASSIGN_URSH] =
94             isRightAssociative[ASSIGN_ADD] =
95             isRightAssociative[ASSIGN_SUB] =
96             isRightAssociative[ASSIGN_MUL] =
97             isRightAssociative[ASSIGN_DIV] =
98             isRightAssociative[ASSIGN_MOD] = true;
99
100         precedence[ASSIGN] =
101             precedence[ASSIGN_BITOR] =
102             precedence[ASSIGN_BITXOR] =
103             precedence[ASSIGN_BITAND] =
104             precedence[ASSIGN_LSH] =
105             precedence[ASSIGN_RSH] =
106             precedence[ASSIGN_URSH] =
107             precedence[ASSIGN_ADD] =
108             precedence[ASSIGN_SUB] =
109             precedence[ASSIGN_MUL] =
110             precedence[ASSIGN_DIV] =
111             precedence[ASSIGN_MOD] = 1;
112         precedence[HOOK] = 2;
113         precedence[COMMA] = 3;
114         precedence[OR] = precedence[AND] = precedence[BANG] = 4;
115         precedence[GT] = precedence[GE] = 5;
116         precedence[BITOR] = 6;
117         precedence[BITXOR] = 7;
118         precedence[BITAND] = 8;
119         precedence[EQ] = precedence[NE] = 9;
120         precedence[LT] = precedence[LE] = precedence[TYPEOF] = 10;
121         precedence[SHEQ] = precedence[SHNE] = 11;
122         precedence[LSH] = precedence[RSH] = precedence[URSH] = 12;
123         precedence[ADD] = precedence[SUB] = 13;
124         precedence[MUL] = precedence[DIV] = precedence[MOD] = 14;
125         precedence[BITNOT] =  15;
126         precedence[INC] = precedence[DEC] = 16;
127         precedence[LP] = 17;
128         precedence[DOT] = precedence[LB] = 18;
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(CompiledFunctionImpl appendTo, int minPrecedence) throws IOException {
146         int saveParserLine = parserLine;
147         _startExpr(appendTo, minPrecedence);
148         parserLine = saveParserLine;
149     }
150     private void _startExpr(CompiledFunctionImpl appendTo, int minPrecedence) throws IOException {
151         int tok = getToken();
152         CompiledFunctionImpl 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 THIS: b.add(parserLine, TOPSCOPE, null); break;
161         case NULL: b.add(parserLine, LITERAL, null); break;
162         case TRUE: case FALSE: b.add(parserLine, LITERAL, new Boolean(tok == TRUE)); break;
163
164         case LB: {
165             b.add(parserLine, ARRAY, new Integer(0));                       // push an array onto the stack
166             int size0 = b.size();
167             int i = 0;
168             if (peekToken() != RB)
169                 while(true) {                                               // iterate over the initialization values
170                     int size = b.size();
171                     b.add(parserLine, LITERAL, new Integer(i++));           // push the index in the array to place it into
172                     if (peekToken() == COMMA || peekToken() == RB)
173                         b.add(parserLine, LITERAL, null);                   // for stuff like [1,,2,]
174                     else
175                         startExpr(b, -1);                                   // push the value onto the stack
176                     b.add(parserLine, PUT);                                 // put it into the array
177                     b.add(parserLine, POP);                                 // discard the value remaining on the stack
178                     if (peekToken() == RB) break;
179                     consume(COMMA);
180                 }
181             b.set(size0 - 1, new Integer(i));                               // back at the ARRAY instruction, write the size of the array
182             consume(RB);
183             break;
184         }
185         case SUB: {  // negative literal (like "3 * -1")
186             consume(NUMBER);
187             b.add(parserLine, LITERAL, new Double(number.doubleValue() * -1));
188             break;
189         }
190         case LP: {  // grouping (not calling)
191             startExpr(b, -1);
192             consume(RP);
193             break;
194         }
195         case INC: case DEC: {  // prefix (not postfix)
196             startExpr(b, precedence[tok]);
197             if (b.get(b.size() - 1) != GET)
198                 throw pe("prefixed increment/decrement can only be performed on a valid assignment target");
199             b.set(b.size() - 1, tok, new Boolean(true));
200             break;
201         }
202         case BANG: case BITNOT: case TYPEOF: {
203             startExpr(b, precedence[tok]);
204             b.add(parserLine, tok);
205             break;
206         }
207         case LC: { // object constructor
208             b.add(parserLine, OBJECT, null);                                     // put an object on the stack
209             if (peekToken() != RC)
210                 while(true) {
211                     if (peekToken() != NAME && peekToken() != STRING)
212                         throw pe("expected NAME or STRING");
213                     getToken();
214                     b.add(parserLine, LITERAL, string);                          // grab the key
215                     consume(COLON);
216                     startExpr(b, -1);                                            // grab the value
217                     b.add(parserLine, PUT);                                      // put the value into the object
218                     b.add(parserLine, POP);                                      // discard the remaining value
219                     if (peekToken() == RC) break;
220                     consume(COMMA);
221                     if (peekToken() == RC) break;                                // we permit {,,} -- I'm not sure if ECMA does
222                 }
223             consume(RC);
224             break;
225         }
226         case NAME: {
227             b.add(parserLine, TOPSCOPE);
228             b.add(parserLine, LITERAL, string);
229             continueExprAfterAssignable(b);
230             break;
231         }
232         case FUNCTION: {
233             consume(LP);
234             int numArgs = 0;
235             CompiledFunctionImpl b2 = new JS.CompiledFunction(sourceName, parserLine, null, null);
236             b.add(parserLine, NEWFUNCTION, b2);
237
238             // function prelude; arguments array is already on the stack
239             b2.add(parserLine, TOPSCOPE);                                                // push the scope onto the stack
240             b2.add(parserLine, SWAP);                                                    // swap 'this' and 'arguments'
241
242             b2.add(parserLine, LITERAL, "arguments");                                    // declare arguments (equivalent to 'var arguments;')
243             b2.add(parserLine, DECLARE);
244
245             b2.add(parserLine, LITERAL, "arguments");                                    // set this.arguments and leave the value on the stack
246             b2.add(parserLine, SWAP);
247             b2.add(parserLine, PUT);
248             b2.add(parserLine, SWAP);
249             b2.add(parserLine, POP);
250
251             while(peekToken() != RP) {                                    // run through the list of argument names
252                 if (peekToken() == NAME) {
253                     consume(NAME);                                        // a named argument
254                     
255                     b2.add(parserLine, LITERAL, string);                  // declare the name
256                     b2.add(parserLine, DECLARE);
257                     
258                     b2.add(parserLine, LITERAL, new Integer(numArgs));    // retrieve it from the arguments array
259                     b2.add(parserLine, GET_PRESERVE);
260                     b2.add(parserLine, SWAP);
261                     b2.add(parserLine, POP);
262                     
263                     b2.add(parserLine, TOPSCOPE);                         // put it to the current scope
264                     b2.add(parserLine, SWAP);
265                     b2.add(parserLine, LITERAL, string);
266                     b2.add(parserLine, SWAP);
267                     b2.add(parserLine, PUT);
268                     
269                     b2.add(parserLine, POP);                              // clean the stack
270                     b2.add(parserLine, POP);
271                 }
272                 if (peekToken() == RP) break;
273                 consume(COMMA);
274                 numArgs++;
275             }
276             consume(RP);
277
278             b2.add(parserLine, POP);                                      // pop off the arguments array
279
280             parseStatement(b2, null);                                     // the function body
281
282             b2.add(parserLine, LITERAL, null);                            // in case we "fall out the bottom", return NULL
283             b2.add(parserLine, RETURN);
284
285             break;
286         }
287         default: throw pe("expected expression, found " + codeToString[tok] + ", which cannot start an expression");
288         }
289
290         // attempt to continue the expression
291         continueExpr(b, minPrecedence);
292     }
293
294
295     /**
296      *  Assuming that a complete assignable (lvalue) has just been
297      *  parsed and the object and key are on the stack,
298      *  <tt>continueExprAfterAssignable</tt> will attempt to parse an
299      *  expression that modifies the assignable.  This method always
300      *  decreases the stack depth by exactly one element.
301      */
302     private void continueExprAfterAssignable(CompiledFunctionImpl b) throws IOException {
303         int saveParserLine = parserLine;
304         _continueExprAfterAssignable(b);
305         parserLine = saveParserLine;
306     }
307     private void _continueExprAfterAssignable(CompiledFunctionImpl b) throws IOException {
308         if (b == null) throw new Error("got null b; this should never happen");
309         int tok = getToken();
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_ADD: case ASSIGN_SUB: case ASSIGN_MUL: case ASSIGN_DIV: case ASSIGN_MOD: {
313             b.add(parserLine, GET_PRESERVE);
314             startExpr(b, -1);
315             b.add(parserLine, tok - 1);
316             b.add(parserLine, PUT);
317             b.add(parserLine, SWAP);
318             b.add(parserLine, POP);
319             break;
320         }
321         case INC: case DEC: { // postfix
322             b.add(parserLine, GET_PRESERVE);
323             b.add(parserLine, LITERAL, new Integer(1));
324             b.add(parserLine, tok == INC ? ADD : SUB);
325             b.add(parserLine, PUT);
326             b.add(parserLine, SWAP);
327             b.add(parserLine, POP);
328             b.add(parserLine, LITERAL, new Integer(1));
329             b.add(parserLine, tok == INC ? SUB : ADD);
330             break;
331         }
332         case ASSIGN: {
333             startExpr(b, -1);
334             b.add(parserLine, PUT);
335             b.add(parserLine, SWAP);
336             b.add(parserLine, POP);
337             break;
338         }
339         case LP: {
340             int n = parseArgs(b);
341             b.add(parserLine,CALLMETHOD,new Integer(n));
342             break;
343         }
344         default: {
345             pushBackToken();
346             b.add(parserLine, GET);
347             return;
348         }
349         }
350     }
351
352
353     /**
354      *  Assuming that a complete expression has just been parsed,
355      *  <tt>continueExpr</tt> will attempt to extend this expression by
356      *  parsing additional tokens and appending additional bytecodes.
357      *
358      *  No operators with precedence less than <tt>minPrecedence</tt>
359      *  will be parsed.
360      *
361      *  If any bytecodes are appended, they will not alter the stack
362      *  depth.
363      */
364     private void continueExpr(CompiledFunctionImpl b, int minPrecedence) throws IOException {
365         int saveParserLine = parserLine;
366         _continueExpr(b, minPrecedence);
367         parserLine = saveParserLine;
368     }
369     private void _continueExpr(CompiledFunctionImpl b, int minPrecedence) throws IOException {
370         if (b == null) throw new Error("got null b; this should never happen");
371         int tok = getToken();
372         if (tok == -1) return;
373         if (minPrecedence != -1 && (precedence[tok] < minPrecedence || (precedence[tok] == minPrecedence && !isRightAssociative[tok]))) {
374             pushBackToken();
375             return;
376         }
377
378         switch (tok) {
379         case LP: {  // invocation (not grouping)
380             int n = parseArgs(b);
381             b.add(parserLine, CALL, new Integer(n));
382             break;
383         }
384         case BITOR: case BITXOR: case BITAND: case SHEQ: case SHNE: case LSH:
385         case RSH: case URSH: case ADD: case MUL: case DIV: case MOD:
386         case GT: case GE: case EQ: case NE: case LT: case LE: case SUB: {
387             startExpr(b, precedence[tok]);
388             b.add(parserLine, tok);
389             break;
390         }
391         case OR: case AND: {
392             b.add(parserLine, tok == AND ? b.JF : b.JT, new Integer(0));       // test to see if we can short-circuit
393             int size = b.size();
394             startExpr(b, precedence[tok]);                                     // otherwise check the second value
395             b.add(parserLine, JMP, new Integer(2));                            // leave the second value on the stack and jump to the end
396             b.add(parserLine, LITERAL, tok == AND ?
397                   new Boolean(false) : new Boolean(true));                     // target of the short-circuit jump is here
398             b.set(size - 1, new Integer(b.size() - size));                     // write the target of the short-circuit jump
399             break;
400         }
401         case DOT: {
402             consume(NAME);
403             b.add(parserLine, LITERAL, string);
404             continueExprAfterAssignable(b);
405             break;
406         }
407         case LB: { // subscripting (not array constructor)
408             startExpr(b, -1);
409             consume(RB);
410             continueExprAfterAssignable(b);
411             break;
412         }
413         case HOOK: {
414             b.add(parserLine, JF, new Integer(0));                // jump to the if-false expression
415             int size = b.size();
416             startExpr(b, -1);                                     // write the if-true expression
417             b.add(parserLine, JMP, new Integer(0));               // if true, jump *over* the if-false expression     
418             b.set(size - 1, new Integer(b.size() - size + 1));    // now we know where the target of the jump is
419             consume(COLON);
420             size = b.size();
421             startExpr(b, -1);                                     // write the if-false expression
422             b.set(size - 1, new Integer(b.size() - size + 1));    // this is the end; jump to here
423             break;
424         }
425         default: {
426             pushBackToken();
427             return;
428         }
429         }
430
431         continueExpr(b, minPrecedence);                           // try to continue the expression
432     }
433     
434     // parse a set of comma separated function arguments, assume LP has already been consumed
435     private int parseArgs(CompiledFunctionImpl b) throws IOException {
436         int i = 0;
437         while(peekToken() != RP) {
438             i++;
439             if (peekToken() != COMMA) {
440                 startExpr(b, -1);
441                 if (peekToken() == RP) break;
442             }
443             consume(COMMA);
444         }
445         consume(RP);
446         return i;
447     }
448     
449     /** Parse a block of statements which must be surrounded by LC..RC. */
450     void parseBlock(CompiledFunctionImpl b) throws IOException { parseBlock(b, null); }
451     void parseBlock(CompiledFunctionImpl b, String label) throws IOException {
452         int saveParserLine = parserLine;
453         _parseBlock(b, label);
454         parserLine = saveParserLine;
455     }
456     void _parseBlock(CompiledFunctionImpl b, String label) throws IOException {
457         if (peekToken() == -1) return;
458         else if (peekToken() != LC) parseStatement(b, null);
459         else {
460             consume(LC);
461             while(peekToken() != RC && peekToken() != -1) parseStatement(b, null);
462             consume(RC);
463         }
464     }
465
466     /** Parse a single statement, consuming the RC or SEMI which terminates it. */
467     void parseStatement(CompiledFunctionImpl b, String label) throws IOException {
468         int saveParserLine = parserLine;
469         _parseStatement(b, label);
470         parserLine = saveParserLine;
471     }
472     void _parseStatement(CompiledFunctionImpl b, String label) throws IOException {
473         int tok = peekToken();
474         if (tok == -1) return;
475         switch(tok = getToken()) {
476             
477         case THROW: case ASSERT: case RETURN: {
478             if (tok == RETURN && peekToken() == SEMI)
479                 b.add(parserLine, LITERAL, null);
480             else
481                 startExpr(b, -1);
482             b.add(parserLine, tok);
483             consume(SEMI);
484             break;
485         }
486         case BREAK: case CONTINUE: {
487             if (peekToken() == NAME) consume(NAME);
488             b.add(parserLine, tok, string);
489             consume(SEMI);
490             break;
491         }
492         case VAR: {
493             b.add(parserLine, TOPSCOPE);                         // push the current scope
494             while(true) {
495                 consume(NAME);
496                 String name = string;
497                 b.add(parserLine, LITERAL, name);                // push the name to be declared
498                 b.add(parserLine, DECLARE);                      // declare it
499                 if (peekToken() == ASSIGN) {                     // if there is an '=' after the variable name
500                     b.add(parserLine, LITERAL, name);            // put the var name back on the stack
501                     consume(ASSIGN);
502                     startExpr(b, -1);
503                     b.add(parserLine, PUT);                      // assign it
504                     b.add(parserLine, POP);                      // clean the stack
505                 }
506                 if (peekToken() != COMMA) break;
507                 consume(COMMA);
508             }
509             b.add(parserLine, POP);                              // pop off the topscope
510             if ((mostRecentlyReadToken != RC || peekToken() == SEMI) && peekToken() != -1 && mostRecentlyReadToken != SEMI) consume(SEMI);
511             break;
512         }
513         case IF: {
514             consume(LP);
515             startExpr(b, -1);
516             consume(RP);
517             
518             b.add(parserLine, JF, new Integer(0));                    // if false, jump to the else-block
519             int size = b.size();
520             parseStatement(b, null);
521             
522             if (peekToken() == ELSE) {
523                 consume(ELSE);
524                 b.add(parserLine, JMP, new Integer(0));               // if we took the true-block, jump over the else-block
525                 b.set(size - 1, new Integer(b.size() - size + 1));
526                 size = b.size();
527                 parseStatement(b, null);
528             }
529             b.set(size - 1, new Integer(b.size() - size + 1));        // regardless of which branch we took, b[size] needs to point here
530             break;
531         }
532         case WHILE: {
533             consume(LP);
534             if (label != null) b.add(parserLine, LABEL, label);
535             b.add(parserLine, LOOP);
536             int size = b.size();
537             b.add(parserLine, POP);                                   // discard the first-iteration indicator
538             startExpr(b, -1);
539             b.add(parserLine, JT, new Integer(2));                    // if the while() clause is true, jump over the BREAK
540             b.add(parserLine, BREAK);
541             consume(RP);
542             parseStatement(b, null);
543             b.add(parserLine, CONTINUE);                              // if we fall out of the end, definately continue
544             b.set(size - 1, new Integer(b.size() - size + 1));        // end of the loop
545             break;
546         }
547         case SWITCH: {
548             consume(LP);
549             if (label != null) b.add(parserLine, LABEL, label);
550             b.add(parserLine, LOOP);
551             int size0 = b.size();
552             startExpr(b, -1);
553             consume(RP);
554             consume(LC);
555             while(true)
556                 if (peekToken() == CASE) {                         // we compile CASE statements like a bunch of if..else's
557                     consume(CASE);
558                     b.add(parserLine, DUP);                        // duplicate the switch() value; we'll consume one copy
559                     startExpr(b, -1);
560                     consume(COLON);
561                     b.add(parserLine, EQ);                         // check if we should do this case-block
562                     b.add(parserLine, JF, new Integer(0));         // if not, jump to the next one
563                     int size = b.size();
564                     while(peekToken() != CASE && peekToken() != DEFAULT && peekToken() != RC) parseStatement(b, null);
565                     b.set(size - 1, new Integer(1 + b.size() - size));
566                 } else if (peekToken() == DEFAULT) {
567                     consume(DEFAULT);
568                     consume(COLON);
569                     while(peekToken() != CASE && peekToken() != DEFAULT && peekToken() != RC) parseStatement(b, null);
570                 } else if (peekToken() == RC) {
571                     consume(RC);
572                     b.add(parserLine, BREAK);                      // break out of the loop if we 'fall through'
573                     break;
574                 } else {
575                     throw pe("expected CASE, DEFAULT, or RC; got " + codeToString[peekToken()]);
576                 }
577             b.set(size0 - 1, new Integer(b.size() - size0 + 1));      // end of the loop
578             break;
579         }
580             
581         case DO: {
582             if (label != null) b.add(parserLine, LABEL, label);
583             b.add(parserLine, LOOP);
584             int size = b.size();
585             parseStatement(b, null);
586             consume(WHILE);
587             consume(LP);
588             startExpr(b, -1);
589             b.add(parserLine, JT, new Integer(2));                  // check the while() clause; jump over the BREAK if true
590             b.add(parserLine, BREAK);
591             b.add(parserLine, CONTINUE);
592             consume(RP);
593             consume(SEMI);
594             b.set(size - 1, new Integer(b.size() - size + 1));      // end of the loop; write this location to the LOOP instruction
595             break;
596         }
597             
598         case TRY: {
599             b.add(parserLine, TRY); // try bytecode causes a TryMarker to be pushed
600             int tryInsn = b.size() - 1;
601             // parse the expression to be TRYed
602             parseStatement(b, null); 
603             // pop the try  marker. this is pushed when the TRY bytecode is executed                              
604             b.add(parserLine, POP);
605             // jump forward to the end of the catch block, start of the finally block                             
606             b.add(parserLine, JMP);                                  
607             int successJMPInsn = b.size() - 1;
608             
609             if (peekToken() != CATCH && peekToken() != FINALLY)
610                 throw pe("try without catch or finally");
611             
612             int catchJMPDistance = -1;
613             if (peekToken() == CATCH) {
614                 catchJMPDistance = b.size() - tryInsn;
615                 String exceptionVar;
616                 getToken();
617                 consume(LP);
618                 consume(NAME);
619                 exceptionVar = string;
620                 consume(RP);
621                 b.add(parserLine, TOPSCOPE);                        // the exception is on top of the stack; put it to the chosen name
622                 b.add(parserLine, SWAP);
623                 b.add(parserLine, LITERAL,exceptionVar);
624                 b.add(parserLine, SWAP);
625                 b.add(parserLine, PUT);
626                 b.add(parserLine, POP);
627                 b.add(parserLine, POP);
628                 parseStatement(b, null);
629                 // pop the try and catch markers
630                 b.add(parserLine,POP);
631                 b.add(parserLine,POP);
632             }
633             
634             // jump here if no exception was thrown
635             b.set(successJMPInsn, new Integer(b.size() - successJMPInsn)); 
636                         
637             int finallyJMPDistance = -1;
638             if (peekToken() == FINALLY) {
639                 b.add(parserLine, LITERAL, null); // null FinallyData
640                 finallyJMPDistance = b.size() - tryInsn;
641                 consume(FINALLY);
642                 parseStatement(b, null);
643                 b.add(parserLine,FINALLY_DONE); 
644             }
645             
646             // setup the TRY arguments
647             b.set(tryInsn, new int[] { catchJMPDistance, finallyJMPDistance });
648             
649             break;
650         }
651             
652         case FOR: {
653             consume(LP);
654             
655             tok = getToken();
656             boolean hadVar = false;                                      // if it's a for..in, we ignore the VAR
657             if (tok == VAR) { hadVar = true; tok = getToken(); }
658             String varName = string;
659             boolean forIn = peekToken() == IN;                           // determine if this is a for..in loop or not
660             pushBackToken(tok, varName);
661             
662             if (forIn) {
663                 b.add(parserLine, NEWSCOPE);                             // for-loops always create new scopes
664                 b.add(parserLine, LITERAL, varName);                     // declare the new variable
665                 b.add(parserLine, DECLARE);
666                     
667                 b.add(parserLine, LOOP);                                 // we actually only add this to ensure that BREAK works
668                 b.add(parserLine, POP);                                  // discard the first-iteration indicator
669                 int size = b.size();
670                 consume(NAME);
671                 consume(IN);
672                 startExpr(b, -1);
673                 b.add(parserLine, PUSHKEYS);                             // push the keys as an array; check the length
674                 b.add(parserLine, LITERAL, "length");
675                 b.add(parserLine, GET);
676                 consume(RP);
677                     
678                 b.add(parserLine, LITERAL, new Integer(1));              // decrement the length
679                 b.add(parserLine, SUB);
680                 b.add(parserLine, DUP);
681                 b.add(parserLine, LITERAL, new Integer(0));              // see if we've exhausted all the elements
682                 b.add(parserLine, LT);
683                 b.add(parserLine, JF, new Integer(2));
684                 b.add(parserLine, BREAK);                                // if we have, then BREAK
685                 b.add(parserLine, GET_PRESERVE);                         // get the key out of the keys array
686                 b.add(parserLine, LITERAL, varName);
687                 b.add(parserLine, PUT);                                  // write it to this[varName]                          
688                 parseStatement(b, null);                                 // do some stuff
689                 b.add(parserLine, CONTINUE);                             // continue if we fall out the bottom
690
691                 b.set(size - 1, new Integer(b.size() - size + 1));       // BREAK to here
692                 b.add(parserLine, OLDSCOPE);                             // restore the scope
693                     
694             } else {
695                 if (hadVar) pushBackToken(VAR, null);                    // yeah, this actually matters
696                 b.add(parserLine, NEWSCOPE);                             // grab a fresh scope
697                     
698                 parseStatement(b, null);                                 // initializer
699                 CompiledFunctionImpl e2 =                                    // we need to put the incrementor before the test
700                     new JS.CompiledFunction(sourceName, parserLine, null, null);  // so we save the test here
701                 if (peekToken() != SEMI)
702                     startExpr(e2, -1);
703                 else
704                     e2.add(parserLine, b.LITERAL, Boolean.TRUE);         // handle the for(foo;;foo) case
705                 consume(SEMI);
706                 if (label != null) b.add(parserLine, LABEL, label);
707                 b.add(parserLine, LOOP);
708                 int size2 = b.size();
709                     
710                 b.add(parserLine, JT, new Integer(0));                   // if we're on the first iteration, jump over the incrementor
711                 int size = b.size();
712                 if (peekToken() != RP) {                                 // do the increment thing
713                     startExpr(b, -1);
714                     b.add(parserLine, POP);
715                 }
716                 b.set(size - 1, new Integer(b.size() - size + 1));
717                 consume(RP);
718                     
719                 b.paste(e2);                                             // ok, *now* test if we're done yet
720                 b.add(parserLine, JT, new Integer(2));                   // break out if we don't meet the test
721                 b.add(parserLine, BREAK);
722                 parseStatement(b, null);
723                 b.add(parserLine, CONTINUE);                             // if we fall out the bottom, CONTINUE
724                 b.set(size2 - 1, new Integer(b.size() - size2 + 1));     // end of the loop
725                     
726                 b.add(parserLine, OLDSCOPE);                             // get our scope back
727             }
728             break;
729         }
730                 
731         case NAME: {  // either a label or an identifier; this is the one place we're not LL(1)
732             String possiblyTheLabel = string;
733             if (peekToken() == COLON) {      // label
734                 consume(COLON);
735                 parseStatement(b, possiblyTheLabel);
736                 break;
737             } else {                         // expression
738                 pushBackToken(NAME, possiblyTheLabel);  
739                 startExpr(b, -1);
740                 b.add(parserLine, POP);
741                 if ((mostRecentlyReadToken != RC || peekToken() == SEMI) && peekToken() != -1 && mostRecentlyReadToken != SEMI) consume(SEMI);
742                 break;
743             }
744         }
745
746         case SEMI: return;                                               // yep, the null statement is valid
747
748         case LC: {  // blocks are statements too
749             pushBackToken();
750             b.add(parserLine, NEWSCOPE);
751             parseBlock(b, label);
752             b.add(parserLine, OLDSCOPE);
753             break;
754         }
755
756         default: {  // hope that it's an expression
757             pushBackToken();
758             startExpr(b, -1);
759             b.add(parserLine, POP);
760             if ((mostRecentlyReadToken != RC || peekToken() == SEMI) && peekToken() != -1 && mostRecentlyReadToken != SEMI) consume(SEMI);
761             break;
762         }
763         }
764     }
765
766
767     // ParserException //////////////////////////////////////////////////////////////////////
768     private IOException pe(String s) { return new IOException(sourceName + ":" + parserLine + " " + s); }
769     
770 }
771