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