1 // Copyright 2002 Adam Megacz, see the COPYING file for licensing [GPL]
8 /** parses a stream of lexed tokens into a tree of Expr's */
9 public class Parser extends Lexer {
11 // Constructors //////////////////////////////////////////////////////
13 public Parser(Reader r, String sourceName, int line) throws IOException {
15 this.sourceName = sourceName;
20 public static void main(String[] s) throws Exception {
21 Parser p = new Parser(new InputStreamReader(System.in), "stdin", 0);
23 Expr block = p.parseBlock(false);
24 if (block == null) return;
25 System.out.println(block);
26 if (p.peekToken() == -1) return;
31 // Statics ////////////////////////////////////////////////////////////
33 static byte[] precedence = new byte[MAX_TOKEN + 1];
34 static boolean[] isRightAssociative = new boolean[MAX_TOKEN + 1];
36 precedence[ASSIGN] = 1;
37 isRightAssociative[ASSIGN] = true;
39 precedence[COMMA] = 3;
40 precedence[OR] = precedence[AND] = 4;
41 precedence[GT] = precedence[GE] = 5;
42 precedence[BITOR] = 6;
43 precedence[BITXOR] = 7;
44 precedence[BITAND] = 8;
45 precedence[EQ] = precedence[NE] = 9;
46 precedence[LT] = precedence[LE] = 10;
47 precedence[SHEQ] = precedence[SHNE] = 11;
48 precedence[LSH] = precedence[RSH] = precedence[URSH] = 12;
49 precedence[ADD] = precedence[SUB] = 13;
50 precedence[MUL] = precedence[DIV] = precedence[MOD] = 14;
51 precedence[BITNOT] = precedence[INSTANCEOF] = 15;
52 precedence[INC] = precedence[DEC] = 16;
59 // Parsing Logic /////////////////////////////////////////////////////////
61 public void consume(int code) throws IOException {
63 if (got != code) throw new ParserException("expected " + codeToString[code] + ", got " + (got == -1 ? "EOL" : codeToString[got]));
65 public void consume(int code, int code2) throws IOException {
67 if (got != code && got != code2)
68 throw new ParserException("expected " + codeToString[code] + " or " + codeToString[code2] +
69 ", got " + (got == -1 ? "EOL" : codeToString[got]));
71 public void expect(int code) throws IOException {
72 int got = peekToken();
73 if (got != code) throw new ParserException("expected " + codeToString[code] + ", got " + (got == -1 ? "EOL" : codeToString[got]));
76 /** parses the largest possible expression */
77 public Expr parseMaximalExpr() throws IOException { return parseMaximalExpr(null, -1); }
78 public Expr parseMaximalExpr(Expr prefix, int minPrecedence) throws IOException {
80 if (peekToken() == -1) break;
82 prefix = parseSingleExpr(prefix, minPrecedence);
83 if (save == prefix) break;
84 if (prefix == null) throw new ParserException("parseSingleExpr() returned null");
89 public Expr parseSingleExpr(Expr prefix, int minPrecedence) throws IOException {
90 Expr e1 = null, e2 = null, e3 = null, head = null, tail = null, ret = null;
92 int tok = peekToken();
93 if (minPrecedence > 0 &&
94 tok < precedence.length &&
95 precedence[tok] != 0 &&
96 (isRightAssociative[tok] ?
97 (precedence[tok] < minPrecedence) :
98 (precedence[tok] <= minPrecedence))) {
104 // these case arms match the precedence of operators; each arm is a precedence level.
107 case ASSIGN_BITOR: case ASSIGN_BITXOR: case ASSIGN_BITAND: case ASSIGN_LSH:
108 case ASSIGN_RSH: case ASSIGN_URSH: case ASSIGN_ADD: case ASSIGN_SUB: case ASSIGN_MUL: case ASSIGN_DIV: case ASSIGN_MOD:
109 return new Expr(curLine, ASSIGN, prefix, new Expr(curLine, tok - 1, prefix, parseMaximalExpr(null, precedence[ASSIGN])));
113 // FIXME: ugly hack!!
115 if (prefix == null) {
117 ByteCode b = (ByteCode)parseMaximalExpr(null, precedence[tok]);
118 b.set(b.size() - 1, tok, new Boolean(true));
122 ByteCode b = (ByteCode)prefix;
123 b.set(b.size() - 1, tok, new Boolean(false));
128 if (prefix == null) { // grouping
129 ByteCode b = new ByteCode(curLine, ByteCode.EXPR, parseMaximalExpr());
133 } else { // invocation
134 ByteCode b = new ByteCode(curLine);
136 b.add(b.EXPR, prefix);
137 while(peekToken() != RP) {
138 b.add(b.EXPR, parseMaximalExpr());
140 if (peekToken() == RP) break;
144 b.add(b.CALL, new Integer(i));
148 case BANG: case BITNOT: case INSTANCEOF: case TYPEOF: {
149 if (prefix != null) { pushBackToken(); return prefix; }
150 ByteCode b = new ByteCode(curLine);
151 b.add(b.EXPR, parseMaximalExpr(null, precedence[tok]));
157 if (prefix == null && peekToken() == NUMBER) {
159 return new ByteCode(curLine, ByteCode.LITERAL, new Double(number.doubleValue() * -1));
160 } // else fall through
161 case BITOR: case BITXOR: case BITAND: case SHEQ: case SHNE: case LSH:
162 case RSH: case URSH: case ADD: case MUL: case DIV: case MOD:
163 case GT: case GE: case EQ: case NE: case LT: case LE: {
164 if (prefix == null) throw new ParserException("the " + codeToString[tok] + " token cannot start an expression");
165 ByteCode b = new ByteCode(curLine);
166 b.add(b.EXPR, prefix);
167 b.add(b.EXPR, parseMaximalExpr(null, precedence[tok]));
172 // includes short-circuit logic
174 if (prefix == null) throw new ParserException("the " + codeToString[tok] + " token cannot start an expression");
175 ByteCode b = new ByteCode(curLine);
176 b.add(b.LITERAL, tok == AND ? new Boolean(false) : new Boolean(true));
177 b.add(b.EXPR, prefix);
178 b.add(tok == AND ? b.JF : b.JT, new Integer(3));
179 b.add(b.POP, NO_ARG);
180 b.add(b.EXPR, parseMaximalExpr(null, precedence[tok]));
185 if (prefix == null) throw new ParserException("the " + codeToString[tok] + " token cannot start an expression");
186 ByteCode b = new ByteCode(curLine);
187 b.add(b.THIS, NO_ARG);
188 b.add(b.LITERAL, prefix.string); // FIXME, this is ass-ugly
189 b.add(b.EXPR, parseMaximalExpr(null, precedence[ASSIGN]));
190 b.add(b.PUT, NO_ARG);
191 b.add(b.SWAP, NO_ARG);
192 b.add(b.POP, NO_ARG);
196 case WITH: throw new ParserException("XWT does not allow the WITH keyword");
197 case VOID: case RESERVED: throw new ParserException("reserved word that you shouldn't be using");
200 if (prefix != null) { pushBackToken(); return prefix; }
201 return new ByteCode(curLine, ByteCode.LITERAL, number);
204 if (prefix != null) { pushBackToken(); return prefix; }
205 return new ByteCode(curLine, ByteCode.LITERAL, string);
207 case NULL: case TRUE: case FALSE: case NOP:
208 if (prefix != null) { pushBackToken(); return prefix; }
209 return new ByteCode(curLine, ByteCode.LITERAL, (tok == NULL || tok == NOP) ? null : new Boolean(tok == TRUE));
211 case COMMA: pushBackToken(); return prefix;
214 if (prefix != null) { pushBackToken(); return prefix; }
215 return new ByteCode(curLine, ByteCode.THIS, NO_ARG);
220 if (prefix != null) { pushBackToken(); return prefix; }
221 String name = string;
222 ByteCode b = new ByteCode(curLine);
223 if (peekToken() == ASSIGN) {
225 b.add(ByteCode.THIS, NO_ARG);
226 b.add(ByteCode.LITERAL, name);
227 b.add(ByteCode.EXPR, parseMaximalExpr(null, minPrecedence));
228 b.add(ByteCode.PUT, NO_ARG);
229 b.add(ByteCode.SWAP, NO_ARG);
230 b.add(ByteCode.POP, NO_ARG);
233 b.add(ByteCode.THIS, NO_ARG);
234 b.add(ByteCode.LITERAL, name);
235 b.add(ByteCode.GET, NO_ARG);
236 return parseMaximalExpr(b, minPrecedence);
242 String target = string;
243 ByteCode b = new ByteCode(curLine);
244 b.add(b.EXPR, prefix);
245 if (peekToken() == ASSIGN) {
247 Expr val = parseMaximalExpr();
248 b.add(b.LITERAL, target);
250 b.add(b.PUT, NO_ARG);
251 b.add(b.SWAP, NO_ARG);
252 b.add(b.POP, NO_ARG);
254 b.add(b.LITERAL, target);
255 b.add(b.GET, NO_ARG);
261 ByteCode b = new ByteCode(curLine);
262 if (prefix == null) {
263 b.add(b.ARRAY, new Integer(0));
266 Expr e = parseMaximalExpr();
267 if (e == null && peekToken() == RB) { consume(RB); return b; }
268 if (e == null) e = new Expr(curLine, NULL);
269 b.add(b.LITERAL, new Integer(i++));
271 b.add(b.PUT, NO_ARG);
272 b.add(b.POP, NO_ARG);
273 if (peekToken() == RB) { consume(RB); return b; }
277 b.add(b.EXPR, prefix);
278 b.add(b.EXPR, parseMaximalExpr());
280 if (peekToken() == ASSIGN) {
282 b.add(b.EXPR, parseMaximalExpr());
283 b.add(b.PUT, NO_ARG);
284 b.add(b.SWAP, NO_ARG);
285 b.add(b.POP, NO_ARG);
287 b.add(b.GET, NO_ARG);
296 if (prefix != null) { pushBackToken(); return prefix; }
297 ByteCode b = new ByteCode(curLine);
298 b.add(b.OBJECT, null);
299 if (peekToken() == RC) { consume(RC); return b; }
301 consume(NAME, STRING);
302 b.add(b.LITERAL, string);
304 b.add(b.EXPR, parseMaximalExpr());
305 b.add(b.PUT, NO_ARG);
306 b.add(b.POP, NO_ARG);
307 if (peekToken() == RC) { consume(RC); return b; }
309 if (peekToken() == RC) { consume(RC); return b; }
314 ByteCode b = new ByteCode(curLine);
315 b.add(b.EXPR, prefix);
316 b.add(b.JF, new Integer(3));
317 b.add(b.EXPR, parseMaximalExpr());
318 b.add(b.JMP, new Integer(2));
320 b.add(b.EXPR, parseMaximalExpr());
325 if (prefix != null) { pushBackToken(); return prefix; }
327 ExprList list = new ExprList(curLine, LC);
328 if (peekToken() == RP) consume(RP);
333 list.add(new Expr(curLine, NULL));
336 list.add(new Expr(curLine, NAME, string));
337 if (peekToken() == RP) { consume(RP); break; }
341 return new Expr(curLine, FUNCTION, list, parseBlock(true));
345 if (prefix != null) { pushBackToken(); return prefix; }
346 ByteCode b = new ByteCode(curLine);
347 b.add(b.THIS, NO_ARG);
350 String name = string;
351 b.add(b.DECLARE, name);
352 if (peekToken() == ASSIGN) {
353 b.add(b.LITERAL, name);
355 b.add(b.EXPR, parseMaximalExpr());
356 b.add(b.PUT, NO_ARG);
357 b.add(b.POP, NO_ARG);
359 if (peekToken() != COMMA) break;
365 case IN: pushBackToken(); return prefix;
368 if (prefix != null) { pushBackToken(); return prefix; }
369 ByteCode b = new ByteCode(curLine);
371 b.add(b.EXPR, parseMaximalExpr());
373 b.add(b.JF, new Integer(3));
374 b.add(b.EXPR, parseBlock(false));
375 b.add(b.JMP, new Integer(2));
376 if (peekToken() != ELSE) return b.add(b.LITERAL, null);
378 b.add(b.EXPR, parseBlock(false));
385 if (prefix != null) { pushBackToken(); return prefix; }
386 if (getToken() != LP) throw new ParserException("expected left paren");
387 Expr switchExpr = parseMaximalExpr();
388 if (getToken() != RP) throw new ParserException("expected left paren");
389 if (getToken() != LC) throw new ParserException("expected left brace");
390 ExprList toplevel = new ExprList(curLine, LC);
394 if (tok == DEFAULT) caseExpr = null;
395 else if (tok == CASE) caseExpr = parseMaximalExpr();
396 else throw new ParserException("expected CASE or DEFAULT");
398 // FIXME: we shouldn't be creating a scope here
399 ExprList list = new ExprList(curLine, LC);
400 while(peekToken() != CASE && peekToken() != DEFAULT && peekToken() != RC) {
401 if ((e1 = parseBlock(false)) == null) break;
404 toplevel.add(new Expr(curLine, tok, caseExpr, list));
405 if (peekToken() == RC) { consume(RC); return new Expr(curLine, SWITCH, switchExpr, toplevel); }
410 // We deliberately allow you to omit braces in catch{}/finally{} if they are single statements...
411 if (prefix != null) { pushBackToken(); return prefix; }
412 Expr tryBlock = parseBlock(true);
415 ExprList list = new ExprList(curLine, TRY);
418 if (getToken() != LP) throw new ParserException("expected (");
419 if (getToken() != NAME) throw new ParserException("expected name");
420 Expr name = new Expr(curLine, NAME, string);
421 if (getToken() != RP) throw new ParserException("expected )");
422 list.add(new Expr(curLine, CATCH, name, parseBlock(false)));
425 if (tok == FINALLY) {
427 list.add(new Expr(curLine, FINALLY, parseBlock(false)));
430 if (list.size() == 0) throw new ParserException("try without catch or finally");
431 return new Expr(curLine, TRY, tryBlock, list);
435 if (prefix != null) { pushBackToken(); return prefix; }
437 Expr parenExpr = parseMaximalExpr();
439 if ((t = getToken()) != RP)
440 throw new ParserException("expected right paren, but got " + codeToString[t]);
441 Expr firstBlock = parseBlock(false);
442 ExprList list = new ExprList(curLine, WHILE);
444 list.add(firstBlock);
445 list.add(new Expr(curLine, NULL));
450 if (prefix != null) { pushBackToken(); return prefix; }
451 if (getToken() != LP) throw new ParserException("expected left paren");
452 e1 = parseMaximalExpr();
453 if (peekToken() == IN) {
455 e2 = parseMaximalExpr();
456 if (getToken() != RP) throw new ParserException("expected right paren");
457 return new Expr(curLine, FOR, new Expr(curLine, IN, e1.left, e2), parseBlock(false));
461 if (initExpr == null) initExpr = new Expr(curLine, NULL);
462 expect(SEMI); getToken();
463 Expr whileExpr = parseMaximalExpr();
464 expect(SEMI); getToken();
465 Expr incExpr = parseMaximalExpr();
466 expect(RP); getToken();
467 Expr body = parseBlock(false);
468 Expr loop = new Expr(curLine, WHILE, whileExpr, body);
469 ExprList list = new ExprList(curLine, LC);
471 ExprList list2 = new ExprList(curLine, WHILE);
473 list2.add(whileExpr);
480 if (prefix != null) { pushBackToken(); return prefix; }
481 ExprList list = new ExprList(curLine, DO);
482 Expr body = parseBlock(false);
485 list.add(parseMaximalExpr());
487 list.add(new Expr(curLine, NULL));
499 // Expr //////////////////////////////////////////////////////////////////////
501 public static final Object NO_ARG = new Object();
503 class ByteCode extends Expr {
505 // This class interprets a small forthlike bytecode language
506 // we use to represent JavaScript. It's a stack machine.
508 // Each instruction is an opcode and a literal. Any operation
509 // that accesses the top of the stack and does not have a
510 // mandatory literal can be performed on a literal instead of
511 // the top of the stack.
514 public static final byte arithmetic = -1; // -- arithmetic operators from parser
515 public static final byte LITERAL = -2; // < String | Number | null > -- push a literal onto the stack
516 public static final byte ARRAY = -3; // < size > -- create a new array of size <size>
517 public static final byte OBJECT = -4; // -- push an empty object onto the stack
518 public static final byte FUNCTION = -5; // < bytecode_block > -- push a new instance of a function with the given bytecode
519 public static final byte DECLARE = -6; // < name > -- declare <name> in the current scope
520 public static final byte THIS = -7; // -- push the topmost non-transparent scope onto the stack
521 public static final byte GET = -8; // -- get stack[0] from stack[1]
522 public static final byte PUT = -9; // -- put stack[1] to key stack[0] on stack[2]; leaves object on the stack
523 public static final byte THROW = -10; // -- throw topmost element
524 public static final byte RETURN = -11; // -- return the topmost value on the stack
525 public static final byte ASSERT = -12; // -- fail if topmost element is not true
526 public static final byte JT = -13; // < relative_address > -- pop the stack; if true, jump to <relative_address>
527 public static final byte JF = -21; // < relative_address > -- pop the stack; if false, jump to <relative_address>
528 public static final byte JMP = -22; // < relative_address > -- jump to <relative_address>
529 static public final byte POP = -14; // -- discard the top element on the stack
531 public static final byte CALL = -15; // < numargs > -- call stack[0] with the topmost <numargs> values as arguments
532 public static final byte TRY = -16; // < bytecode_block > -- run the block pointed to; returns with thrown exn on top of stack
534 public static final byte INSTANCEOF = -17; // -- ??
535 public static final byte TYPEOF = -18; // --
537 public static final byte FOR__IN = -19; // -- ??
538 public static final byte EXPR = -20; // -- transitional
539 public static final byte SWAP = -23; // -- transitional
540 public static final byte SCOPE = -30; // -- transitional
542 int[] op = new int[10];
543 Object[] arg = new Object[10];
546 public ByteCode(int line) { super(line, "foo"); }
547 public ByteCode(int line, int op_, Object arg_) { this(line); add(op_, arg_); }
549 public int size() { return size; }
550 public void set(int pos, int op_, Object arg_) { op[pos] = op_; arg[pos] = arg_; }
551 public ByteCode add(int op_, Object arg_) {
552 if (size == op.length - 1) {
553 int[] op2 = new int[op.length * 2]; System.arraycopy(op, 0, op2, 0, op.length); op = op2;
554 Object[] arg2 = new Object[op.length * 2]; System.arraycopy(arg, 0, arg2, 0, arg.length); arg = arg2;
562 public Object eval(final JS.Scope s) throws ControlTransferException, JS.Exn {
563 return eval(s, new Parser.Thread());
565 public Object eval(JS.Scope s, Parser.Thread t) throws ControlTransferException {
566 for(int i=0; i<size; i++)
568 case arithmetic: break;
572 case OBJECT: t.push(new JS.Obj()); break;
573 case ARRAY: t.push(new JS.Array(toNumber(arg[i]).intValue())); break;
574 case DECLARE: s.declare(arg[i] == NO_ARG ? (String)t.pop() : (String)arg[i]); break;
575 case THIS: t.push(s); break; // FIXME: transparents
576 case ASSERT: if (!toBoolean(t.pop())) throw new EvaluatorException("assertion failed"); break;
577 case THROW: throw new JS.Exn(t.pop());
578 case JT: if (toBoolean(t.pop())) i += toNumber(arg[i]).intValue() - 1; break;
579 case JF: if (!toBoolean(t.pop())) i += toNumber(arg[i]).intValue() - 1; break;
580 case JMP: i += toNumber(arg[i]).intValue() - 1; break;
581 case POP: t.pop(); break;
582 case SWAP: t.swap(); break;
585 Object val = arg[i] == NO_ARG ? t.pop() : arg[i];
586 Object key = t.pop();
587 ((JS)t.peek()).put(key, val);
593 Object v = arg[i] == NO_ARG ? t.pop() : arg[i];
600 case EXPR: t.push(((Expr)arg[i]).eval(s)); break;
601 case SCOPE: t.push(((Expr)arg[i]).eval(new JS.Scope(s))); break;
604 JS.Array arguments = new JS.Array();
605 int numArgs = toNumber(arg[i]).intValue();
606 arguments.setSize(numArgs);
607 for(int j=numArgs - 1; j >= 0; j--) arguments.setElementAt(t.pop(), j);
608 JS.Function f = (JS.Function)t.pop();
609 if (f == null) throw new JS.Exn(new EvaluatorException("attempted to call null"));
610 t.push(f.call(arguments));
613 case FUNCTION: break;
616 case INSTANCEOF: break;
620 case Lexer.BITNOT: t.push(new Long(~toLong(t.pop()))); break;
621 case Lexer.BANG: t.push(new Boolean(!toBoolean(t.pop()))); break;
623 case Lexer.INC: case Lexer.DEC: {
624 boolean isPrefix = toBoolean(arg[i]);
625 Object key = t.pop();
626 JS obj = (JS)t.pop();
627 Number num = toNumber(obj.get(key));
628 Number val = new Double(op[i] == Lexer.INC ? num.doubleValue() + 1.0 : num.doubleValue() - 1.0);
630 t.push(isPrefix ? val : num);
635 Object right = t.pop();
636 Object left = t.pop();
639 case Lexer.BITOR: t.push(new Long(toLong(left) | toLong(right))); break;
640 case Lexer.BITXOR: t.push(new Long(toLong(left) ^ toLong(right))); break;
641 case Lexer.BITAND: t.push(new Long(toLong(left) & toLong(right))); break;
646 if (l instanceof String || r instanceof String) {
647 if (l == null) l = "null";
648 if (r == null) r = "null";
649 if (l instanceof Number && ((Number)l).doubleValue() == ((Number)l).longValue())
650 l = new Long(((Number)l).longValue());
651 if (r instanceof Number && ((Number)r).doubleValue() == ((Number)r).longValue())
652 r = new Long(((Number)r).longValue());
653 t.push(l.toString() + r.toString()); break;
655 t.push(new Double(toDouble(l) + toDouble(r))); break;
658 case Lexer.SUB: t.push(new Double(toDouble(left) - toDouble(right))); break;
659 case Lexer.MUL: t.push(new Double(toDouble(left) * toDouble(right))); break;
660 case Lexer.DIV: t.push(new Double(toDouble(left) / toDouble(right))); break;
661 case Lexer.MOD: t.push(new Double(toDouble(left) % toDouble(right))); break;
663 case Lexer.LSH: t.push(new Long(toLong(left) << toLong(right))); break;
664 case Lexer.RSH: t.push(new Long(toLong(left) >> toLong(right))); break;
665 case Lexer.URSH: t.push(new Long(toLong(left) >>> toLong(right))); break;
667 // FIXME: these need to work on strings
668 case Lexer.LT: t.push(toDouble(left) < toDouble(right) ? Boolean.TRUE : Boolean.FALSE); break;
669 case Lexer.LE: t.push(toDouble(left) <= toDouble(right) ? Boolean.TRUE : Boolean.FALSE); break;
670 case Lexer.GT: t.push(toDouble(left) > toDouble(right) ? Boolean.TRUE : Boolean.FALSE); break;
671 case Lexer.GE: t.push(toDouble(left) >= toDouble(right) ? Boolean.TRUE : Boolean.FALSE); break;
675 // FIXME: should use Javascript coercion-equality rules
679 if (l == null) { Object tmp = r; r = l; l = tmp; }
680 if (l == null && r == null) ret = true;
681 else if (l instanceof Boolean) ret = new Boolean(toBoolean(r)).equals(l);
682 else if (l instanceof Number) ret = toNumber(r).doubleValue() == toNumber(l).doubleValue();
683 else if (l instanceof String) ret = r != null && l.equals(r.toString());
684 else ret = l.equals(r);
685 t.push(new Boolean(op[i] == Lexer.EQ ? ret : !ret)); break;
688 default: throw new Error("unknown opcode " + op[i]);
692 throw new EvaluatorException("eval() terminated with " + t.size() + " elements on the stack; one expected");
697 public Object doGet(final Object o, final Object v) {
698 if (o == null) throw new EvaluatorException("tried to get property \"" + v + "\" from the null value");
699 if (o instanceof String) {
700 if (v.equals("length")) return new Integer(((String)o).length());
701 else if (v.equals("substring")) return new JS.Function() {
702 public Object _call(JS.Array args) {
703 if (args.length() == 1) return ((String)o).substring(toNumber(args.elementAt(0)).intValue());
704 else if (args.length() == 2) return ((String)o).substring(toNumber(args.elementAt(0)).intValue(),
705 toNumber(args.elementAt(1)).intValue());
706 else throw new Error("String.substring() can only take one or two arguments");
709 else if (v.equals("toLowerCase")) return new JS.Function() {
710 public Object _call(JS.Array args) {
711 return ((String)o).toLowerCase();
713 else if (v.equals("toUpperCase")) return new JS.Function() {
714 public Object _call(JS.Array args) {
715 return ((String)o).toString().toUpperCase();
717 else if (v.equals("charAt")) return new JS.Function() {
718 public Object _call(JS.Array args) {
719 return ((String)o).charAt(toNumber(args.elementAt(0)).intValue()) + "";
721 else if (v.equals("lastIndexOf")) return new JS.Function() {
722 public Object _call(JS.Array args) {
723 if (args.length() != 1) return null;
724 return new Integer(((String)o).lastIndexOf(args.elementAt(0).toString()));
726 else if (v.equals("indexOf")) return new JS.Function() {
727 public Object _call(JS.Array args) {
728 if (args.length() != 1) return null;
729 return new Integer(((String)o).indexOf(args.elementAt(0).toString()));
731 throw new Error("Not Implemented: properties on String objects");
732 } else if (o instanceof Boolean) {
733 throw new Error("Not Implemented: properties on Boolean objects");
734 } else if (o instanceof Number) {
735 Log.log(this, "Not Implemented: properties on Number objects");
737 //throw new Error("Not Implemented: properties on Number objects");
738 } else if (o instanceof JS) {
739 return ((JS)o).get(v);
746 public Object[] os = new Object[256];
748 public void push(Object o) { os[size++] = o; }
749 public Object pop() { return os[--size]; }
750 public Object peek() { return os[size - 1]; }
751 public void swap() { Object temp = os[size - 1]; os[size - 1] = os[size - 2]; os[size - 2] = temp; }
752 public int size() { return size; }
755 class ExprList extends Expr {
757 public ExprList(int curLine, int code) { super(curLine, code); }
758 public void add(Expr e) { v.addElement(e); }
759 public int numExprs() { return v.size(); }
760 public int size() { return v.size(); }
761 public Expr elementAt(int i) { return (Expr)v.elementAt(i); }
762 public Object eval(final JS.Scope s) throws ControlTransferException, JS.Exn {
766 JS.Scope scope = new JS.Scope(s);
767 for(int i=0; i<v.size(); i++) ((Expr)v.elementAt(i)).eval(scope);
772 JS.Array ret = new JS.Array();
773 for(int i=0; i<numExprs(); i++) ret.addElement(elementAt(i).eval(s));
778 JS.Obj ret = new JS.Obj();
779 for(int i=0; i<numExprs(); i++) {
780 Expr e = elementAt(i);
781 Object key = e.left.string;
782 Object val = e.right.eval(s);
790 boolean first = true;
792 ExprList list = this;
793 Expr whileExpr = list.elementAt(0);
794 Expr bodyExpr = list.elementAt(1);
795 Expr incExpr = list.elementAt(2);
796 for(;(first && code == Lexer.DO) || toBoolean(whileExpr.eval(s)); bogus = incExpr.eval(s)) {
800 } catch (ContinueException c) {
801 if (c.label == null || c.label.equals(string)) continue;
802 } catch (BreakException b) {
803 if (b.label == null || b.label.equals(string)) return null;
804 throw (BreakException)b.fillInStackTrace();
807 } catch (BreakException e) {
808 if (e.label != null && !e.label.equals(string)) throw e;
812 for(int i=0; i<size(); i++) {
813 Expr e = elementAt(i);
814 s.declare(e.left.string);
815 if (e.right != null) e.right.eval(s);
818 default: throw new Error("augh!");
823 /** a block is either a single statement or a list of statements surrounded by curly braces; all expressions are also statements */
824 public Expr parseBlock(boolean requireBraces) throws IOException {
826 int tok = peekToken();
827 if (tok == -1) return null;
828 boolean braced = tok == LC;
829 if (requireBraces && !braced) throw new ParserException("expected {, got " + codeToString[tok]);
830 if (braced) consume(LC);
832 ByteCode ret = new ByteCode(curLine);
833 ByteCode block = new ByteCode(curLine);
834 block.add(ret.LITERAL, Boolean.TRUE);
835 ret.add(block.SCOPE, block);
837 switch(tok = peekToken()) {
840 smt = parseBlock(true); break;
842 case THROW: case RETURN: case ASSERT:
844 if (peekToken() == SEMI) {
845 if (tok == THROW || tok == ASSERT) throw new ParserException(codeToString[tok] + " requires an argument");
847 smt = new Expr(curLine, tok);
849 smt = new Expr(curLine, tok, parseMaximalExpr());
854 case GOTO: case BREAK: case CONTINUE: {
859 smt = new Expr(curLine, tok, new Expr(curLine, string));
860 } else if (tok == GOTO) {
861 throw new ParserException("goto must be followed by a label");
863 smt = new Expr(curLine, tok, new Expr(curLine, string));
869 if (braced) consume(RC);
870 return block.size() == 0 ? null : ret;
874 if (!braced) return block.size() == 0 ? null : ret;
878 String name = string;
880 if (peekToken() == COLON) {
882 smt = new Expr(curLine, COLON, new Expr(curLine, name), parseBlock(false));
885 pushBackToken(NAME, name);
886 // fall through to default case
892 smt = parseMaximalExpr();
893 if (smt == null) return block.size() == 0 ? null : ret;
894 if (peekToken() == SEMI) getToken();
898 if (!braced) return smt;
899 block.add(block.EXPR, smt);
900 block.add(block.POP, NO_ARG);
905 /** sorta like gcc trees */
912 String sourceName = "unknown";
914 String string = null;
915 Number number = null;
917 public String toString() { return toString(0); }
918 public String toString(int indent) {
920 for(int i=0; i<indent; i++) ret += " ";
921 ret += Lexer.codeToString[code];
922 if (code == Lexer.NUMBER) ret += " " + number;
923 else if (string != null) ret += " \"" + string + "\"";
925 if (left != null) ret += left.toString(indent + 2);
926 if (right != null) ret += right.toString(indent + 2);
930 public Expr(int line, String s) { this(line, Lexer.STRING); this.string = s; } // an identifier or label
931 public Expr(int line, int code, String s) { this(line, code); this.string = s; }
932 public Expr(int line, Number n) { this(line, Lexer.NUMBER); this.number = n; } // an identifier or label
933 public Expr(int line, int code) { this(line, code, null, null); }
934 public Expr(int line, int code, Expr left) { this(line, code, left, null); }
935 public Expr(int line, int code, Expr left, Expr right) {
936 this.code = code; this.left = left; this.right = right;
938 this.sourceName = Parser.this.sourceName;
941 public double toDouble(Object o) { return toNumber(o).doubleValue(); }
942 public long toLong(Object o) { return toNumber(o).longValue(); }
943 public boolean toBoolean(Object o) {
944 if (o == null) return false;
945 if (o instanceof Boolean) return ((Boolean)o).booleanValue();
946 if (o instanceof Number) return o.equals(new Integer(0));
950 public Object eval(final JS.Scope s) throws ControlTransferException, JS.Exn {
954 Object o = left.eval(s);
955 if (o == null) return "null";
956 if (o.getClass() == String.class) return "string";
957 if (o.getClass() == Boolean.class) return "boolean";
958 if (o instanceof Number) return "number";
959 if (o instanceof JS.Array) return "array";
960 if (o instanceof JS) return "object";
961 throw new EvaluatorException("typeof " + o.getClass().getName() + " unknown");
964 case Lexer.NUMBER: return number;
965 case Lexer.STRING: return string;
968 Object v = (code == Lexer.ASSIGN) ? right.eval(s) : new Double(toDouble(left.eval(s)) + (code == Lexer.INC ? 1 : -1));
969 if (left.code == Lexer.DOT) {
970 Object o = left.left.eval(s);
971 if (o instanceof String) {
972 throw new EvaluatorException("can't set properties on a String");
973 } else if (o instanceof Number) {
974 throw new EvaluatorException("can't set properties on a Number");
975 } else if (o instanceof Boolean) {
976 throw new EvaluatorException("can't set properties on a Boolean");
979 if (target == null) throw new JS.Exn(new EvaluatorException("attempted to put to the null value"));
980 target.put(left.right.eval(s), v);
984 s.put(left.string, v);
989 case Lexer.NULL: return null;
990 case Lexer.FALSE: return Boolean.FALSE;
991 case Lexer.TRUE: return Boolean.TRUE;
992 case Lexer.ASSERT: if (!toBoolean(left.eval(s))) throw new EvaluatorException("assertion failed");
993 case Lexer.THROW: throw new JS.Exn(left.eval(s));
994 case Lexer.NAME: return s.get(string);
995 case Lexer.THIS: return s.isTransparent() ? s : this.eval(s.getParentScope());
998 boolean safeToExit = false;
1000 Object ret = left.eval(s);
1003 } catch (JS.Exn e) {
1004 ExprList list = (ExprList)right;
1005 Expr c = list.elementAt(0);
1006 if (c.code == Lexer.CATCH) {
1007 JS.Scope scope = new JS.Scope(s);
1008 s.put(c.left.string, e);
1009 c.right.eval(scope);
1010 c = list.elementAt(1);
1012 if (c.code == Lexer.FINALLY) {
1013 JS.Scope scope = new JS.Scope(s);
1017 if (!safeToExit) Log.log(this, "WARNING: Java exception penetrated a JavaScript try{} block");
1022 case Lexer.FUNCTION:
1023 return new JS.Function() {
1024 public String toString() { return right.sourceName + ":" + right.line; }
1025 public String getSourceName() throws JS.Exn { return right.sourceName; }
1026 public Object _call(final JS.Array args) throws JS.Exn {
1027 Function save = JS.getCurrentFunction();
1028 JS.currentFunction.put(java.lang.Thread.currentThread(), this);
1029 JS.Scope scope = new JS.Scope(s) {
1031 public String getSourceName() { return sourceName; }
1032 public Object get(Object key) throws JS.Exn {
1033 if (key.equals("trapee")) return org.xwt.Trap.currentTrapee();
1034 else if (key.equals("cascade")) return org.xwt.Trap.cascadeFunction;
1035 else if (key.equals("arguments")) return args;
1036 return super.get(key);
1040 ExprList list = (ExprList)left;
1041 for(i=0; i<list.size(); i++) {
1042 scope.declare(list.elementAt(i).string);
1043 scope.put(list.elementAt(i).string, args.get(new Integer(i)));
1046 return right.eval(scope);
1047 } catch (ReturnException r) {
1049 } catch (ControlTransferException c) {
1050 throw new EvaluatorException("error, ControlTransferException tried to leave a function: "
1053 if (save == null) JS.currentFunction.remove(java.lang.Thread.currentThread());
1054 else JS.currentFunction.put(java.lang.Thread.currentThread(), save);
1060 Object[] keys = ((JS)left.right.eval(s)).keys();
1061 for(int i=0; i<keys.length; i++) {
1062 JS.Scope scope = new JS.Scope(s);
1063 scope.declare(left.string);
1064 scope.put(left.string, keys[i]);
1067 } catch (ContinueException c) {
1068 if (c.label == null || c.label.equals(string)) continue;
1069 } catch (BreakException b) {
1070 if (b.label == null || b.label.equals(string)) return null;
1071 throw (BreakException)b.fillInStackTrace();
1077 Object switchVal = left.eval(s);
1080 ExprList list = (ExprList)right;
1081 for(int i=0; i<list.size(); i++) {
1082 Expr e = list.elementAt(i);
1083 if (go || e.code == Lexer.DEFAULT || e.left.eval(s).equals(switchVal)) go = true;
1084 if (go) e.right.eval(s);
1086 } catch (BreakException b) {
1087 if (b.label == null || b.label.equals(string)) return null;
1088 throw (BreakException)b.fillInStackTrace();
1092 case Lexer.BREAK: throw new BreakException(string);
1093 case Lexer.CONTINUE: throw new ContinueException(string);
1094 case Lexer.RETURN: throw new ReturnException(left == null ? null : left.eval(s));
1096 default: throw new EvaluatorException("don't know how to eval an Expr with code " + Lexer.codeToString[code] + "\n" + this);
1100 class EvaluatorException extends RuntimeException {
1101 public EvaluatorException(String s) { super(sourceName + ":" + line + " " + s); }
1105 static abstract class ControlTransferException extends Exception { }
1106 static class BreakException extends ControlTransferException {
1107 public String label;
1108 BreakException(String label) { this.label = label; }
1110 static class ContinueException extends ControlTransferException {
1111 public String label;
1112 ContinueException(String label) { this.label = label; }
1114 static class ReturnException extends ControlTransferException {
1115 public Object retval;
1116 ReturnException(Object retval) { this.retval = retval; }
1119 class ParserException extends RuntimeException {
1120 public ParserException(String s) { super(sourceName + ":" + line + " " + s); }
1123 public static Number toNumber(Object o) {
1124 if (o == null) return new Long(0);
1125 if (o instanceof Number) return ((Number)o);
1126 if (o instanceof String) try { return new Double((String)o); } catch (NumberFormatException e) { return new Double(0); }
1127 if (o instanceof Boolean) return ((Boolean)o).booleanValue() ? new Long(1) : new Long(0);
1128 if (o instanceof JS) return ((JS)o).coerceToNumber();
1130 throw new Error("toNumber() got object of type " + o.getClass().getName());