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 = JS.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,JS.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,JS.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, JS.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 ? JS.T : JS.F); break;
243 b.add(parserLine, GLOBALSCOPE);
244 b.add(parserLine, GET, JS.S("",true));
245 b.add(parserLine, LITERAL, JS.S(string,true));
246 continueExprAfterAssignable(b,minPrecedence,null);
251 b.add(parserLine, ARRAY, JS.ZERO); // push an array onto the stack
254 if (peekToken() != RB)
255 while(true) { // iterate over the initialization values
256 b.add(parserLine, LITERAL, JS.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, JS.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, JS.N(number.doubleValue() * (tok == SUB ? -1 : 1)));
274 } else { // unary +/- operator
275 if(tok == SUB) b.add(parserLine, LITERAL, JS.ZERO);
276 // BITNOT has the same precedence as the unary +/- operators
277 startExpr(b,precedence[BITNOT]);
278 if(tok == ADD) b.add(parserLine, LITERAL, JS.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, JS.N(1));
300 b.add(parserLine, tok == INC ? ADD : SUB, JS.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, JS.T);
349 b.add(parserLine, CASCADE, JS.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, JS.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);
402 private Grammar parseGrammar(Grammar g) throws IOException {
403 int tok = getToken();
406 case BITOR: return new Grammar.Alternative(g, parseGrammar(null));
407 case ADD: return parseGrammar(new Grammar.Repetition(g, 1, Integer.MAX_VALUE));
408 case MUL: return parseGrammar(new Grammar.Repetition(g, 0, Integer.MAX_VALUE));
409 case HOOK: return parseGrammar(new Grammar.Repetition(g, 0, 1));
413 //case NUMBER: g0 = new Grammar.Literal(number); break;
414 case NAME: g0 = new Grammar.Reference(string); break;
416 g0 = new Grammar.Literal(string);
417 if (peekToken() == DOT) {
422 if (old.length() != 1 || string.length() != 1) throw pe("literal ranges must be single-char strings");
423 g0 = new Grammar.Range(old.charAt(0), string.charAt(0));
426 case LP: g0 = parseGrammar(null); consume(RP); break;
427 default: pushBackToken(); return g;
429 if (g == null) return parseGrammar(g0);
430 return parseGrammar(new Grammar.Juxtaposition(g, g0));
434 * Assuming that a complete assignable (lvalue) has just been
435 * parsed and the object and key are on the stack,
436 * <tt>continueExprAfterAssignable</tt> will attempt to parse an
437 * expression that modifies the assignable. This method always
438 * decreases the stack depth by exactly one element.
440 private void continueExprAfterAssignable(JSFunction b,int minPrecedence, JS varKey) throws IOException {
441 int saveParserLine = parserLine;
442 _continueExprAfterAssignable(b,minPrecedence,varKey);
443 parserLine = saveParserLine;
445 private void _continueExprAfterAssignable(JSFunction b,int minPrecedence, JS varKey) throws IOException {
446 if (b == null) throw new Error("got null b; this should never happen");
447 int tok = getToken();
448 if (minPrecedence != -1 && (precedence[tok] < minPrecedence || (precedence[tok] == minPrecedence && !isRightAssociative[tok])))
449 // force the default case
454 b.add(parserLine, GET_PRESERVE);
455 Grammar g = parseGrammar(null);
456 if (peekToken() == LC) {
457 g.action = new JSFunction(sourceName, parserLine, null);
458 parseBlock((JSFunction)g.action);
459 ((JSFunction)g.action).add(parserLine, LITERAL, null); // in case we "fall out the bottom", return NULL
460 ((JSFunction)g.action).add(parserLine, RETURN);
462 b.add(parserLine, MAKE_GRAMMAR, g);
463 b.add(parserLine, PUT);
467 case ASSIGN_BITOR: case ASSIGN_BITXOR: case ASSIGN_BITAND: case ASSIGN_LSH: case ASSIGN_RSH: case ASSIGN_URSH:
468 case ASSIGN_MUL: case ASSIGN_DIV: case ASSIGN_MOD: case ASSIGN_ADD: case ASSIGN_SUB: case ADD_TRAP: case DEL_TRAP: {
469 if (tok != ADD_TRAP && tok != DEL_TRAP)
470 b.add(parserLine, varKey == null ? GET_PRESERVE : SCOPEGET, varKey);
472 startExpr(b, precedence[tok]);
474 if (tok != ADD_TRAP && tok != DEL_TRAP) {
475 // tok-1 is always s/^ASSIGN_// (0 is BITOR, 1 is ASSIGN_BITOR, etc)
476 b.add(parserLine, tok - 1, tok-1==ADD ? JS.N(2) : null);
478 b.add(parserLine, PUT);
479 b.add(parserLine, SWAP);
480 b.add(parserLine, POP);
482 b.add(parserLine, SCOPEPUT, varKey);
485 if(varKey != null) throw pe("cannot place traps on local variables");
486 b.add(parserLine, tok);
490 case INC: case DEC: { // postfix
492 b.add(parserLine, GET_PRESERVE, Boolean.TRUE);
493 b.add(parserLine, LITERAL, JS.N(1));
494 b.add(parserLine, tok == INC ? ADD : SUB, JS.N(2));
495 b.add(parserLine, PUT, null);
496 b.add(parserLine, SWAP, null);
497 b.add(parserLine, POP, null);
498 b.add(parserLine, LITERAL, JS.N(1));
499 b.add(parserLine, tok == INC ? SUB : ADD, JS.N(2)); // undo what we just did, since this is postfix
501 b.add(parserLine, SCOPEGET, varKey);
502 b.add(parserLine, DUP);
503 b.add(parserLine, LITERAL, JS.ONE);
504 b.add(parserLine, tok == INC ? ADD : SUB, JS.N(2));
505 b.add(parserLine, SCOPEPUT, varKey);
510 startExpr(b, precedence[tok]);
512 b.add(parserLine, PUT);
513 b.add(parserLine, SWAP);
514 b.add(parserLine, POP);
516 b.add(parserLine, SCOPEPUT, varKey);
521 // Method calls are implemented by doing a GET_PRESERVE
522 // first. If the object supports method calls, it will
524 b.add(parserLine, varKey == null ? GET_PRESERVE : SCOPEGET, varKey);
525 int n = parseArgs(b);
526 b.add(parserLine, varKey == null ? CALLMETHOD : CALL, JS.N(n));
532 b.add(parserLine, SCOPEGET, varKey);
533 else if(b.get(b.size-1) == LITERAL && b.getArg(b.size-1) != null)
534 b.set(b.size-1,GET,b.getArg(b.size-1));
536 b.add(parserLine, GET);
544 * Assuming that a complete expression has just been parsed,
545 * <tt>continueExpr</tt> will attempt to extend this expression by
546 * parsing additional tokens and appending additional bytecodes.
548 * No operators with precedence less than <tt>minPrecedence</tt>
551 * If any bytecodes are appended, they will not alter the stack
554 private void continueExpr(JSFunction b, int minPrecedence) throws IOException {
555 int saveParserLine = parserLine;
556 _continueExpr(b, minPrecedence);
557 parserLine = saveParserLine;
559 private void _continueExpr(JSFunction b, int minPrecedence) throws IOException {
560 if (b == null) throw new Error("got null b; this should never happen");
561 int tok = getToken();
562 if (tok == -1) return;
563 if (minPrecedence != -1 && (precedence[tok] < minPrecedence || (precedence[tok] == minPrecedence && !isRightAssociative[tok]))) {
569 case LP: { // invocation (not grouping)
570 int n = parseArgs(b);
571 b.add(parserLine, CALL, JS.N(n));
574 case BITOR: case BITXOR: case BITAND: case SHEQ: case SHNE: case LSH:
575 case RSH: case URSH: case MUL: case DIV: case MOD:
576 case GT: case GE: case EQ: case NE: case LT: case LE: case SUB: {
577 startExpr(b, precedence[tok]);
578 b.add(parserLine, tok);
585 startExpr(b,precedence[tok]);
587 nextTok = getToken();
588 } while(nextTok == tok);
590 b.add(parserLine, tok, JS.N(count));
594 b.add(parserLine, tok == AND ? JSFunction.JF : JSFunction.JT, JS.ZERO); // test to see if we can short-circuit
596 startExpr(b, precedence[tok]); // otherwise check the second value
597 b.add(parserLine, JMP, JS.N(2)); // leave the second value on the stack and jump to the end
598 b.add(parserLine, LITERAL, tok == AND ?
599 JS.B(false) : JS.B(true)); // target of the short-circuit jump is here
600 b.set(size - 1, JS.N(b.size - size)); // write the target of the short-circuit jump
604 // support foo..bar syntax for foo[""].bar
605 if (peekToken() == DOT) {
610 b.add(parserLine, LITERAL, JSString.intern(string));
611 continueExprAfterAssignable(b,minPrecedence,null);
614 case LB: { // subscripting (not array constructor)
617 continueExprAfterAssignable(b,minPrecedence,null);
621 b.add(parserLine, JF, JS.ZERO); // jump to the if-false expression
623 startExpr(b, minPrecedence); // write the if-true expression
624 b.add(parserLine, JMP, JS.ZERO); // if true, jump *over* the if-false expression
625 b.set(size - 1, JS.N(b.size - size + 1)); // now we know where the target of the jump is
628 startExpr(b, minPrecedence); // write the if-false expression
629 b.set(size - 1, JS.N(b.size - size + 1)); // this is the end; jump to here
633 // pop the result of the previous expression, it is ignored
634 b.add(parserLine,POP);
644 continueExpr(b, minPrecedence); // try to continue the expression
647 // parse a set of comma separated function arguments, assume LP has already been consumed
648 private int parseArgs(JSFunction b) throws IOException {
650 while(peekToken() != RP) {
652 if (peekToken() != COMMA) {
653 startExpr(b, NO_COMMA);
654 if (peekToken() == RP) break;
662 /** Parse a block of statements which must be surrounded by LC..RC. */
663 void parseBlock(JSFunction b) throws IOException { parseBlock(b, null); }
664 void parseBlock(JSFunction b, String label) throws IOException {
665 int saveParserLine = parserLine;
666 _parseBlock(b, label);
667 parserLine = saveParserLine;
669 void _parseBlock(JSFunction b, String label) throws IOException {
670 if (peekToken() == -1) return;
671 else if (peekToken() != LC) parseStatement(b, null);
674 while(peekToken() != RC && peekToken() != -1) parseStatement(b, null);
679 /** Parse a single statement, consuming the RC or SEMI which terminates it. */
680 void parseStatement(JSFunction b, String label) throws IOException {
681 int saveParserLine = parserLine;
682 _parseStatement(b, label);
683 parserLine = saveParserLine;
685 void _parseStatement(JSFunction b, String label) throws IOException {
686 int tok = peekToken();
687 if (tok == -1) return;
688 switch(tok = getToken()) {
690 case THROW: case ASSERT: case RETURN: {
691 if (tok == RETURN && peekToken() == SEMI)
692 b.add(parserLine, LITERAL, null);
695 b.add(parserLine, tok);
699 case BREAK: case CONTINUE: {
700 if (peekToken() == NAME) consume(NAME);
701 b.add(parserLine, tok, string);
710 if (peekToken() == ASSIGN) { // if there is an '=' after the variable name
712 startExpr(b, NO_COMMA);
713 b.add(parserLine, SCOPEPUT, scopeKey(var)); // assign it
714 b.add(parserLine, POP); // clean the stack
716 if (peekToken() != COMMA) break;
719 if ((mostRecentlyReadToken != RC || peekToken() == SEMI) && peekToken() != -1 && mostRecentlyReadToken != SEMI) consume(SEMI);
727 b.add(parserLine, JF, JS.ZERO); // if false, jump to the else-block
729 parseStatement(b, null);
731 if (peekToken() == ELSE) {
733 b.add(parserLine, JMP, JS.ZERO); // if we took the true-block, jump over the else-block
734 b.set(size - 1, JS.N(b.size - size + 1));
736 parseStatement(b, null);
738 b.set(size - 1, JS.N(b.size - size + 1)); // regardless of which branch we took, b[size] needs to point here
743 if (label != null) b.add(parserLine, LABEL, label);
744 b.add(parserLine, LOOP);
746 b.add(parserLine, POP); // discard the first-iteration indicator
748 b.add(parserLine, JT, JS.N(2)); // if the while() clause is true, jump over the BREAK
749 b.add(parserLine, BREAK);
751 parseStatement(b, null);
752 b.add(parserLine, CONTINUE); // if we fall out of the end, definately continue
753 b.set(size - 1, JS.N(b.size - size + 1)); // end of the loop
758 if (label != null) b.add(parserLine, LABEL, label);
759 b.add(parserLine, LOOP);
765 if (peekToken() == CASE) { // we compile CASE statements like a bunch of if..else's
767 b.add(parserLine, DUP); // duplicate the switch() value; we'll consume one copy
770 b.add(parserLine, EQ); // check if we should do this case-block
771 b.add(parserLine, JF, JS.ZERO); // if not, jump to the next one
773 while(peekToken() != CASE && peekToken() != DEFAULT && peekToken() != RC) parseStatement(b, null);
774 b.set(size - 1, JS.N(1 + b.size - size));
775 } else if (peekToken() == DEFAULT) {
778 while(peekToken() != CASE && peekToken() != DEFAULT && peekToken() != RC) parseStatement(b, null);
779 } else if (peekToken() == RC) {
781 b.add(parserLine, BREAK); // break out of the loop if we 'fall through'
784 throw pe("expected CASE, DEFAULT, or RC; got " + codeToString[peekToken()]);
786 b.set(size0 - 1, JS.N(b.size - size0 + 1)); // end of the loop
791 if (label != null) b.add(parserLine, LABEL, label);
792 b.add(parserLine, LOOP);
794 parseStatement(b, null);
798 b.add(parserLine, JT, JS.N(2)); // check the while() clause; jump over the BREAK if true
799 b.add(parserLine, BREAK);
800 b.add(parserLine, CONTINUE);
803 b.set(size - 1, JS.N(b.size - size + 1)); // end of the loop; write this location to the LOOP instruction
808 b.add(parserLine, TRY); // try bytecode causes a TryMarker to be pushed
809 int tryInsn = b.size - 1;
810 // parse the expression to be TRYed
811 parseStatement(b, null);
812 // pop the try marker. this is pushed when the TRY bytecode is executed
813 b.add(parserLine, POP);
814 // jump forward to the end of the catch block, start of the finally block
815 b.add(parserLine, JMP);
816 int successJMPInsn = b.size - 1;
818 if (peekToken() != CATCH && peekToken() != FINALLY)
819 throw pe("try without catch or finally");
821 int catchJMPDistance = -1;
822 if (peekToken() == CATCH) {
823 Basket.List catchEnds = new Basket.Array();
824 boolean catchAll = false;
826 catchJMPDistance = b.size - tryInsn;
828 while(peekToken() == CATCH && !catchAll) {
833 exceptionVar = string;
834 int[] writebacks = new int[] { -1, -1, -1 };
835 if (peekToken() != RP) {
836 // extended Ibex catch block: catch(e faultCode "foo.bar.baz")
838 b.add(parserLine, DUP);
839 b.add(parserLine, LITERAL, JSString.intern(string));
840 b.add(parserLine, GET);
841 b.add(parserLine, DUP);
842 b.add(parserLine, LITERAL, null);
843 b.add(parserLine, EQ);
844 b.add(parserLine, JT);
845 writebacks[0] = b.size - 1;
846 if (peekToken() == STRING) {
848 b.add(parserLine, DUP);
849 b.add(parserLine, LITERAL, string);
850 b.add(parserLine, LT);
851 b.add(parserLine, JT);
852 writebacks[1] = b.size - 1;
853 b.add(parserLine, DUP);
854 b.add(parserLine, LITERAL, string + "/"); // (slash is ASCII after dot)
855 b.add(parserLine, GE);
856 b.add(parserLine, JT);
857 writebacks[2] = b.size - 1;
860 b.add(parserLine, DUP);
861 b.add(parserLine, LITERAL, number);
862 b.add(parserLine, EQ);
863 b.add(parserLine, JF);
864 writebacks[1] = b.size - 1;
866 b.add(parserLine, POP); // pop the element thats on the stack from the compare
871 // the exception is on top of the stack; put it to the chosen name
873 scopeDeclare(exceptionVar);
874 b.add(parserLine, SCOPEPUT, scopeKey(exceptionVar));
875 b.add(parserLine, POP);
879 b.add(parserLine, JMP);
880 catchEnds.add(new Integer(b.size-1));
882 for(int i=0; i<3; i++) if (writebacks[i] != -1) b.set(writebacks[i], JS.N(b.size-writebacks[i]));
883 b.add(parserLine, POP); // pop the element thats on the stack from the compare
887 b.add(parserLine, THROW);
889 for(int i=0;i<catchEnds.size();i++) {
890 int n = ((Integer)catchEnds.get(i)).intValue();
891 b.set(n, JS.N(b.size-n));
894 // pop the try and catch markers
895 b.add(parserLine,POP);
896 b.add(parserLine,POP);
899 // jump here if no exception was thrown
900 b.set(successJMPInsn, JS.N(b.size - successJMPInsn));
902 int finallyJMPDistance = -1;
903 if (peekToken() == FINALLY) {
904 b.add(parserLine, LITERAL, null); // null FinallyData
905 finallyJMPDistance = b.size - tryInsn;
907 parseStatement(b, null);
908 b.add(parserLine,FINALLY_DONE);
911 // setup the TRY arguments
912 b.set(tryInsn, new int[] { catchJMPDistance, finallyJMPDistance });
921 boolean hadVar = false; // if it's a for..in, we ignore the VAR
922 if (tok == VAR) { hadVar = true; tok = getToken(); }
923 String varName = string;
924 boolean forIn = peekToken() == IN; // determine if this is a for..in loop or not
925 pushBackToken(tok, varName);
933 b.add(parserLine, PUSHKEYS);
936 b.add(parserLine, LOOP);
937 b.add(parserLine, POP);
939 b.add(parserLine,SWAP); // get the keys enumeration object on top
940 b.add(parserLine,DUP);
941 b.add(parserLine,GET,JS.S("hasMoreElements"));
943 b.add(parserLine,JT);
944 b.add(parserLine,SWAP);
945 b.add(parserLine,BREAK);
946 b.set(size2, JS.N(b.size - size2));
947 b.add(parserLine,DUP);
948 b.add(parserLine,GET,JS.S("nextElement"));
952 if(hadVar) scopeDeclare(varName);
953 JS varKey = scopeKey(varName);
956 b.add(parserLine,GLOBALSCOPE);
957 b.add(parserLine,SWAP);
958 b.add(parserLine, LITERAL, JSString.intern(varName));
959 b.add(parserLine,SWAP);
960 b.add(parserLine,PUT);
961 b.add(parserLine,POP);
963 b.add(parserLine, SCOPEPUT, varKey);
965 b.add(parserLine,POP); // pop the put'ed value
966 b.add(parserLine,SWAP); // put CallMarker back into place
968 parseStatement(b, null);
971 b.add(parserLine, CONTINUE);
972 // jump here on break
973 b.set(size, JS.N(b.size - size));
975 b.add(parserLine, POP);
977 if (hadVar) pushBackToken(VAR, null); // yeah, this actually matters
978 scopePush(b); // grab a fresh scope
980 parseStatement(b, null); // initializer
981 JSFunction e2 = // we need to put the incrementor before the test
982 new JSFunction(sourceName, parserLine, null); // so we save the test here
983 if (peekToken() != SEMI)
986 e2.add(parserLine, JSFunction.LITERAL, JS.T); // handle the for(foo;;foo) case
988 if (label != null) b.add(parserLine, LABEL, label);
989 b.add(parserLine, LOOP);
992 b.add(parserLine, JT, JS.ZERO); // if we're on the first iteration, jump over the incrementor
994 if (peekToken() != RP) { // do the increment thing
996 b.add(parserLine, POP);
998 b.set(size - 1, JS.N(b.size - size + 1));
1001 b.paste(e2); // ok, *now* test if we're done yet
1002 b.add(parserLine, JT, JS.N(2)); // break out if we don't meet the test
1003 b.add(parserLine, BREAK);
1004 parseStatement(b, null);
1005 b.add(parserLine, CONTINUE); // if we fall out the bottom, CONTINUE
1006 b.set(size2 - 1, JS.N(b.size - size2 + 1)); // end of the loop
1008 scopePop(b); // get our scope back
1013 case NAME: { // either a label or an identifier; this is the one place we're not LL(1)
1014 String possiblyTheLabel = string;
1015 if (peekToken() == COLON) { // label
1017 parseStatement(b, possiblyTheLabel);
1019 } else { // expression
1020 pushBackToken(NAME, possiblyTheLabel);
1022 b.add(parserLine, POP);
1023 if ((mostRecentlyReadToken != RC || peekToken() == SEMI) && peekToken() != -1 && mostRecentlyReadToken != SEMI) consume(SEMI);
1028 case SEMI: return; // yep, the null statement is valid
1030 case LC: { // blocks are statements too
1033 parseBlock(b, label);
1038 default: { // hope that it's an expression
1041 b.add(parserLine, POP);
1042 if ((mostRecentlyReadToken != RC || peekToken() == SEMI) && peekToken() != -1 && mostRecentlyReadToken != SEMI) consume(SEMI);
1049 // ParserException //////////////////////////////////////////////////////////////////////
1050 private IOException pe(String s) { return new IOException(sourceName + ":" + line + " " + s); }