1 // Copyright 2000-2005 the Contributors, as shown in the revision logs.
2 // Licensed under the Apache Public Source License 2.0 ("the License").
3 // You may not use this file except in compliance with the License.
7 import org.ibex.util.*;
11 * Parses a stream of lexed tokens into a tree of JSFunction's.
13 * There are three kinds of things we parse: blocks, statements, and
16 * - Expressions are a special type of statement that evaluates to a
17 * value (for example, "break" is not an expression, * but "3+2"
18 * is). Some tokens sequences start expressions (for * example,
19 * literal numbers) and others continue an expression which * has
20 * already been begun (for example, '+'). Finally, some *
21 * expressions are valid targets for an assignment operation; after
22 * * each of these expressions, continueExprAfterAssignable() is
23 * called * to check for an assignment operation.
25 * - A statement ends with a semicolon and does not return a value.
27 * - A block is a single statement or a sequence of statements
28 * surrounded by curly braces.
30 * Each parsing method saves the parserLine before doing its actual
31 * work and restores it afterwards. This ensures that parsing a
32 * subexpression does not modify the line number until a token
33 * *after* the subexpression has been consumed by the parent
36 * Technically it would be a better design for this class to build an
37 * intermediate parse tree and use that to emit bytecode. Here's the
40 * Advantages of building a parse tree:
41 * - easier to apply optimizations
42 * - would let us handle more sophisticated languages than JavaScript
44 * Advantages of leaving out the parse tree
45 * - faster compilation
46 * - less load on the garbage collector
47 * - much simpler code, easier to understand
50 * Fortunately JS is such a simple language that we can get away with
51 * the half-assed approach and still produce a working, complete
54 * The bytecode language emitted doesn't really cause any appreciable
55 * semantic loss, and is itself a parseable language very similar to
56 * Forth or a postfix variant of LISP. This means that the bytecode
57 * can be transformed into a parse tree, which can be manipulated.
58 * So if we ever want to add an optimizer, it could easily be done by
59 * producing a parse tree from the bytecode, optimizing that tree,
60 * and then re-emitting the bytecode. The parse tree node class
61 * would also be much simpler since the bytecode language has so few
64 * Actually, the above paragraph is slightly inaccurate -- there are
65 * places where we push a value and then perform an arbitrary number
66 * of operations using it before popping it; this doesn't parse well.
67 * But these cases are clearly marked and easy to change if we do
68 * need to move to a parse tree format.
70 class Parser extends Lexer implements ByteCodes {
73 // Constructors //////////////////////////////////////////////////////
75 private Parser(Reader r, String sourceName, int line) throws IOException { super(r, sourceName, line); }
78 public static void main(String[] s) throws IOException {
79 JS block = JS.fromReader("stdin", 0, new InputStreamReader(System.in));
80 if (block == null) return;
81 System.out.println(block);
84 // Statics ////////////////////////////////////////////////////////////
86 static byte[] precedence = new byte[MAX_TOKEN + 1];
87 static boolean[] isRightAssociative = new boolean[MAX_TOKEN + 1];
88 // Use this as the precedence when we want anything up to the comma
89 private final static int NO_COMMA = 2;
91 isRightAssociative[ASSIGN] =
92 isRightAssociative[ASSIGN_BITOR] =
93 isRightAssociative[ASSIGN_BITXOR] =
94 isRightAssociative[ASSIGN_BITAND] =
95 isRightAssociative[ASSIGN_LSH] =
96 isRightAssociative[ASSIGN_RSH] =
97 isRightAssociative[ASSIGN_URSH] =
98 isRightAssociative[ASSIGN_ADD] =
99 isRightAssociative[ASSIGN_SUB] =
100 isRightAssociative[ASSIGN_MUL] =
101 isRightAssociative[ASSIGN_DIV] =
102 isRightAssociative[ASSIGN_MOD] =
103 isRightAssociative[ADD_TRAP] =
104 isRightAssociative[DEL_TRAP] =
107 precedence[COMMA] = 1;
108 // 2 is intentionally left unassigned. we use minPrecedence==2 for comma separated lists
110 precedence[ASSIGN_BITOR] =
111 precedence[ASSIGN_BITXOR] =
112 precedence[ASSIGN_BITAND] =
113 precedence[ASSIGN_LSH] =
114 precedence[ASSIGN_RSH] =
115 precedence[ASSIGN_URSH] =
116 precedence[ASSIGN_ADD] =
117 precedence[ASSIGN_SUB] =
118 precedence[ASSIGN_MUL] =
119 precedence[ASSIGN_DIV] =
120 precedence[ADD_TRAP] =
121 precedence[DEL_TRAP] =
122 precedence[ASSIGN_MOD] = 3;
123 precedence[HOOK] = 4;
126 precedence[BITOR] = 7;
127 precedence[BITXOR] = 8;
128 precedence[BITAND] = 9;
129 precedence[EQ] = precedence[NE] = precedence[SHEQ] = precedence[SHNE] = 10;
130 precedence[LT] = precedence[LE] = precedence[GT] = precedence[GE] = 11;
131 precedence[LSH] = precedence[RSH] = precedence[URSH] = 12;
132 precedence[ADD] = precedence[SUB] = 12;
133 precedence[MUL] = precedence[DIV] = precedence[MOD] = 13;
134 precedence[BITNOT] = precedence[BANG] = precedence[TYPEOF] = 14;
135 precedence[DOT] = precedence[LB] = precedence[LP] = precedence[INC] = precedence[DEC] = 15;
138 // Local variable management
139 Vec scopeStack = new Vec();
140 static class ScopeInfo {
144 Hash mapping = new Hash();
146 Hash globalCache = new Hash();
147 JS scopeKey(String name) {
148 if(globalCache.get(name) != null) return null;
149 for(int i=scopeStack.size()-1;i>=0;i--) {
150 JS key = (JS)((ScopeInfo) scopeStack.elementAt(i)).mapping.get(name);
151 if(key != null) return key;
153 globalCache.put(name,Boolean.TRUE);
156 void scopeDeclare(String name) throws IOException {
157 ScopeInfo si = (ScopeInfo) scopeStack.lastElement();
158 if(si.mapping.get(name) != null) throw pe("" + name + " already declared in this scope");
159 si.mapping.put(name,JS.N(si.end++));
160 globalCache.put(name,null);
162 void scopePush(JSFunction b) {
163 ScopeInfo prev = (ScopeInfo) scopeStack.lastElement();
164 ScopeInfo si = new ScopeInfo();
167 si.newScopeInsn = b.size;
169 b.add(parserLine, NEWSCOPE);
171 void scopePop(JSFunction b) {
172 ScopeInfo si = (ScopeInfo) scopeStack.pop();
173 b.add(parserLine, OLDSCOPE);
174 b.set(si.newScopeInsn,JS.N((si.base<<16)|((si.end-si.base)<<0)));
178 // Parsing Logic /////////////////////////////////////////////////////////
180 /** parse and compile a function */
181 public static JSFunction fromReader(String sourceName, int firstLine, Reader sourceCode) throws IOException {
182 JSFunction ret = new JSFunction(sourceName, firstLine, null);
183 if (sourceCode == null) return ret;
184 Parser p = new Parser(sourceCode, sourceName, firstLine);
185 p.scopeStack.setSize(0);
186 p.scopeStack.push(new ScopeInfo());
190 if(p.peekToken() == -1) break; // FIXME: Check this logic one more time
191 p.parseStatement(ret, null);
192 //if (s == ret.size) break;
195 if(p.scopeStack.size() != 1) throw new Error("scopeStack height mismatch");
196 ret.add(-1, LITERAL, null);
201 /** gets a token and throws an exception if it is not <tt>code</tt> */
202 private void consume(int code) throws IOException {
203 if (getToken() != code) {
204 if(code == NAME) switch(op) {
205 case RETURN: case TYPEOF: case BREAK: case CONTINUE: case TRY: case THROW:
206 case ASSERT: case NULL: case TRUE: case FALSE: case IN: case IF: case ELSE:
207 case SWITCH: case CASE: case DEFAULT: case WHILE: case VAR: case WITH:
208 case CATCH: case FINALLY:
209 throw pe("Bad variable name; '" + codeToString[op].toLowerCase() + "' is a javascript keyword");
211 throw pe("expected " + codeToString[code] + ", got " + (op == -1 ? "EOF" : codeToString[op]));
216 * Parse the largest possible expression containing no operators
217 * of precedence below <tt>minPrecedence</tt> and append the
218 * bytecodes for that expression to <tt>appendTo</tt>; the
219 * appended bytecodes MUST grow the stack by exactly one element.
221 private void startExpr(JSFunction appendTo, int minPrecedence) throws IOException {
222 int saveParserLine = parserLine;
223 _startExpr(appendTo, minPrecedence);
224 parserLine = saveParserLine;
226 private void _startExpr(JSFunction appendTo, int minPrecedence) throws IOException {
227 int tok = getToken();
228 JSFunction b = appendTo;
231 case -1: throw pe("expected expression");
233 // all of these simply push values onto the stack
234 case NUMBER: b.add(parserLine, LITERAL, JS.N(number)); break;
235 case STRING: b.add(parserLine, LITERAL, JSString.intern(string)); break;
236 case NULL: b.add(parserLine, LITERAL, null); break;
237 case TRUE: case FALSE: b.add(parserLine, LITERAL, tok == TRUE ? JS.T : JS.F); break;
242 b.add(parserLine, GLOBALSCOPE);
243 b.add(parserLine, GET, JS.S("",true));
244 b.add(parserLine, LITERAL, JS.S(string,true));
245 continueExprAfterAssignable(b,minPrecedence,null);
250 b.add(parserLine, ARRAY, JS.ZERO); // push an array onto the stack
253 if (peekToken() != RB)
254 while(true) { // iterate over the initialization values
255 b.add(parserLine, LITERAL, JS.N(i++)); // push the index in the array to place it into
256 if (peekToken() == COMMA || peekToken() == RB)
257 b.add(parserLine, LITERAL, null); // for stuff like [1,,2,]
259 startExpr(b, NO_COMMA); // push the value onto the stack
260 b.add(parserLine, PUT); // put it into the array
261 b.add(parserLine, POP); // discard the value remaining on the stack
262 if (peekToken() == RB) break;
265 b.set(size0 - 1, JS.N(i)); // back at the ARRAY instruction, write the size of the array
269 case SUB: case ADD: {
270 if(peekToken() == NUMBER) { // literal
272 b.add(parserLine, LITERAL, JS.N(number.doubleValue() * (tok == SUB ? -1 : 1)));
273 } else { // unary +/- operator
274 if(tok == SUB) b.add(parserLine, LITERAL, JS.ZERO);
275 // BITNOT has the same precedence as the unary +/- operators
276 startExpr(b,precedence[BITNOT]);
277 if(tok == ADD) b.add(parserLine, LITERAL, JS.ZERO); // HACK to force expr into a numeric context
278 b.add(parserLine, SUB);
282 case LP: { // grouping (not calling)
287 case INC: case DEC: { // prefix (not postfix)
288 startExpr(b, precedence[tok]);
289 int prev = b.size - 1;
290 boolean sg = b.get(prev) == SCOPEGET;
291 if (b.get(prev) == GET && b.getArg(prev) != null)
292 b.set(prev, LITERAL, b.getArg(prev));
293 else if(b.get(prev) == GET)
296 throw pe("prefixed increment/decrement can only be performed on a valid assignment target");
297 if(!sg) b.add(parserLine, GET_PRESERVE, Boolean.TRUE);
298 b.add(parserLine, LITERAL, JS.N(1));
299 b.add(parserLine, tok == INC ? ADD : SUB, JS.N(2));
301 b.add(parserLine, SCOPEPUT, b.getArg(prev));
303 b.add(parserLine, PUT, null);
304 b.add(parserLine, SWAP, null);
305 b.add(parserLine, POP, null);
309 case BANG: case BITNOT: case TYPEOF: {
310 startExpr(b, precedence[tok]);
311 b.add(parserLine, tok);
314 case LC: { // object constructor
315 b.add(parserLine, OBJECT, null); // put an object on the stack
316 if (peekToken() != RC)
318 if (peekToken() != NAME && peekToken() != STRING)
319 throw pe("expected NAME or STRING");
321 b.add(parserLine, LITERAL, JSString.intern(string)); // grab the key
323 startExpr(b, NO_COMMA); // grab the value
324 b.add(parserLine, PUT); // put the value into the object
325 b.add(parserLine, POP); // discard the remaining value
326 if (peekToken() == RC) break;
328 if (peekToken() == RC) break; // we permit {,,} -- I'm not sure if ECMA does
334 JS varKey = scopeKey(string);
336 b.add(parserLine, GLOBALSCOPE);
337 b.add(parserLine, LITERAL, JSString.intern(string));
339 continueExprAfterAssignable(b,minPrecedence,varKey);
343 if(peekToken() == ASSIGN) {
345 startExpr(b, precedence[ASSIGN]);
346 b.add(parserLine, CASCADE, JS.T);
348 b.add(parserLine, CASCADE, JS.F);
356 JSFunction b2 = new JSFunction(sourceName, parserLine, null);
357 b.add(parserLine, NEWFUNCTION, b2);
359 // function prelude; arguments array is already on the stack
361 scopeDeclare("arguments");
362 b2.add(parserLine, SCOPEPUT,scopeKey("arguments"));
364 while(peekToken() != RP) { // run through the list of argument names
366 if (peekToken() == NAME) {
367 consume(NAME); // a named argument
369 b2.add(parserLine, DUP); // dup the args array
370 b2.add(parserLine, GET, JS.N(numArgs - 1)); // retrieve it from the arguments array
371 scopeDeclare(string);
372 b2.add(parserLine, SCOPEPUT, scopeKey(string));
373 b2.add(parserLine, POP);
375 if (peekToken() == RP) break;
380 b2.numFormalArgs = numArgs;
381 b2.add(parserLine, POP); // pop off the arguments array
383 if(peekToken() != LC)
384 throw pe("JSFunctions must have a block surrounded by curly brackets");
386 parseBlock(b2, null); // the function body
389 b2.add(parserLine, LITERAL, null); // in case we "fall out the bottom", return NULL
390 b2.add(parserLine, RETURN);
394 default: throw pe("expected expression, found " + codeToString[tok] + ", which cannot start an expression");
397 // attempt to continue the expression
398 continueExpr(b, minPrecedence);
401 private Grammar parseGrammar(Grammar g) throws IOException {
402 int tok = getToken();
405 case BITOR: return new Grammar.Alternative(g, parseGrammar(null));
406 case ADD: return parseGrammar(new Grammar.Repetition(g, 1, Integer.MAX_VALUE));
407 case MUL: return parseGrammar(new Grammar.Repetition(g, 0, Integer.MAX_VALUE));
408 case HOOK: return parseGrammar(new Grammar.Repetition(g, 0, 1));
412 //case NUMBER: g0 = new Grammar.Literal(number); break;
413 case NAME: g0 = new Grammar.Reference(string); break;
415 g0 = new Grammar.Literal(string);
416 if (peekToken() == DOT) {
421 if (old.length() != 1 || string.length() != 1) throw pe("literal ranges must be single-char strings");
422 g0 = new Grammar.Range(old.charAt(0), string.charAt(0));
425 case LP: g0 = parseGrammar(null); consume(RP); break;
426 default: pushBackToken(); return g;
428 if (g == null) return parseGrammar(g0);
429 return parseGrammar(new Grammar.Juxtaposition(g, g0));
433 * Assuming that a complete assignable (lvalue) has just been
434 * parsed and the object and key are on the stack,
435 * <tt>continueExprAfterAssignable</tt> will attempt to parse an
436 * expression that modifies the assignable. This method always
437 * decreases the stack depth by exactly one element.
439 private void continueExprAfterAssignable(JSFunction b,int minPrecedence, JS varKey) throws IOException {
440 int saveParserLine = parserLine;
441 _continueExprAfterAssignable(b,minPrecedence,varKey);
442 parserLine = saveParserLine;
444 private void _continueExprAfterAssignable(JSFunction b,int minPrecedence, JS varKey) throws IOException {
445 if (b == null) throw new Error("got null b; this should never happen");
446 int tok = getToken();
447 if (minPrecedence != -1 && (precedence[tok] < minPrecedence || (precedence[tok] == minPrecedence && !isRightAssociative[tok])))
448 // force the default case
453 b.add(parserLine, GET_PRESERVE);
454 Grammar g = parseGrammar(null);
455 if (peekToken() == LC) {
456 g.action = new JSFunction(sourceName, parserLine, null);
457 parseBlock((JSFunction)g.action);
458 ((JSFunction)g.action).add(parserLine, LITERAL, null); // in case we "fall out the bottom", return NULL
459 ((JSFunction)g.action).add(parserLine, RETURN);
461 b.add(parserLine, MAKE_GRAMMAR, g);
462 b.add(parserLine, PUT);
466 case ASSIGN_BITOR: case ASSIGN_BITXOR: case ASSIGN_BITAND: case ASSIGN_LSH: case ASSIGN_RSH: case ASSIGN_URSH:
467 case ASSIGN_MUL: case ASSIGN_DIV: case ASSIGN_MOD: case ASSIGN_ADD: case ASSIGN_SUB: case ADD_TRAP: case DEL_TRAP: {
468 if (tok != ADD_TRAP && tok != DEL_TRAP)
469 b.add(parserLine, varKey == null ? GET_PRESERVE : SCOPEGET, varKey);
471 startExpr(b, precedence[tok]);
473 if (tok != ADD_TRAP && tok != DEL_TRAP) {
474 // tok-1 is always s/^ASSIGN_// (0 is BITOR, 1 is ASSIGN_BITOR, etc)
475 b.add(parserLine, tok - 1, tok-1==ADD ? JS.N(2) : null);
477 b.add(parserLine, PUT);
478 b.add(parserLine, SWAP);
479 b.add(parserLine, POP);
481 b.add(parserLine, SCOPEPUT, varKey);
484 if(varKey != null) throw pe("cannot place traps on local variables");
485 b.add(parserLine, tok);
489 case INC: case DEC: { // postfix
491 b.add(parserLine, GET_PRESERVE, Boolean.TRUE);
492 b.add(parserLine, LITERAL, JS.N(1));
493 b.add(parserLine, tok == INC ? ADD : SUB, JS.N(2));
494 b.add(parserLine, PUT, null);
495 b.add(parserLine, SWAP, null);
496 b.add(parserLine, POP, null);
497 b.add(parserLine, LITERAL, JS.N(1));
498 b.add(parserLine, tok == INC ? SUB : ADD, JS.N(2)); // undo what we just did, since this is postfix
500 b.add(parserLine, SCOPEGET, varKey);
501 b.add(parserLine, DUP);
502 b.add(parserLine, LITERAL, JS.ONE);
503 b.add(parserLine, tok == INC ? ADD : SUB, JS.N(2));
504 b.add(parserLine, SCOPEPUT, varKey);
509 startExpr(b, precedence[tok]);
511 b.add(parserLine, PUT);
512 b.add(parserLine, SWAP);
513 b.add(parserLine, POP);
515 b.add(parserLine, SCOPEPUT, varKey);
520 // Method calls are implemented by doing a GET_PRESERVE
521 // first. If the object supports method calls, it will
523 b.add(parserLine, varKey == null ? GET_PRESERVE : SCOPEGET, varKey);
524 int n = parseArgs(b);
525 b.add(parserLine, varKey == null ? CALLMETHOD : CALL, JS.N(n));
531 b.add(parserLine, SCOPEGET, varKey);
532 else if(b.get(b.size-1) == LITERAL && b.getArg(b.size-1) != null)
533 b.set(b.size-1,GET,b.getArg(b.size-1));
535 b.add(parserLine, GET);
543 * Assuming that a complete expression has just been parsed,
544 * <tt>continueExpr</tt> will attempt to extend this expression by
545 * parsing additional tokens and appending additional bytecodes.
547 * No operators with precedence less than <tt>minPrecedence</tt>
550 * If any bytecodes are appended, they will not alter the stack
553 private void continueExpr(JSFunction b, int minPrecedence) throws IOException {
554 int saveParserLine = parserLine;
555 _continueExpr(b, minPrecedence);
556 parserLine = saveParserLine;
558 private void _continueExpr(JSFunction b, int minPrecedence) throws IOException {
559 if (b == null) throw new Error("got null b; this should never happen");
560 int tok = getToken();
561 if (tok == -1) return;
562 if (minPrecedence != -1 && (precedence[tok] < minPrecedence || (precedence[tok] == minPrecedence && !isRightAssociative[tok]))) {
568 case LP: { // invocation (not grouping)
569 int n = parseArgs(b);
570 b.add(parserLine, CALL, JS.N(n));
573 case BITOR: case BITXOR: case BITAND: case SHEQ: case SHNE: case LSH:
574 case RSH: case URSH: case MUL: case DIV: case MOD:
575 case GT: case GE: case EQ: case NE: case LT: case LE: case SUB: {
576 startExpr(b, precedence[tok]);
577 b.add(parserLine, tok);
584 startExpr(b,precedence[tok]);
586 nextTok = getToken();
587 } while(nextTok == tok);
589 b.add(parserLine, tok, JS.N(count));
593 b.add(parserLine, tok == AND ? JSFunction.JF : JSFunction.JT, JS.ZERO); // test to see if we can short-circuit
595 startExpr(b, precedence[tok]); // otherwise check the second value
596 b.add(parserLine, JMP, JS.N(2)); // leave the second value on the stack and jump to the end
597 b.add(parserLine, LITERAL, tok == AND ?
598 JS.B(false) : JS.B(true)); // target of the short-circuit jump is here
599 b.set(size - 1, JS.N(b.size - size)); // write the target of the short-circuit jump
603 // support foo..bar syntax for foo[""].bar
604 if (peekToken() == DOT) {
609 b.add(parserLine, LITERAL, JSString.intern(string));
610 continueExprAfterAssignable(b,minPrecedence,null);
613 case LB: { // subscripting (not array constructor)
616 continueExprAfterAssignable(b,minPrecedence,null);
620 b.add(parserLine, JF, JS.ZERO); // jump to the if-false expression
622 startExpr(b, minPrecedence); // write the if-true expression
623 b.add(parserLine, JMP, JS.ZERO); // if true, jump *over* the if-false expression
624 b.set(size - 1, JS.N(b.size - size + 1)); // now we know where the target of the jump is
627 startExpr(b, minPrecedence); // write the if-false expression
628 b.set(size - 1, JS.N(b.size - size + 1)); // this is the end; jump to here
632 // pop the result of the previous expression, it is ignored
633 b.add(parserLine,POP);
643 continueExpr(b, minPrecedence); // try to continue the expression
646 // parse a set of comma separated function arguments, assume LP has already been consumed
647 private int parseArgs(JSFunction b) throws IOException {
649 while(peekToken() != RP) {
651 if (peekToken() != COMMA) {
652 startExpr(b, NO_COMMA);
653 if (peekToken() == RP) break;
661 /** Parse a block of statements which must be surrounded by LC..RC. */
662 void parseBlock(JSFunction b) throws IOException { parseBlock(b, null); }
663 void parseBlock(JSFunction b, String label) throws IOException {
664 int saveParserLine = parserLine;
665 _parseBlock(b, label);
666 parserLine = saveParserLine;
668 void _parseBlock(JSFunction b, String label) throws IOException {
669 if (peekToken() == -1) return;
670 else if (peekToken() != LC) parseStatement(b, null);
673 while(peekToken() != RC && peekToken() != -1) parseStatement(b, null);
678 /** Parse a single statement, consuming the RC or SEMI which terminates it. */
679 void parseStatement(JSFunction b, String label) throws IOException {
680 int saveParserLine = parserLine;
681 _parseStatement(b, label);
682 parserLine = saveParserLine;
684 void _parseStatement(JSFunction b, String label) throws IOException {
685 int tok = peekToken();
686 if (tok == -1) return;
687 switch(tok = getToken()) {
689 case THROW: case ASSERT: case RETURN: {
690 if (tok == RETURN && peekToken() == SEMI)
691 b.add(parserLine, LITERAL, null);
694 b.add(parserLine, tok);
698 case BREAK: case CONTINUE: {
699 if (peekToken() == NAME) consume(NAME);
700 b.add(parserLine, tok, string);
709 if (peekToken() == ASSIGN) { // if there is an '=' after the variable name
711 startExpr(b, NO_COMMA);
712 b.add(parserLine, SCOPEPUT, scopeKey(var)); // assign it
713 b.add(parserLine, POP); // clean the stack
715 if (peekToken() != COMMA) break;
718 if ((mostRecentlyReadToken != RC || peekToken() == SEMI) && peekToken() != -1 && mostRecentlyReadToken != SEMI) consume(SEMI);
726 b.add(parserLine, JF, JS.ZERO); // if false, jump to the else-block
728 parseStatement(b, null);
730 if (peekToken() == ELSE) {
732 b.add(parserLine, JMP, JS.ZERO); // if we took the true-block, jump over the else-block
733 b.set(size - 1, JS.N(b.size - size + 1));
735 parseStatement(b, null);
737 b.set(size - 1, JS.N(b.size - size + 1)); // regardless of which branch we took, b[size] needs to point here
742 if (label != null) b.add(parserLine, LABEL, label);
743 b.add(parserLine, LOOP);
745 b.add(parserLine, POP); // discard the first-iteration indicator
747 b.add(parserLine, JT, JS.N(2)); // if the while() clause is true, jump over the BREAK
748 b.add(parserLine, BREAK);
750 parseStatement(b, null);
751 b.add(parserLine, CONTINUE); // if we fall out of the end, definately continue
752 b.set(size - 1, JS.N(b.size - size + 1)); // end of the loop
757 if (label != null) b.add(parserLine, LABEL, label);
758 b.add(parserLine, LOOP);
764 if (peekToken() == CASE) { // we compile CASE statements like a bunch of if..else's
766 b.add(parserLine, DUP); // duplicate the switch() value; we'll consume one copy
769 b.add(parserLine, EQ); // check if we should do this case-block
770 b.add(parserLine, JF, JS.ZERO); // if not, jump to the next one
772 while(peekToken() != CASE && peekToken() != DEFAULT && peekToken() != RC) parseStatement(b, null);
773 b.set(size - 1, JS.N(1 + b.size - size));
774 } else if (peekToken() == DEFAULT) {
777 while(peekToken() != CASE && peekToken() != DEFAULT && peekToken() != RC) parseStatement(b, null);
778 } else if (peekToken() == RC) {
780 b.add(parserLine, BREAK); // break out of the loop if we 'fall through'
783 throw pe("expected CASE, DEFAULT, or RC; got " + codeToString[peekToken()]);
785 b.set(size0 - 1, JS.N(b.size - size0 + 1)); // end of the loop
790 if (label != null) b.add(parserLine, LABEL, label);
791 b.add(parserLine, LOOP);
793 parseStatement(b, null);
797 b.add(parserLine, JT, JS.N(2)); // check the while() clause; jump over the BREAK if true
798 b.add(parserLine, BREAK);
799 b.add(parserLine, CONTINUE);
802 b.set(size - 1, JS.N(b.size - size + 1)); // end of the loop; write this location to the LOOP instruction
807 b.add(parserLine, TRY); // try bytecode causes a TryMarker to be pushed
808 int tryInsn = b.size - 1;
809 // parse the expression to be TRYed
810 parseStatement(b, null);
811 // pop the try marker. this is pushed when the TRY bytecode is executed
812 b.add(parserLine, POP);
813 // jump forward to the end of the catch block, start of the finally block
814 b.add(parserLine, JMP);
815 int successJMPInsn = b.size - 1;
817 if (peekToken() != CATCH && peekToken() != FINALLY)
818 throw pe("try without catch or finally");
820 int catchJMPDistance = -1;
821 if (peekToken() == CATCH) {
822 Vec catchEnds = new Vec();
823 boolean catchAll = false;
825 catchJMPDistance = b.size - tryInsn;
827 while(peekToken() == CATCH && !catchAll) {
832 exceptionVar = string;
833 int[] writebacks = new int[] { -1, -1, -1 };
834 if (peekToken() != RP) {
835 // extended Ibex catch block: catch(e faultCode "foo.bar.baz")
837 b.add(parserLine, DUP);
838 b.add(parserLine, LITERAL, JSString.intern(string));
839 b.add(parserLine, GET);
840 b.add(parserLine, DUP);
841 b.add(parserLine, LITERAL, null);
842 b.add(parserLine, EQ);
843 b.add(parserLine, JT);
844 writebacks[0] = b.size - 1;
845 if (peekToken() == STRING) {
847 b.add(parserLine, DUP);
848 b.add(parserLine, LITERAL, string);
849 b.add(parserLine, LT);
850 b.add(parserLine, JT);
851 writebacks[1] = b.size - 1;
852 b.add(parserLine, DUP);
853 b.add(parserLine, LITERAL, string + "/"); // (slash is ASCII after dot)
854 b.add(parserLine, GE);
855 b.add(parserLine, JT);
856 writebacks[2] = b.size - 1;
859 b.add(parserLine, DUP);
860 b.add(parserLine, LITERAL, number);
861 b.add(parserLine, EQ);
862 b.add(parserLine, JF);
863 writebacks[1] = b.size - 1;
865 b.add(parserLine, POP); // pop the element thats on the stack from the compare
870 // the exception is on top of the stack; put it to the chosen name
872 scopeDeclare(exceptionVar);
873 b.add(parserLine, SCOPEPUT, scopeKey(exceptionVar));
874 b.add(parserLine, POP);
878 b.add(parserLine, JMP);
879 catchEnds.addElement(new Integer(b.size-1));
881 for(int i=0; i<3; i++) if (writebacks[i] != -1) b.set(writebacks[i], JS.N(b.size-writebacks[i]));
882 b.add(parserLine, POP); // pop the element thats on the stack from the compare
886 b.add(parserLine, THROW);
888 for(int i=0;i<catchEnds.size();i++) {
889 int n = ((Integer)catchEnds.elementAt(i)).intValue();
890 b.set(n, JS.N(b.size-n));
893 // pop the try and catch markers
894 b.add(parserLine,POP);
895 b.add(parserLine,POP);
898 // jump here if no exception was thrown
899 b.set(successJMPInsn, JS.N(b.size - successJMPInsn));
901 int finallyJMPDistance = -1;
902 if (peekToken() == FINALLY) {
903 b.add(parserLine, LITERAL, null); // null FinallyData
904 finallyJMPDistance = b.size - tryInsn;
906 parseStatement(b, null);
907 b.add(parserLine,FINALLY_DONE);
910 // setup the TRY arguments
911 b.set(tryInsn, new int[] { catchJMPDistance, finallyJMPDistance });
920 boolean hadVar = false; // if it's a for..in, we ignore the VAR
921 if (tok == VAR) { hadVar = true; tok = getToken(); }
922 String varName = string;
923 boolean forIn = peekToken() == IN; // determine if this is a for..in loop or not
924 pushBackToken(tok, varName);
932 b.add(parserLine, PUSHKEYS);
935 b.add(parserLine, LOOP);
936 b.add(parserLine, POP);
938 b.add(parserLine,SWAP); // get the keys enumeration object on top
939 b.add(parserLine,DUP);
940 b.add(parserLine,GET,JS.S("hasMoreElements"));
942 b.add(parserLine,JT);
943 b.add(parserLine,SWAP);
944 b.add(parserLine,BREAK);
945 b.set(size2, JS.N(b.size - size2));
946 b.add(parserLine,DUP);
947 b.add(parserLine,GET,JS.S("nextElement"));
951 if(hadVar) scopeDeclare(varName);
952 JS varKey = scopeKey(varName);
955 b.add(parserLine,GLOBALSCOPE);
956 b.add(parserLine,SWAP);
957 b.add(parserLine, LITERAL, JSString.intern(varName));
958 b.add(parserLine,SWAP);
959 b.add(parserLine,PUT);
960 b.add(parserLine,POP);
962 b.add(parserLine, SCOPEPUT, varKey);
964 b.add(parserLine,POP); // pop the put'ed value
965 b.add(parserLine,SWAP); // put CallMarker back into place
967 parseStatement(b, null);
970 b.add(parserLine, CONTINUE);
971 // jump here on break
972 b.set(size, JS.N(b.size - size));
974 b.add(parserLine, POP);
976 if (hadVar) pushBackToken(VAR, null); // yeah, this actually matters
977 scopePush(b); // grab a fresh scope
979 parseStatement(b, null); // initializer
980 JSFunction e2 = // we need to put the incrementor before the test
981 new JSFunction(sourceName, parserLine, null); // so we save the test here
982 if (peekToken() != SEMI)
985 e2.add(parserLine, JSFunction.LITERAL, JS.T); // handle the for(foo;;foo) case
987 if (label != null) b.add(parserLine, LABEL, label);
988 b.add(parserLine, LOOP);
991 b.add(parserLine, JT, JS.ZERO); // if we're on the first iteration, jump over the incrementor
993 if (peekToken() != RP) { // do the increment thing
995 b.add(parserLine, POP);
997 b.set(size - 1, JS.N(b.size - size + 1));
1000 b.paste(e2); // ok, *now* test if we're done yet
1001 b.add(parserLine, JT, JS.N(2)); // break out if we don't meet the test
1002 b.add(parserLine, BREAK);
1003 parseStatement(b, null);
1004 b.add(parserLine, CONTINUE); // if we fall out the bottom, CONTINUE
1005 b.set(size2 - 1, JS.N(b.size - size2 + 1)); // end of the loop
1007 scopePop(b); // get our scope back
1012 case NAME: { // either a label or an identifier; this is the one place we're not LL(1)
1013 String possiblyTheLabel = string;
1014 if (peekToken() == COLON) { // label
1016 parseStatement(b, possiblyTheLabel);
1018 } else { // expression
1019 pushBackToken(NAME, possiblyTheLabel);
1021 b.add(parserLine, POP);
1022 if ((mostRecentlyReadToken != RC || peekToken() == SEMI) && peekToken() != -1 && mostRecentlyReadToken != SEMI) consume(SEMI);
1027 case SEMI: return; // yep, the null statement is valid
1029 case LC: { // blocks are statements too
1032 parseBlock(b, label);
1037 default: { // hope that it's an expression
1040 b.add(parserLine, POP);
1041 if ((mostRecentlyReadToken != RC || peekToken() == SEMI) && peekToken() != -1 && mostRecentlyReadToken != SEMI) consume(SEMI);
1048 // ParserException //////////////////////////////////////////////////////////////////////
1049 private IOException pe(String s) { return new IOException(sourceName + ":" + line + " " + s); }