1 // Copyright 2004 Adam Megacz, see the COPYING file for licensing [GPL]
4 import org.ibex.util.*;
8 * Parses a stream of lexed tokens into a tree of JSFunction's.
10 * There are three kinds of things we parse: blocks, statements, and
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.
22 * - A statement ends with a semicolon and does not return a value.
24 * - A block is a single statement or a sequence of statements
25 * surrounded by curly braces.
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
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
37 * Advantages of building a parse tree:
38 * - easier to apply optimizations
39 * - would let us handle more sophisticated languages than JavaScript
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
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
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
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.
67 class Parser extends Lexer implements ByteCodes {
70 // Constructors //////////////////////////////////////////////////////
72 private Parser(Reader r, String sourceName, int line) throws IOException { super(r, sourceName, line); }
75 public static void main(String[] s) throws IOException {
76 JS block = JS.fromReader("stdin", 0, new InputStreamReader(System.in));
77 if (block == null) return;
78 System.out.println(block);
81 // Statics ////////////////////////////////////////////////////////////
83 static byte[] precedence = new byte[MAX_TOKEN + 1];
84 static boolean[] isRightAssociative = new boolean[MAX_TOKEN + 1];
85 // Use this as the precedence when we want anything up to the comma
86 private final static int NO_COMMA = 2;
88 isRightAssociative[ASSIGN] =
89 isRightAssociative[ASSIGN_BITOR] =
90 isRightAssociative[ASSIGN_BITXOR] =
91 isRightAssociative[ASSIGN_BITAND] =
92 isRightAssociative[ASSIGN_LSH] =
93 isRightAssociative[ASSIGN_RSH] =
94 isRightAssociative[ASSIGN_URSH] =
95 isRightAssociative[ASSIGN_ADD] =
96 isRightAssociative[ASSIGN_SUB] =
97 isRightAssociative[ASSIGN_MUL] =
98 isRightAssociative[ASSIGN_DIV] =
99 isRightAssociative[ASSIGN_MOD] =
100 isRightAssociative[ADD_TRAP] =
101 isRightAssociative[DEL_TRAP] =
104 precedence[COMMA] = 1;
105 // 2 is intentionally left unassigned. we use minPrecedence==2 for comma separated lists
107 precedence[ASSIGN_BITOR] =
108 precedence[ASSIGN_BITXOR] =
109 precedence[ASSIGN_BITAND] =
110 precedence[ASSIGN_LSH] =
111 precedence[ASSIGN_RSH] =
112 precedence[ASSIGN_URSH] =
113 precedence[ASSIGN_ADD] =
114 precedence[ASSIGN_SUB] =
115 precedence[ASSIGN_MUL] =
116 precedence[ASSIGN_DIV] =
117 precedence[ADD_TRAP] =
118 precedence[DEL_TRAP] =
119 precedence[ASSIGN_MOD] = 3;
120 precedence[HOOK] = 4;
123 precedence[BITOR] = 7;
124 precedence[BITXOR] = 8;
125 precedence[BITAND] = 9;
126 precedence[EQ] = precedence[NE] = precedence[SHEQ] = precedence[SHNE] = 10;
127 precedence[LT] = precedence[LE] = precedence[GT] = precedence[GE] = 11;
128 precedence[LSH] = precedence[RSH] = precedence[URSH] = 12;
129 precedence[ADD] = precedence[SUB] = 12;
130 precedence[MUL] = precedence[DIV] = precedence[MOD] = 13;
131 precedence[BITNOT] = precedence[BANG] = precedence[TYPEOF] = 14;
132 precedence[DOT] = precedence[LB] = precedence[LP] = precedence[INC] = precedence[DEC] = 15;
135 // Local variable management
136 Vec scopeStack = new Vec();
137 static class ScopeInfo {
141 Hash mapping = new Hash();
143 Hash globalCache = new Hash();
144 JS scopeKey(String name) {
145 if(globalCache.get(name) != null) return null;
146 for(int i=scopeStack.size()-1;i>=0;i--) {
147 JS key = (JS)((ScopeInfo) scopeStack.elementAt(i)).mapping.get(name);
148 if(key != null) return key;
150 globalCache.put(name,Boolean.TRUE);
153 void scopeDeclare(String name) throws IOException {
154 ScopeInfo si = (ScopeInfo) scopeStack.lastElement();
155 if(si.mapping.get(name) != null) throw pe("" + name + " already declared in this scope");
156 si.mapping.put(name,JS.N(si.end++));
157 globalCache.put(name,null);
159 void scopePush(JSFunction b) {
160 ScopeInfo prev = (ScopeInfo) scopeStack.lastElement();
161 ScopeInfo si = new ScopeInfo();
164 si.newScopeInsn = b.size;
166 b.add(parserLine, NEWSCOPE);
168 void scopePop(JSFunction b) {
169 ScopeInfo si = (ScopeInfo) scopeStack.pop();
170 b.add(parserLine, OLDSCOPE);
171 b.set(si.newScopeInsn,JS.N((si.base<<16)|((si.end-si.base)<<0)));
175 // Parsing Logic /////////////////////////////////////////////////////////
177 /** parse and compile a function */
178 public static JSFunction fromReader(String sourceName, int firstLine, Reader sourceCode) throws IOException {
179 JSFunction ret = new JSFunction(sourceName, firstLine, null);
180 if (sourceCode == null) return ret;
181 Parser p = new Parser(sourceCode, sourceName, firstLine);
182 p.scopeStack.setSize(0);
183 p.scopeStack.push(new ScopeInfo());
187 if(p.peekToken() == -1) break; // FIXME: Check this logic one more time
188 p.parseStatement(ret, null);
189 //if (s == ret.size) break;
192 if(p.scopeStack.size() != 1) throw new Error("scopeStack height mismatch");
193 ret.add(-1, LITERAL, null);
198 /** gets a token and throws an exception if it is not <tt>code</tt> */
199 private void consume(int code) throws IOException {
200 if (getToken() != code) {
201 if(code == NAME) switch(op) {
202 case RETURN: case TYPEOF: case BREAK: case CONTINUE: case TRY: case THROW:
203 case ASSERT: case NULL: case TRUE: case FALSE: case IN: case IF: case ELSE:
204 case SWITCH: case CASE: case DEFAULT: case WHILE: case VAR: case WITH:
205 case CATCH: case FINALLY:
206 throw pe("Bad variable name; '" + codeToString[op].toLowerCase() + "' is a javascript keyword");
208 throw pe("expected " + codeToString[code] + ", got " + (op == -1 ? "EOF" : codeToString[op]));
213 * Parse the largest possible expression containing no operators
214 * of precedence below <tt>minPrecedence</tt> and append the
215 * bytecodes for that expression to <tt>appendTo</tt>; the
216 * appended bytecodes MUST grow the stack by exactly one element.
218 private void startExpr(JSFunction appendTo, int minPrecedence) throws IOException {
219 int saveParserLine = parserLine;
220 _startExpr(appendTo, minPrecedence);
221 parserLine = saveParserLine;
223 private void _startExpr(JSFunction appendTo, int minPrecedence) throws IOException {
224 int tok = getToken();
225 JSFunction b = appendTo;
228 case -1: throw pe("expected expression");
230 // all of these simply push values onto the stack
231 case NUMBER: b.add(parserLine, LITERAL, JS.N(number)); break;
232 case STRING: b.add(parserLine, LITERAL, JSString.intern(string)); break;
233 case NULL: b.add(parserLine, LITERAL, null); break;
234 case TRUE: case FALSE: b.add(parserLine, LITERAL, tok == TRUE ? JS.T : JS.F); break;
239 b.add(parserLine, GLOBALSCOPE);
240 b.add(parserLine, GET, JS.S("",true));
241 b.add(parserLine, LITERAL, JS.S(string,true));
242 continueExprAfterAssignable(b,minPrecedence,null);
247 b.add(parserLine, ARRAY, JS.ZERO); // push an array onto the stack
250 if (peekToken() != RB)
251 while(true) { // iterate over the initialization values
252 b.add(parserLine, LITERAL, JS.N(i++)); // push the index in the array to place it into
253 if (peekToken() == COMMA || peekToken() == RB)
254 b.add(parserLine, LITERAL, null); // for stuff like [1,,2,]
256 startExpr(b, NO_COMMA); // push the value onto the stack
257 b.add(parserLine, PUT); // put it into the array
258 b.add(parserLine, POP); // discard the value remaining on the stack
259 if (peekToken() == RB) break;
262 b.set(size0 - 1, JS.N(i)); // back at the ARRAY instruction, write the size of the array
266 case SUB: case ADD: {
267 if(peekToken() == NUMBER) { // literal
269 b.add(parserLine, LITERAL, JS.N(number.doubleValue() * (tok == SUB ? -1 : 1)));
270 } else { // unary +/- operator
271 if(tok == SUB) b.add(parserLine, LITERAL, JS.ZERO);
272 // BITNOT has the same precedence as the unary +/- operators
273 startExpr(b,precedence[BITNOT]);
274 if(tok == ADD) b.add(parserLine, LITERAL, JS.ZERO); // HACK to force expr into a numeric context
275 b.add(parserLine, SUB);
279 case LP: { // grouping (not calling)
284 case INC: case DEC: { // prefix (not postfix)
285 startExpr(b, precedence[tok]);
286 int prev = b.size - 1;
287 boolean sg = b.get(prev) == SCOPEGET;
288 if (b.get(prev) == GET && b.getArg(prev) != null)
289 b.set(prev, LITERAL, b.getArg(prev));
290 else if(b.get(prev) == GET)
293 throw pe("prefixed increment/decrement can only be performed on a valid assignment target");
294 if(!sg) b.add(parserLine, GET_PRESERVE, Boolean.TRUE);
295 b.add(parserLine, LITERAL, JS.N(1));
296 b.add(parserLine, tok == INC ? ADD : SUB, JS.N(2));
298 b.add(parserLine, SCOPEPUT, b.getArg(prev));
300 b.add(parserLine, PUT, null);
301 b.add(parserLine, SWAP, null);
302 b.add(parserLine, POP, null);
306 case BANG: case BITNOT: case TYPEOF: {
307 startExpr(b, precedence[tok]);
308 b.add(parserLine, tok);
311 case LC: { // object constructor
312 b.add(parserLine, OBJECT, null); // put an object on the stack
313 if (peekToken() != RC)
315 if (peekToken() != NAME && peekToken() != STRING)
316 throw pe("expected NAME or STRING");
318 b.add(parserLine, LITERAL, JSString.intern(string)); // grab the key
320 startExpr(b, NO_COMMA); // grab the value
321 b.add(parserLine, PUT); // put the value into the object
322 b.add(parserLine, POP); // discard the remaining value
323 if (peekToken() == RC) break;
325 if (peekToken() == RC) break; // we permit {,,} -- I'm not sure if ECMA does
331 JS varKey = scopeKey(string);
333 b.add(parserLine, GLOBALSCOPE);
334 b.add(parserLine, LITERAL, JSString.intern(string));
336 continueExprAfterAssignable(b,minPrecedence,varKey);
340 if(peekToken() == ASSIGN) {
342 startExpr(b, precedence[ASSIGN]);
343 b.add(parserLine, CASCADE, JS.T);
345 b.add(parserLine, CASCADE, JS.F);
353 JSFunction b2 = new JSFunction(sourceName, parserLine, null);
354 b.add(parserLine, NEWFUNCTION, b2);
356 // function prelude; arguments array is already on the stack
358 scopeDeclare("arguments");
359 b2.add(parserLine, SCOPEPUT,scopeKey("arguments"));
361 while(peekToken() != RP) { // run through the list of argument names
363 if (peekToken() == NAME) {
364 consume(NAME); // a named argument
366 b2.add(parserLine, DUP); // dup the args array
367 b2.add(parserLine, GET, JS.N(numArgs - 1)); // retrieve it from the arguments array
368 scopeDeclare(string);
369 b2.add(parserLine, SCOPEPUT, scopeKey(string));
370 b2.add(parserLine, POP);
372 if (peekToken() == RP) break;
377 b2.numFormalArgs = numArgs;
378 b2.add(parserLine, POP); // pop off the arguments array
380 if(peekToken() != LC)
381 throw pe("JSFunctions must have a block surrounded by curly brackets");
383 parseBlock(b2, null); // the function body
386 b2.add(parserLine, LITERAL, null); // in case we "fall out the bottom", return NULL
387 b2.add(parserLine, RETURN);
391 default: throw pe("expected expression, found " + codeToString[tok] + ", which cannot start an expression");
394 // attempt to continue the expression
395 continueExpr(b, minPrecedence);
398 private Grammar parseGrammar(Grammar g) throws IOException {
399 int tok = getToken();
402 case BITOR: return new Grammar.Alternative(g, parseGrammar(null));
403 case ADD: return parseGrammar(new Grammar.Repetition(g, 1, Integer.MAX_VALUE));
404 case MUL: return parseGrammar(new Grammar.Repetition(g, 0, Integer.MAX_VALUE));
405 case HOOK: return parseGrammar(new Grammar.Repetition(g, 0, 1));
409 //case NUMBER: g0 = new Grammar.Literal(number); break;
410 case NAME: g0 = new Grammar.Reference(string); break;
412 g0 = new Grammar.Literal(string);
413 if (peekToken() == DOT) {
418 if (old.length() != 1 || string.length() != 1) throw pe("literal ranges must be single-char strings");
419 g0 = new Grammar.Range(old.charAt(0), string.charAt(0));
422 case LP: g0 = parseGrammar(null); consume(RP); break;
423 default: pushBackToken(); return g;
425 if (g == null) return parseGrammar(g0);
426 return parseGrammar(new Grammar.Juxtaposition(g, g0));
430 * Assuming that a complete assignable (lvalue) has just been
431 * parsed and the object and key are on the stack,
432 * <tt>continueExprAfterAssignable</tt> will attempt to parse an
433 * expression that modifies the assignable. This method always
434 * decreases the stack depth by exactly one element.
436 private void continueExprAfterAssignable(JSFunction b,int minPrecedence, JS varKey) throws IOException {
437 int saveParserLine = parserLine;
438 _continueExprAfterAssignable(b,minPrecedence,varKey);
439 parserLine = saveParserLine;
441 private void _continueExprAfterAssignable(JSFunction b,int minPrecedence, JS varKey) throws IOException {
442 if (b == null) throw new Error("got null b; this should never happen");
443 int tok = getToken();
444 if (minPrecedence != -1 && (precedence[tok] < minPrecedence || (precedence[tok] == minPrecedence && !isRightAssociative[tok])))
445 // force the default case
450 b.add(parserLine, GET_PRESERVE);
451 Grammar g = parseGrammar(null);
452 if (peekToken() == LC) {
453 g.action = new JSFunction(sourceName, parserLine, null);
454 parseBlock((JSFunction)g.action);
455 ((JSFunction)g.action).add(parserLine, LITERAL, null); // in case we "fall out the bottom", return NULL
456 ((JSFunction)g.action).add(parserLine, RETURN);
458 b.add(parserLine, MAKE_GRAMMAR, g);
459 b.add(parserLine, PUT);
463 case ASSIGN_BITOR: case ASSIGN_BITXOR: case ASSIGN_BITAND: case ASSIGN_LSH: case ASSIGN_RSH: case ASSIGN_URSH:
464 case ASSIGN_MUL: case ASSIGN_DIV: case ASSIGN_MOD: case ASSIGN_ADD: case ASSIGN_SUB: case ADD_TRAP: case DEL_TRAP: {
465 if (tok != ADD_TRAP && tok != DEL_TRAP)
466 b.add(parserLine, varKey == null ? GET_PRESERVE : SCOPEGET, varKey);
468 startExpr(b, precedence[tok]);
470 if (tok != ADD_TRAP && tok != DEL_TRAP) {
471 // tok-1 is always s/^ASSIGN_// (0 is BITOR, 1 is ASSIGN_BITOR, etc)
472 b.add(parserLine, tok - 1, tok-1==ADD ? JS.N(2) : null);
474 b.add(parserLine, PUT);
475 b.add(parserLine, SWAP);
476 b.add(parserLine, POP);
478 b.add(parserLine, SCOPEPUT, varKey);
481 if(varKey != null) throw pe("cannot place traps on local variables");
482 b.add(parserLine, tok);
486 case INC: case DEC: { // postfix
488 b.add(parserLine, GET_PRESERVE, Boolean.TRUE);
489 b.add(parserLine, LITERAL, JS.N(1));
490 b.add(parserLine, tok == INC ? ADD : SUB, JS.N(2));
491 b.add(parserLine, PUT, null);
492 b.add(parserLine, SWAP, null);
493 b.add(parserLine, POP, null);
494 b.add(parserLine, LITERAL, JS.N(1));
495 b.add(parserLine, tok == INC ? SUB : ADD, JS.N(2)); // undo what we just did, since this is postfix
497 b.add(parserLine, SCOPEGET, varKey);
498 b.add(parserLine, DUP);
499 b.add(parserLine, LITERAL, JS.ONE);
500 b.add(parserLine, tok == INC ? ADD : SUB, JS.N(2));
501 b.add(parserLine, SCOPEPUT, varKey);
506 startExpr(b, precedence[tok]);
508 b.add(parserLine, PUT);
509 b.add(parserLine, SWAP);
510 b.add(parserLine, POP);
512 b.add(parserLine, SCOPEPUT, varKey);
517 // Method calls are implemented by doing a GET_PRESERVE
518 // first. If the object supports method calls, it will
520 b.add(parserLine, varKey == null ? GET_PRESERVE : SCOPEGET, varKey);
521 int n = parseArgs(b);
522 b.add(parserLine, varKey == null ? CALLMETHOD : CALL, JS.N(n));
528 b.add(parserLine, SCOPEGET, varKey);
529 else if(b.get(b.size-1) == LITERAL && b.getArg(b.size-1) != null)
530 b.set(b.size-1,GET,b.getArg(b.size-1));
532 b.add(parserLine, GET);
540 * Assuming that a complete expression has just been parsed,
541 * <tt>continueExpr</tt> will attempt to extend this expression by
542 * parsing additional tokens and appending additional bytecodes.
544 * No operators with precedence less than <tt>minPrecedence</tt>
547 * If any bytecodes are appended, they will not alter the stack
550 private void continueExpr(JSFunction b, int minPrecedence) throws IOException {
551 int saveParserLine = parserLine;
552 _continueExpr(b, minPrecedence);
553 parserLine = saveParserLine;
555 private void _continueExpr(JSFunction b, int minPrecedence) throws IOException {
556 if (b == null) throw new Error("got null b; this should never happen");
557 int tok = getToken();
558 if (tok == -1) return;
559 if (minPrecedence != -1 && (precedence[tok] < minPrecedence || (precedence[tok] == minPrecedence && !isRightAssociative[tok]))) {
565 case LP: { // invocation (not grouping)
566 int n = parseArgs(b);
567 b.add(parserLine, CALL, JS.N(n));
570 case BITOR: case BITXOR: case BITAND: case SHEQ: case SHNE: case LSH:
571 case RSH: case URSH: case MUL: case DIV: case MOD:
572 case GT: case GE: case EQ: case NE: case LT: case LE: case SUB: {
573 startExpr(b, precedence[tok]);
574 b.add(parserLine, tok);
581 startExpr(b,precedence[tok]);
583 nextTok = getToken();
584 } while(nextTok == tok);
586 b.add(parserLine, tok, JS.N(count));
590 b.add(parserLine, tok == AND ? JSFunction.JF : JSFunction.JT, JS.ZERO); // test to see if we can short-circuit
592 startExpr(b, precedence[tok]); // otherwise check the second value
593 b.add(parserLine, JMP, JS.N(2)); // leave the second value on the stack and jump to the end
594 b.add(parserLine, LITERAL, tok == AND ?
595 JS.B(false) : JS.B(true)); // target of the short-circuit jump is here
596 b.set(size - 1, JS.N(b.size - size)); // write the target of the short-circuit jump
600 // support foo..bar syntax for foo[""].bar
601 if (peekToken() == DOT) {
606 b.add(parserLine, LITERAL, JSString.intern(string));
607 continueExprAfterAssignable(b,minPrecedence,null);
610 case LB: { // subscripting (not array constructor)
613 continueExprAfterAssignable(b,minPrecedence,null);
617 b.add(parserLine, JF, JS.ZERO); // jump to the if-false expression
619 startExpr(b, minPrecedence); // write the if-true expression
620 b.add(parserLine, JMP, JS.ZERO); // if true, jump *over* the if-false expression
621 b.set(size - 1, JS.N(b.size - size + 1)); // now we know where the target of the jump is
624 startExpr(b, minPrecedence); // write the if-false expression
625 b.set(size - 1, JS.N(b.size - size + 1)); // this is the end; jump to here
629 // pop the result of the previous expression, it is ignored
630 b.add(parserLine,POP);
640 continueExpr(b, minPrecedence); // try to continue the expression
643 // parse a set of comma separated function arguments, assume LP has already been consumed
644 private int parseArgs(JSFunction b) throws IOException {
646 while(peekToken() != RP) {
648 if (peekToken() != COMMA) {
649 startExpr(b, NO_COMMA);
650 if (peekToken() == RP) break;
658 /** Parse a block of statements which must be surrounded by LC..RC. */
659 void parseBlock(JSFunction b) throws IOException { parseBlock(b, null); }
660 void parseBlock(JSFunction b, String label) throws IOException {
661 int saveParserLine = parserLine;
662 _parseBlock(b, label);
663 parserLine = saveParserLine;
665 void _parseBlock(JSFunction b, String label) throws IOException {
666 if (peekToken() == -1) return;
667 else if (peekToken() != LC) parseStatement(b, null);
670 while(peekToken() != RC && peekToken() != -1) parseStatement(b, null);
675 /** Parse a single statement, consuming the RC or SEMI which terminates it. */
676 void parseStatement(JSFunction b, String label) throws IOException {
677 int saveParserLine = parserLine;
678 _parseStatement(b, label);
679 parserLine = saveParserLine;
681 void _parseStatement(JSFunction b, String label) throws IOException {
682 int tok = peekToken();
683 if (tok == -1) return;
684 switch(tok = getToken()) {
686 case THROW: case ASSERT: case RETURN: {
687 if (tok == RETURN && peekToken() == SEMI)
688 b.add(parserLine, LITERAL, null);
691 b.add(parserLine, tok);
695 case BREAK: case CONTINUE: {
696 if (peekToken() == NAME) consume(NAME);
697 b.add(parserLine, tok, string);
706 if (peekToken() == ASSIGN) { // if there is an '=' after the variable name
708 startExpr(b, NO_COMMA);
709 b.add(parserLine, SCOPEPUT, scopeKey(var)); // assign it
710 b.add(parserLine, POP); // clean the stack
712 if (peekToken() != COMMA) break;
715 if ((mostRecentlyReadToken != RC || peekToken() == SEMI) && peekToken() != -1 && mostRecentlyReadToken != SEMI) consume(SEMI);
723 b.add(parserLine, JF, JS.ZERO); // if false, jump to the else-block
725 parseStatement(b, null);
727 if (peekToken() == ELSE) {
729 b.add(parserLine, JMP, JS.ZERO); // if we took the true-block, jump over the else-block
730 b.set(size - 1, JS.N(b.size - size + 1));
732 parseStatement(b, null);
734 b.set(size - 1, JS.N(b.size - size + 1)); // regardless of which branch we took, b[size] needs to point here
739 if (label != null) b.add(parserLine, LABEL, label);
740 b.add(parserLine, LOOP);
742 b.add(parserLine, POP); // discard the first-iteration indicator
744 b.add(parserLine, JT, JS.N(2)); // if the while() clause is true, jump over the BREAK
745 b.add(parserLine, BREAK);
747 parseStatement(b, null);
748 b.add(parserLine, CONTINUE); // if we fall out of the end, definately continue
749 b.set(size - 1, JS.N(b.size - size + 1)); // end of the loop
754 if (label != null) b.add(parserLine, LABEL, label);
755 b.add(parserLine, LOOP);
761 if (peekToken() == CASE) { // we compile CASE statements like a bunch of if..else's
763 b.add(parserLine, DUP); // duplicate the switch() value; we'll consume one copy
766 b.add(parserLine, EQ); // check if we should do this case-block
767 b.add(parserLine, JF, JS.ZERO); // if not, jump to the next one
769 while(peekToken() != CASE && peekToken() != DEFAULT && peekToken() != RC) parseStatement(b, null);
770 b.set(size - 1, JS.N(1 + b.size - size));
771 } else if (peekToken() == DEFAULT) {
774 while(peekToken() != CASE && peekToken() != DEFAULT && peekToken() != RC) parseStatement(b, null);
775 } else if (peekToken() == RC) {
777 b.add(parserLine, BREAK); // break out of the loop if we 'fall through'
780 throw pe("expected CASE, DEFAULT, or RC; got " + codeToString[peekToken()]);
782 b.set(size0 - 1, JS.N(b.size - size0 + 1)); // end of the loop
787 if (label != null) b.add(parserLine, LABEL, label);
788 b.add(parserLine, LOOP);
790 parseStatement(b, null);
794 b.add(parserLine, JT, JS.N(2)); // check the while() clause; jump over the BREAK if true
795 b.add(parserLine, BREAK);
796 b.add(parserLine, CONTINUE);
799 b.set(size - 1, JS.N(b.size - size + 1)); // end of the loop; write this location to the LOOP instruction
804 b.add(parserLine, TRY); // try bytecode causes a TryMarker to be pushed
805 int tryInsn = b.size - 1;
806 // parse the expression to be TRYed
807 parseStatement(b, null);
808 // pop the try marker. this is pushed when the TRY bytecode is executed
809 b.add(parserLine, POP);
810 // jump forward to the end of the catch block, start of the finally block
811 b.add(parserLine, JMP);
812 int successJMPInsn = b.size - 1;
814 if (peekToken() != CATCH && peekToken() != FINALLY)
815 throw pe("try without catch or finally");
817 int catchJMPDistance = -1;
818 if (peekToken() == CATCH) {
819 Vec catchEnds = new Vec();
820 boolean catchAll = false;
822 catchJMPDistance = b.size - tryInsn;
824 while(peekToken() == CATCH && !catchAll) {
829 exceptionVar = string;
830 int[] writebacks = new int[] { -1, -1, -1 };
831 if (peekToken() != RP) {
832 // extended Ibex catch block: catch(e faultCode "foo.bar.baz")
834 b.add(parserLine, DUP);
835 b.add(parserLine, LITERAL, JSString.intern(string));
836 b.add(parserLine, GET);
837 b.add(parserLine, DUP);
838 b.add(parserLine, LITERAL, null);
839 b.add(parserLine, EQ);
840 b.add(parserLine, JT);
841 writebacks[0] = b.size - 1;
842 if (peekToken() == STRING) {
844 b.add(parserLine, DUP);
845 b.add(parserLine, LITERAL, string);
846 b.add(parserLine, LT);
847 b.add(parserLine, JT);
848 writebacks[1] = b.size - 1;
849 b.add(parserLine, DUP);
850 b.add(parserLine, LITERAL, string + "/"); // (slash is ASCII after dot)
851 b.add(parserLine, GE);
852 b.add(parserLine, JT);
853 writebacks[2] = b.size - 1;
856 b.add(parserLine, DUP);
857 b.add(parserLine, LITERAL, number);
858 b.add(parserLine, EQ);
859 b.add(parserLine, JF);
860 writebacks[1] = b.size - 1;
862 b.add(parserLine, POP); // pop the element thats on the stack from the compare
867 // the exception is on top of the stack; put it to the chosen name
869 scopeDeclare(exceptionVar);
870 b.add(parserLine, SCOPEPUT, scopeKey(exceptionVar));
871 b.add(parserLine, POP);
875 b.add(parserLine, JMP);
876 catchEnds.addElement(new Integer(b.size-1));
878 for(int i=0; i<3; i++) if (writebacks[i] != -1) b.set(writebacks[i], JS.N(b.size-writebacks[i]));
879 b.add(parserLine, POP); // pop the element thats on the stack from the compare
883 b.add(parserLine, THROW);
885 for(int i=0;i<catchEnds.size();i++) {
886 int n = ((Integer)catchEnds.elementAt(i)).intValue();
887 b.set(n, JS.N(b.size-n));
890 // pop the try and catch markers
891 b.add(parserLine,POP);
892 b.add(parserLine,POP);
895 // jump here if no exception was thrown
896 b.set(successJMPInsn, JS.N(b.size - successJMPInsn));
898 int finallyJMPDistance = -1;
899 if (peekToken() == FINALLY) {
900 b.add(parserLine, LITERAL, null); // null FinallyData
901 finallyJMPDistance = b.size - tryInsn;
903 parseStatement(b, null);
904 b.add(parserLine,FINALLY_DONE);
907 // setup the TRY arguments
908 b.set(tryInsn, new int[] { catchJMPDistance, finallyJMPDistance });
917 boolean hadVar = false; // if it's a for..in, we ignore the VAR
918 if (tok == VAR) { hadVar = true; tok = getToken(); }
919 String varName = string;
920 boolean forIn = peekToken() == IN; // determine if this is a for..in loop or not
921 pushBackToken(tok, varName);
929 b.add(parserLine, PUSHKEYS);
932 b.add(parserLine, LOOP);
933 b.add(parserLine, POP);
935 b.add(parserLine,SWAP); // get the keys enumeration object on top
936 b.add(parserLine,DUP);
937 b.add(parserLine,GET,JS.S("hasMoreElements"));
939 b.add(parserLine,JT);
940 b.add(parserLine,SWAP);
941 b.add(parserLine,BREAK);
942 b.set(size2, JS.N(b.size - size2));
943 b.add(parserLine,DUP);
944 b.add(parserLine,GET,JS.S("nextElement"));
948 if(hadVar) scopeDeclare(varName);
949 JS varKey = scopeKey(varName);
952 b.add(parserLine,GLOBALSCOPE);
953 b.add(parserLine,SWAP);
954 b.add(parserLine, LITERAL, JSString.intern(varName));
955 b.add(parserLine,SWAP);
956 b.add(parserLine,PUT);
957 b.add(parserLine,POP);
959 b.add(parserLine, SCOPEPUT, varKey);
961 b.add(parserLine,POP); // pop the put'ed value
962 b.add(parserLine,SWAP); // put CallMarker back into place
964 parseStatement(b, null);
967 b.add(parserLine, CONTINUE);
968 // jump here on break
969 b.set(size, JS.N(b.size - size));
971 b.add(parserLine, POP);
973 if (hadVar) pushBackToken(VAR, null); // yeah, this actually matters
974 scopePush(b); // grab a fresh scope
976 parseStatement(b, null); // initializer
977 JSFunction e2 = // we need to put the incrementor before the test
978 new JSFunction(sourceName, parserLine, null); // so we save the test here
979 if (peekToken() != SEMI)
982 e2.add(parserLine, JSFunction.LITERAL, JS.T); // handle the for(foo;;foo) case
984 if (label != null) b.add(parserLine, LABEL, label);
985 b.add(parserLine, LOOP);
988 b.add(parserLine, JT, JS.ZERO); // if we're on the first iteration, jump over the incrementor
990 if (peekToken() != RP) { // do the increment thing
992 b.add(parserLine, POP);
994 b.set(size - 1, JS.N(b.size - size + 1));
997 b.paste(e2); // ok, *now* test if we're done yet
998 b.add(parserLine, JT, JS.N(2)); // break out if we don't meet the test
999 b.add(parserLine, BREAK);
1000 parseStatement(b, null);
1001 b.add(parserLine, CONTINUE); // if we fall out the bottom, CONTINUE
1002 b.set(size2 - 1, JS.N(b.size - size2 + 1)); // end of the loop
1004 scopePop(b); // get our scope back
1009 case NAME: { // either a label or an identifier; this is the one place we're not LL(1)
1010 String possiblyTheLabel = string;
1011 if (peekToken() == COLON) { // label
1013 parseStatement(b, possiblyTheLabel);
1015 } else { // expression
1016 pushBackToken(NAME, possiblyTheLabel);
1018 b.add(parserLine, POP);
1019 if ((mostRecentlyReadToken != RC || peekToken() == SEMI) && peekToken() != -1 && mostRecentlyReadToken != SEMI) consume(SEMI);
1024 case SEMI: return; // yep, the null statement is valid
1026 case LC: { // blocks are statements too
1029 parseBlock(b, label);
1034 default: { // hope that it's an expression
1037 b.add(parserLine, POP);
1038 if ((mostRecentlyReadToken != RC || peekToken() == SEMI) && peekToken() != -1 && mostRecentlyReadToken != SEMI) consume(SEMI);
1045 // ParserException //////////////////////////////////////////////////////////////////////
1046 private IOException pe(String s) { return new IOException(sourceName + ":" + line + " " + s); }