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.
9 import org.ibex.util.*;
12 * Parses a stream of lexed tokens into a tree of JSFunction's.
14 * There are three kinds of things we parse: blocks, statements, and
17 * - Expressions are a special type of statement that evaluates to a
18 * value (for example, "break" is not an expression, * but "3+2"
19 * is). Some tokens sequences start expressions (for * example,
20 * literal numbers) and others continue an expression which * has
21 * already been begun (for example, '+'). Finally, some *
22 * expressions are valid targets for an assignment operation; after
23 * * each of these expressions, continueExprAfterAssignable() is
24 * called * to check for an assignment operation.
26 * - A statement ends with a semicolon and does not return a value.
28 * - A block is a single statement or a sequence of statements
29 * surrounded by curly braces.
31 * Each parsing method saves the parserLine before doing its actual
32 * work and restores it afterwards. This ensures that parsing a
33 * subexpression does not modify the line number until a token
34 * *after* the subexpression has been consumed by the parent
37 * Technically it would be a better design for this class to build an
38 * intermediate parse tree and use that to emit bytecode. Here's the
41 * Advantages of building a parse tree:
42 * - easier to apply optimizations
43 * - would let us handle more sophisticated languages than JavaScript
45 * Advantages of leaving out the parse tree
46 * - faster compilation
47 * - less load on the garbage collector
48 * - much simpler code, easier to understand
51 * Fortunately JS is such a simple language that we can get away with
52 * the half-assed approach and still produce a working, complete
55 * The bytecode language emitted doesn't really cause any appreciable
56 * semantic loss, and is itself a parseable language very similar to
57 * Forth or a postfix variant of LISP. This means that the bytecode
58 * can be transformed into a parse tree, which can be manipulated.
59 * So if we ever want to add an optimizer, it could easily be done by
60 * producing a parse tree from the bytecode, optimizing that tree,
61 * and then re-emitting the bytecode. The parse tree node class
62 * would also be much simpler since the bytecode language has so few
65 * Actually, the above paragraph is slightly inaccurate -- there are
66 * places where we push a value and then perform an arbitrary number
67 * of operations using it before popping it; this doesn't parse well.
68 * But these cases are clearly marked and easy to change if we do
69 * need to move to a parse tree format.
71 class Parser extends Lexer implements ByteCodes {
74 // Constructors //////////////////////////////////////////////////////
76 private Parser(Reader r, String sourceName, int line) throws IOException { super(r, sourceName, line); }
79 public static void main(String[] s) throws IOException {
80 JS block = JSU.fromReader("stdin", 0, new InputStreamReader(System.in));
81 if (block == null) return;
82 System.out.println(block);
85 // Statics ////////////////////////////////////////////////////////////
87 static byte[] precedence = new byte[MAX_TOKEN + 1];
88 static boolean[] isRightAssociative = new boolean[MAX_TOKEN + 1];
89 // Use this as the precedence when we want anything up to the comma
90 private final static int NO_COMMA = 2;
92 isRightAssociative[ASSIGN] =
93 isRightAssociative[ASSIGN_BITOR] =
94 isRightAssociative[ASSIGN_BITXOR] =
95 isRightAssociative[ASSIGN_BITAND] =
96 isRightAssociative[ASSIGN_LSH] =
97 isRightAssociative[ASSIGN_RSH] =
98 isRightAssociative[ASSIGN_URSH] =
99 isRightAssociative[ASSIGN_ADD] =
100 isRightAssociative[ASSIGN_SUB] =
101 isRightAssociative[ASSIGN_MUL] =
102 isRightAssociative[ASSIGN_DIV] =
103 isRightAssociative[ASSIGN_MOD] =
104 isRightAssociative[ADD_TRAP] =
105 isRightAssociative[DEL_TRAP] =
108 precedence[COMMA] = 1;
109 // 2 is intentionally left unassigned. we use minPrecedence==2 for comma separated lists
111 precedence[ASSIGN_BITOR] =
112 precedence[ASSIGN_BITXOR] =
113 precedence[ASSIGN_BITAND] =
114 precedence[ASSIGN_LSH] =
115 precedence[ASSIGN_RSH] =
116 precedence[ASSIGN_URSH] =
117 precedence[ASSIGN_ADD] =
118 precedence[ASSIGN_SUB] =
119 precedence[ASSIGN_MUL] =
120 precedence[ASSIGN_DIV] =
121 precedence[ADD_TRAP] =
122 precedence[DEL_TRAP] =
123 precedence[ASSIGN_MOD] = 3;
124 precedence[HOOK] = 4;
127 precedence[BITOR] = 7;
128 precedence[BITXOR] = 8;
129 precedence[BITAND] = 9;
130 precedence[EQ] = precedence[NE] = precedence[SHEQ] = precedence[SHNE] = 10;
131 precedence[LT] = precedence[LE] = precedence[GT] = precedence[GE] = 11;
132 precedence[LSH] = precedence[RSH] = precedence[URSH] = 12;
133 precedence[ADD] = precedence[SUB] = 12;
134 precedence[MUL] = precedence[DIV] = precedence[MOD] = 13;
135 precedence[BITNOT] = precedence[BANG] = precedence[TYPEOF] = 14;
136 precedence[DOT] = precedence[LB] = precedence[LP] = precedence[INC] = precedence[DEC] = 15;
139 // Local variable management
140 Basket.Array scopeStack = new Basket.Array();
141 static class ScopeInfo {
145 Map mapping = new HashMap();
147 Map globalCache = new HashMap();
148 JS scopeKey(String name) {
149 if(globalCache.get(name) != null) return null;
150 for(int i=scopeStack.size()-1;i>=0;i--) {
151 JS key = (JS)((ScopeInfo) scopeStack.get(i)).mapping.get(name);
152 if(key != null) return key;
154 globalCache.put(name,Boolean.TRUE);
157 void scopeDeclare(String name) throws IOException {
158 ScopeInfo si = (ScopeInfo) scopeStack.peek();
159 if(si.mapping.get(name) != null) throw pe("" + name + " already declared in this scope");
160 si.mapping.put(name,JSU.N(si.end++));
161 globalCache.put(name,null);
163 void scopePush(JSFunction b) {
164 ScopeInfo prev = (ScopeInfo) scopeStack.peek();
165 ScopeInfo si = new ScopeInfo();
168 si.newScopeInsn = b.size;
170 b.add(parserLine, NEWSCOPE);
172 void scopePop(JSFunction b) {
173 ScopeInfo si = (ScopeInfo) scopeStack.pop();
174 b.add(parserLine, OLDSCOPE);
175 b.set(si.newScopeInsn,JSU.N((si.base<<16)|((si.end-si.base)<<0)));
179 // Parsing Logic /////////////////////////////////////////////////////////
181 /** parse and compile a function */
182 public static JSFunction fromReader(String sourceName, int firstLine, Reader sourceCode) throws IOException {
183 JSFunction ret = new JSFunction(sourceName, firstLine, null);
184 if (sourceCode == null) return ret;
185 Parser p = new Parser(sourceCode, sourceName, firstLine);
186 p.scopeStack.clear();
187 p.scopeStack.push(new ScopeInfo());
191 if(p.peekToken() == -1) break; // FIXME: Check this logic one more time
192 p.parseStatement(ret, null);
193 //if (s == ret.size) break;
196 if(p.scopeStack.size() != 1) throw new Error("scopeStack height mismatch");
197 ret.add(-1, LITERAL, null);
202 /** gets a token and throws an exception if it is not <tt>code</tt> */
203 private void consume(int code) throws IOException {
204 if (getToken() != code) {
205 if(code == NAME) switch(op) {
206 case RETURN: case TYPEOF: case BREAK: case CONTINUE: case TRY: case THROW:
207 case ASSERT: case NULL: case TRUE: case FALSE: case IN: case IF: case ELSE:
208 case SWITCH: case CASE: case DEFAULT: case WHILE: case VAR: case WITH:
209 case CATCH: case FINALLY:
210 throw pe("Bad variable name; '" + codeToString[op].toLowerCase() + "' is a javascript keyword");
212 throw pe("expected " + codeToString[code] + ", got " + (op == -1 ? "EOF" : codeToString[op]));
217 * Parse the largest possible expression containing no operators
218 * of precedence below <tt>minPrecedence</tt> and append the
219 * bytecodes for that expression to <tt>appendTo</tt>; the
220 * appended bytecodes MUST grow the stack by exactly one element.
222 private void startExpr(JSFunction appendTo, int minPrecedence) throws IOException {
223 int saveParserLine = parserLine;
224 _startExpr(appendTo, minPrecedence);
225 parserLine = saveParserLine;
227 private void _startExpr(JSFunction appendTo, int minPrecedence) throws IOException {
228 int tok = getToken();
229 JSFunction b = appendTo;
232 case -1: throw pe("expected expression");
234 // all of these simply push values onto the stack
235 case NUMBER: b.add(parserLine, LITERAL, JSU.N(number)); break;
236 case STRING: b.add(parserLine, LITERAL, JSString.intern(string)); break;
237 case NULL: b.add(parserLine, LITERAL, null); break;
238 case TRUE: case FALSE: b.add(parserLine, LITERAL, tok == TRUE ? JSU.T : JSU.F); break;
243 b.add(parserLine, GLOBALSCOPE);
244 b.add(parserLine, GET, JSU.S("",true));
245 b.add(parserLine, LITERAL, JSU.S(string,true));
246 continueExprAfterAssignable(b,minPrecedence,null);
251 b.add(parserLine, ARRAY, JSU.ZERO); // push an array onto the stack
254 if (peekToken() != RB)
255 while(true) { // iterate over the initialization values
256 b.add(parserLine, LITERAL, JSU.N(i++)); // push the index in the array to place it into
257 if (peekToken() == COMMA || peekToken() == RB)
258 b.add(parserLine, LITERAL, null); // for stuff like [1,,2,]
260 startExpr(b, NO_COMMA); // push the value onto the stack
261 b.add(parserLine, PUT); // put it into the array
262 b.add(parserLine, POP); // discard the value remaining on the stack
263 if (peekToken() == RB) break;
266 b.set(size0 - 1, JSU.N(i)); // back at the ARRAY instruction, write the size of the array
270 case SUB: case ADD: {
271 if(peekToken() == NUMBER) { // literal
273 b.add(parserLine, LITERAL, JSU.N(number.doubleValue() * (tok == SUB ? -1 : 1)));
274 } else { // unary +/- operator
275 if(tok == SUB) b.add(parserLine, LITERAL, JSU.ZERO);
276 // BITNOT has the same precedence as the unary +/- operators
277 startExpr(b,precedence[BITNOT]);
278 if(tok == ADD) b.add(parserLine, LITERAL, JSU.ZERO); // HACK to force expr into a numeric context
279 b.add(parserLine, SUB);
283 case LP: { // grouping (not calling)
288 case INC: case DEC: { // prefix (not postfix)
289 startExpr(b, precedence[tok]);
290 int prev = b.size - 1;
291 boolean sg = b.get(prev) == SCOPEGET;
292 if (b.get(prev) == GET && b.getArg(prev) != null)
293 b.set(prev, LITERAL, b.getArg(prev));
294 else if(b.get(prev) == GET)
297 throw pe("prefixed increment/decrement can only be performed on a valid assignment target");
298 if(!sg) b.add(parserLine, GET_PRESERVE, Boolean.TRUE);
299 b.add(parserLine, LITERAL, JSU.N(1));
300 b.add(parserLine, tok == INC ? ADD : SUB, JSU.N(2));
302 b.add(parserLine, SCOPEPUT, b.getArg(prev));
304 b.add(parserLine, PUT, null);
305 b.add(parserLine, SWAP, null);
306 b.add(parserLine, POP, null);
310 case BANG: case BITNOT: case TYPEOF: {
311 startExpr(b, precedence[tok]);
312 b.add(parserLine, tok);
315 case LC: { // object constructor
316 b.add(parserLine, OBJECT, null); // put an object on the stack
317 if (peekToken() != RC)
319 if (peekToken() != NAME && peekToken() != STRING)
320 throw pe("expected NAME or STRING");
322 b.add(parserLine, LITERAL, JSString.intern(string)); // grab the key
324 startExpr(b, NO_COMMA); // grab the value
325 b.add(parserLine, PUT); // put the value into the object
326 b.add(parserLine, POP); // discard the remaining value
327 if (peekToken() == RC) break;
329 if (peekToken() == RC) break; // we permit {,,} -- I'm not sure if ECMA does
335 JS varKey = scopeKey(string);
337 b.add(parserLine, GLOBALSCOPE);
338 b.add(parserLine, LITERAL, JSString.intern(string));
340 continueExprAfterAssignable(b,minPrecedence,varKey);
344 if(peekToken() == ASSIGN) {
346 startExpr(b, precedence[ASSIGN]);
347 b.add(parserLine, CASCADE, JSU.T);
349 b.add(parserLine, CASCADE, JSU.F);
357 JSFunction b2 = new JSFunction(sourceName, parserLine, null);
358 b.add(parserLine, NEWFUNCTION, b2);
360 // function prelude; arguments array is already on the stack
362 scopeDeclare("arguments");
363 b2.add(parserLine, SCOPEPUT,scopeKey("arguments"));
365 while(peekToken() != RP) { // run through the list of argument names
367 if (peekToken() == NAME) {
368 consume(NAME); // a named argument
370 b2.add(parserLine, DUP); // dup the args array
371 b2.add(parserLine, GET, JSU.N(numArgs - 1)); // retrieve it from the arguments array
372 scopeDeclare(string);
373 b2.add(parserLine, SCOPEPUT, scopeKey(string));
374 b2.add(parserLine, POP);
376 if (peekToken() == RP) break;
381 b2.numFormalArgs = numArgs;
382 b2.add(parserLine, POP); // pop off the arguments array
384 if(peekToken() != LC)
385 throw pe("JSFunctions must have a block surrounded by curly brackets");
387 parseBlock(b2, null); // the function body
390 b2.add(parserLine, LITERAL, null); // in case we "fall out the bottom", return NULL
391 b2.add(parserLine, RETURN);
395 default: throw pe("expected expression, found " + codeToString[tok] + ", which cannot start an expression");
398 // attempt to continue the expression
399 continueExpr(b, minPrecedence);
403 * Assuming that a complete assignable (lvalue) has just been
404 * parsed and the object and key are on the stack,
405 * <tt>continueExprAfterAssignable</tt> will attempt to parse an
406 * expression that modifies the assignable. This method always
407 * decreases the stack depth by exactly one element.
409 private void continueExprAfterAssignable(JSFunction b,int minPrecedence, JS varKey) throws IOException {
410 int saveParserLine = parserLine;
411 _continueExprAfterAssignable(b,minPrecedence,varKey);
412 parserLine = saveParserLine;
414 private void _continueExprAfterAssignable(JSFunction b,int minPrecedence, JS varKey) throws IOException {
415 if (b == null) throw new Error("got null b; this should never happen");
416 int tok = getToken();
417 if (minPrecedence != -1 && (precedence[tok] < minPrecedence || (precedence[tok] == minPrecedence && !isRightAssociative[tok])))
418 // force the default case
421 case ASSIGN_BITOR: case ASSIGN_BITXOR: case ASSIGN_BITAND: case ASSIGN_LSH: case ASSIGN_RSH: case ASSIGN_URSH:
422 case ASSIGN_MUL: case ASSIGN_DIV: case ASSIGN_MOD: case ASSIGN_ADD: case ASSIGN_SUB: case ADD_TRAP: case DEL_TRAP: {
423 if (tok != ADD_TRAP && tok != DEL_TRAP)
424 b.add(parserLine, varKey == null ? GET_PRESERVE : SCOPEGET, varKey);
426 startExpr(b, precedence[tok]);
428 if (tok != ADD_TRAP && tok != DEL_TRAP) {
429 // tok-1 is always s/^ASSIGN_// (0 is BITOR, 1 is ASSIGN_BITOR, etc)
430 b.add(parserLine, tok - 1, tok-1==ADD ? JSU.N(2) : null);
432 b.add(parserLine, PUT);
433 b.add(parserLine, SWAP);
434 b.add(parserLine, POP);
436 b.add(parserLine, SCOPEPUT, varKey);
439 if(varKey != null) throw pe("cannot place traps on local variables");
440 b.add(parserLine, tok);
444 case INC: case DEC: { // postfix
446 b.add(parserLine, GET_PRESERVE, Boolean.TRUE);
447 b.add(parserLine, LITERAL, JSU.N(1));
448 b.add(parserLine, tok == INC ? ADD : SUB, JSU.N(2));
449 b.add(parserLine, PUT, null);
450 b.add(parserLine, SWAP, null);
451 b.add(parserLine, POP, null);
452 b.add(parserLine, LITERAL, JSU.N(1));
453 b.add(parserLine, tok == INC ? SUB : ADD, JSU.N(2)); // undo what we just did, since this is postfix
455 b.add(parserLine, SCOPEGET, varKey);
456 b.add(parserLine, DUP);
457 b.add(parserLine, LITERAL, JSU.ONE);
458 b.add(parserLine, tok == INC ? ADD : SUB, JSU.N(2));
459 b.add(parserLine, SCOPEPUT, varKey);
464 startExpr(b, precedence[tok]);
466 b.add(parserLine, PUT);
467 b.add(parserLine, SWAP);
468 b.add(parserLine, POP);
470 b.add(parserLine, SCOPEPUT, varKey);
475 // Method calls are implemented by doing a GET_PRESERVE
476 // first. If the object supports method calls, it will
478 b.add(parserLine, varKey == null ? GET_PRESERVE : SCOPEGET, varKey);
479 int n = parseArgs(b);
480 b.add(parserLine, varKey == null ? CALLMETHOD : CALL, JSU.N(n));
486 b.add(parserLine, SCOPEGET, varKey);
487 else if(b.get(b.size-1) == LITERAL && b.getArg(b.size-1) != null)
488 b.set(b.size-1,GET,b.getArg(b.size-1));
490 b.add(parserLine, GET);
498 * Assuming that a complete expression has just been parsed,
499 * <tt>continueExpr</tt> will attempt to extend this expression by
500 * parsing additional tokens and appending additional bytecodes.
502 * No operators with precedence less than <tt>minPrecedence</tt>
505 * If any bytecodes are appended, they will not alter the stack
508 private void continueExpr(JSFunction b, int minPrecedence) throws IOException {
509 int saveParserLine = parserLine;
510 _continueExpr(b, minPrecedence);
511 parserLine = saveParserLine;
513 private void _continueExpr(JSFunction b, int minPrecedence) throws IOException {
514 if (b == null) throw new Error("got null b; this should never happen");
515 int tok = getToken();
516 if (tok == -1) return;
517 if (minPrecedence != -1 && (precedence[tok] < minPrecedence || (precedence[tok] == minPrecedence && !isRightAssociative[tok]))) {
523 case LP: { // invocation (not grouping)
524 int n = parseArgs(b);
525 b.add(parserLine, CALL, JSU.N(n));
528 case BITOR: case BITXOR: case BITAND: case SHEQ: case SHNE: case LSH:
529 case RSH: case URSH: case MUL: case DIV: case MOD:
530 case GT: case GE: case EQ: case NE: case LT: case LE: case SUB: {
531 startExpr(b, precedence[tok]);
532 b.add(parserLine, tok);
539 startExpr(b,precedence[tok]);
541 nextTok = getToken();
542 } while(nextTok == tok);
544 b.add(parserLine, tok, JSU.N(count));
548 b.add(parserLine, tok == AND ? JSFunction.JF : JSFunction.JT, JSU.ZERO); // test to see if we can short-circuit
550 startExpr(b, precedence[tok]); // otherwise check the second value
551 b.add(parserLine, JMP, JSU.N(2)); // leave the second value on the stack and jump to the end
552 b.add(parserLine, LITERAL, tok == AND ?
553 JSU.B(false) : JSU.B(true)); // target of the short-circuit jump is here
554 b.set(size - 1, JSU.N(b.size - size)); // write the target of the short-circuit jump
558 // support foo..bar syntax for foo[""].bar
559 if (peekToken() == DOT) {
564 b.add(parserLine, LITERAL, JSString.intern(string));
565 continueExprAfterAssignable(b,minPrecedence,null);
568 case LB: { // subscripting (not array constructor)
571 continueExprAfterAssignable(b,minPrecedence,null);
575 b.add(parserLine, JF, JSU.ZERO); // jump to the if-false expression
577 startExpr(b, minPrecedence); // write the if-true expression
578 b.add(parserLine, JMP, JSU.ZERO); // if true, jump *over* the if-false expression
579 b.set(size - 1, JSU.N(b.size - size + 1)); // now we know where the target of the jump is
582 startExpr(b, minPrecedence); // write the if-false expression
583 b.set(size - 1, JSU.N(b.size - size + 1)); // this is the end; jump to here
587 // pop the result of the previous expression, it is ignored
588 b.add(parserLine,POP);
598 continueExpr(b, minPrecedence); // try to continue the expression
601 // parse a set of comma separated function arguments, assume LP has already been consumed
602 private int parseArgs(JSFunction b) throws IOException {
604 while(peekToken() != RP) {
606 if (peekToken() != COMMA) {
607 startExpr(b, NO_COMMA);
608 if (peekToken() == RP) break;
616 /** Parse a block of statements which must be surrounded by LC..RC. */
617 void parseBlock(JSFunction b) throws IOException { parseBlock(b, null); }
618 void parseBlock(JSFunction b, String label) throws IOException {
619 int saveParserLine = parserLine;
620 _parseBlock(b, label);
621 parserLine = saveParserLine;
623 void _parseBlock(JSFunction b, String label) throws IOException {
624 if (peekToken() == -1) return;
625 else if (peekToken() != LC) parseStatement(b, null);
628 while(peekToken() != RC && peekToken() != -1) parseStatement(b, null);
633 /** Parse a single statement, consuming the RC or SEMI which terminates it. */
634 void parseStatement(JSFunction b, String label) throws IOException {
635 int saveParserLine = parserLine;
636 _parseStatement(b, label);
637 parserLine = saveParserLine;
639 void _parseStatement(JSFunction b, String label) throws IOException {
640 int tok = peekToken();
641 if (tok == -1) return;
642 switch(tok = getToken()) {
644 case THROW: case ASSERT: case RETURN: {
645 if (tok == RETURN && peekToken() == SEMI)
646 b.add(parserLine, LITERAL, null);
649 b.add(parserLine, tok);
653 case BREAK: case CONTINUE: {
654 if (peekToken() == NAME) consume(NAME);
655 b.add(parserLine, tok, string);
664 if (peekToken() == ASSIGN) { // if there is an '=' after the variable name
666 startExpr(b, NO_COMMA);
667 b.add(parserLine, SCOPEPUT, scopeKey(var)); // assign it
668 b.add(parserLine, POP); // clean the stack
670 if (peekToken() != COMMA) break;
673 if ((mostRecentlyReadToken != RC || peekToken() == SEMI) && peekToken() != -1 && mostRecentlyReadToken != SEMI) consume(SEMI);
681 b.add(parserLine, JF, JSU.ZERO); // if false, jump to the else-block
683 parseStatement(b, null);
685 if (peekToken() == ELSE) {
687 b.add(parserLine, JMP, JSU.ZERO); // if we took the true-block, jump over the else-block
688 b.set(size - 1, JSU.N(b.size - size + 1));
690 parseStatement(b, null);
692 b.set(size - 1, JSU.N(b.size - size + 1)); // regardless of which branch we took, b[size] needs to point here
697 if (label != null) b.add(parserLine, LABEL, label);
698 b.add(parserLine, LOOP);
700 b.add(parserLine, POP); // discard the first-iteration indicator
702 b.add(parserLine, JT, JSU.N(2)); // if the while() clause is true, jump over the BREAK
703 b.add(parserLine, BREAK);
705 parseStatement(b, null);
706 b.add(parserLine, CONTINUE); // if we fall out of the end, definately continue
707 b.set(size - 1, JSU.N(b.size - size + 1)); // end of the loop
712 if (label != null) b.add(parserLine, LABEL, label);
713 b.add(parserLine, LOOP);
719 if (peekToken() == CASE) { // we compile CASE statements like a bunch of if..else's
721 b.add(parserLine, DUP); // duplicate the switch() value; we'll consume one copy
724 b.add(parserLine, EQ); // check if we should do this case-block
725 b.add(parserLine, JF, JSU.ZERO); // if not, jump to the next one
727 while(peekToken() != CASE && peekToken() != DEFAULT && peekToken() != RC) parseStatement(b, null);
728 b.set(size - 1, JSU.N(1 + b.size - size));
729 } else if (peekToken() == DEFAULT) {
732 while(peekToken() != CASE && peekToken() != DEFAULT && peekToken() != RC) parseStatement(b, null);
733 } else if (peekToken() == RC) {
735 b.add(parserLine, BREAK); // break out of the loop if we 'fall through'
738 throw pe("expected CASE, DEFAULT, or RC; got " + codeToString[peekToken()]);
740 b.set(size0 - 1, JSU.N(b.size - size0 + 1)); // end of the loop
745 if (label != null) b.add(parserLine, LABEL, label);
746 b.add(parserLine, LOOP);
748 parseStatement(b, null);
752 b.add(parserLine, JT, JSU.N(2)); // check the while() clause; jump over the BREAK if true
753 b.add(parserLine, BREAK);
754 b.add(parserLine, CONTINUE);
757 b.set(size - 1, JSU.N(b.size - size + 1)); // end of the loop; write this location to the LOOP instruction
762 b.add(parserLine, TRY); // try bytecode causes a TryMarker to be pushed
763 int tryInsn = b.size - 1;
764 // parse the expression to be TRYed
765 parseStatement(b, null);
766 // pop the try marker. this is pushed when the TRY bytecode is executed
767 b.add(parserLine, POP);
768 // jump forward to the end of the catch block, start of the finally block
769 b.add(parserLine, JMP);
770 int successJMPInsn = b.size - 1;
772 if (peekToken() != CATCH && peekToken() != FINALLY)
773 throw pe("try without catch or finally");
775 int catchJMPDistance = -1;
776 if (peekToken() == CATCH) {
777 Basket.List catchEnds = new Basket.Array();
778 boolean catchAll = false;
780 catchJMPDistance = b.size - tryInsn;
782 while(peekToken() == CATCH && !catchAll) {
787 exceptionVar = string;
788 int[] writebacks = new int[] { -1, -1, -1 };
789 if (peekToken() != RP) {
790 // extended Ibex catch block: catch(e faultCode "foo.bar.baz")
792 b.add(parserLine, DUP);
793 b.add(parserLine, LITERAL, JSString.intern(string));
794 b.add(parserLine, GET);
795 b.add(parserLine, DUP);
796 b.add(parserLine, LITERAL, null);
797 b.add(parserLine, EQ);
798 b.add(parserLine, JT);
799 writebacks[0] = b.size - 1;
800 if (peekToken() == STRING) {
802 b.add(parserLine, DUP);
803 b.add(parserLine, LITERAL, string);
804 b.add(parserLine, LT);
805 b.add(parserLine, JT);
806 writebacks[1] = b.size - 1;
807 b.add(parserLine, DUP);
808 b.add(parserLine, LITERAL, string + "/"); // (slash is ASCII after dot)
809 b.add(parserLine, GE);
810 b.add(parserLine, JT);
811 writebacks[2] = b.size - 1;
814 b.add(parserLine, DUP);
815 b.add(parserLine, LITERAL, number);
816 b.add(parserLine, EQ);
817 b.add(parserLine, JF);
818 writebacks[1] = b.size - 1;
820 b.add(parserLine, POP); // pop the element thats on the stack from the compare
825 // the exception is on top of the stack; put it to the chosen name
827 scopeDeclare(exceptionVar);
828 b.add(parserLine, SCOPEPUT, scopeKey(exceptionVar));
829 b.add(parserLine, POP);
833 b.add(parserLine, JMP);
834 catchEnds.add(new Integer(b.size-1));
836 for(int i=0; i<3; i++) if (writebacks[i] != -1) b.set(writebacks[i], JSU.N(b.size-writebacks[i]));
837 b.add(parserLine, POP); // pop the element thats on the stack from the compare
841 b.add(parserLine, THROW);
843 for(int i=0;i<catchEnds.size();i++) {
844 int n = ((Integer)catchEnds.get(i)).intValue();
845 b.set(n, JSU.N(b.size-n));
848 // pop the try and catch markers
849 b.add(parserLine,POP);
850 b.add(parserLine,POP);
853 // jump here if no exception was thrown
854 b.set(successJMPInsn, JSU.N(b.size - successJMPInsn));
856 int finallyJMPDistance = -1;
857 if (peekToken() == FINALLY) {
858 b.add(parserLine, LITERAL, null); // null FinallyData
859 finallyJMPDistance = b.size - tryInsn;
861 parseStatement(b, null);
862 b.add(parserLine,FINALLY_DONE);
865 // setup the TRY arguments
866 b.set(tryInsn, new int[] { catchJMPDistance, finallyJMPDistance });
875 boolean hadVar = false; // if it's a for..in, we ignore the VAR
876 if (tok == VAR) { hadVar = true; tok = getToken(); }
877 String varName = string;
878 boolean forIn = peekToken() == IN; // determine if this is a for..in loop or not
879 pushBackToken(tok, varName);
887 b.add(parserLine, PUSHKEYS);
890 b.add(parserLine, LOOP);
891 b.add(parserLine, POP);
893 b.add(parserLine,SWAP); // get the keys enumeration object on top
894 b.add(parserLine,DUP);
895 b.add(parserLine,GET,JSU.S("hasMoreElements"));
897 b.add(parserLine,JT);
898 b.add(parserLine,SWAP);
899 b.add(parserLine,BREAK);
900 b.set(size2, JSU.N(b.size - size2));
901 b.add(parserLine,DUP);
902 b.add(parserLine,GET,JSU.S("nextElement"));
906 if(hadVar) scopeDeclare(varName);
907 JS varKey = scopeKey(varName);
910 b.add(parserLine,GLOBALSCOPE);
911 b.add(parserLine,SWAP);
912 b.add(parserLine, LITERAL, JSString.intern(varName));
913 b.add(parserLine,SWAP);
914 b.add(parserLine,PUT);
915 b.add(parserLine,POP);
917 b.add(parserLine, SCOPEPUT, varKey);
919 b.add(parserLine,POP); // pop the put'ed value
920 b.add(parserLine,SWAP); // put CallMarker back into place
922 parseStatement(b, null);
925 b.add(parserLine, CONTINUE);
926 // jump here on break
927 b.set(size, JSU.N(b.size - size));
929 b.add(parserLine, POP);
931 if (hadVar) pushBackToken(VAR, null); // yeah, this actually matters
932 scopePush(b); // grab a fresh scope
934 parseStatement(b, null); // initializer
935 JSFunction e2 = // we need to put the incrementor before the test
936 new JSFunction(sourceName, parserLine, null); // so we save the test here
937 if (peekToken() != SEMI)
940 e2.add(parserLine, JSFunction.LITERAL, JSU.T); // handle the for(foo;;foo) case
942 if (label != null) b.add(parserLine, LABEL, label);
943 b.add(parserLine, LOOP);
946 b.add(parserLine, JT, JSU.ZERO); // if we're on the first iteration, jump over the incrementor
948 if (peekToken() != RP) { // do the increment thing
950 b.add(parserLine, POP);
952 b.set(size - 1, JSU.N(b.size - size + 1));
955 b.paste(e2); // ok, *now* test if we're done yet
956 b.add(parserLine, JT, JSU.N(2)); // break out if we don't meet the test
957 b.add(parserLine, BREAK);
958 parseStatement(b, null);
959 b.add(parserLine, CONTINUE); // if we fall out the bottom, CONTINUE
960 b.set(size2 - 1, JSU.N(b.size - size2 + 1)); // end of the loop
962 scopePop(b); // get our scope back
967 case NAME: { // either a label or an identifier; this is the one place we're not LL(1)
968 String possiblyTheLabel = string;
969 if (peekToken() == COLON) { // label
971 parseStatement(b, possiblyTheLabel);
973 } else { // expression
974 pushBackToken(NAME, possiblyTheLabel);
976 b.add(parserLine, POP);
977 if ((mostRecentlyReadToken != RC || peekToken() == SEMI) && peekToken() != -1 && mostRecentlyReadToken != SEMI) consume(SEMI);
982 case SEMI: return; // yep, the null statement is valid
984 case LC: { // blocks are statements too
987 parseBlock(b, label);
992 default: { // hope that it's an expression
995 b.add(parserLine, POP);
996 if ((mostRecentlyReadToken != RC || peekToken() == SEMI) && peekToken() != -1 && mostRecentlyReadToken != SEMI) consume(SEMI);
1003 // ParserException //////////////////////////////////////////////////////////////////////
1004 private IOException pe(String s) { return new IOException(sourceName + ":" + line + " " + s); }