1 // Copyright 2003 Adam Megacz, see the COPYING file for licensing [GPL]
8 /** A JavaScript function, compiled into bytecode */
9 public class JSFunction extends JSCallable implements ByteCodes, Tokens {
11 /** Note: code gets run in an <i>unpauseable</i> context. */
12 public Object call(JSArray args) {
13 JSContext cx = new JSContext(this, false);
15 return cx.stack.pop();
19 // Fields and Accessors ///////////////////////////////////////////////
21 int numFormalArgs = 0; ///< the number of formal arguments
22 String sourceName; ///< the source code file that this block was drawn from
23 int[] line = new int[10]; ///< the line numbers
24 private int firstLine = -1; ///< the first line of this script
25 int[] op = new int[10]; ///< the instructions
26 Object[] arg = new Object[10]; ///< the arguments to the instructions
27 int size = 0; ///< the number of instruction/argument pairs
28 JSScope parentJSScope; ///< the default scope to use as a parent scope when executing this
31 // Constructors ////////////////////////////////////////////////////////
33 public JSFunction cloneWithNewParentJSScope(JSScope s) {
34 JSFunction ret = new JSFunction(sourceName, firstLine, s);
35 // Reuse the same op, arg, line, and size variables for the new "instance" of the function
36 // NOTE: Neither *this* function nor the new function should be modified after this call
41 ret.numFormalArgs = this.numFormalArgs;
45 private JSFunction(String sourceName, int firstLine, JSScope parentJSScope) {
46 this.sourceName = sourceName;
47 this.firstLine = firstLine;
48 this.parentJSScope = parentJSScope;
51 protected JSFunction(String sourceName, int firstLine, Reader sourceCode, JSScope parentJSScope) throws IOException {
52 this(sourceName, firstLine, parentJSScope);
53 if (sourceCode == null) return;
54 Parser p = new Parser(sourceCode, sourceName, firstLine);
57 p.parseStatement(this, null);
60 add(-1, LITERAL, null);
66 // Adding and Altering Bytecodes ///////////////////////////////////////////////////
68 int get(int pos) { return op[pos]; }
69 Object getArg(int pos) { return arg[pos]; }
70 void set(int pos, int op_, Object arg_) { op[pos] = op_; arg[pos] = arg_; }
71 void set(int pos, Object arg_) { arg[pos] = arg_; }
72 int pop() { size--; arg[size] = null; return op[size]; }
73 void paste(JSFunction other) { for(int i=0; i<other.size; i++) add(other.line[i], other.op[i], other.arg[i]); }
74 JSFunction add(int line, int op_) { return add(line, op_, null); }
75 JSFunction add(int line, int op_, Object arg_) {
76 if (size == op.length - 1) {
77 int[] line2 = new int[op.length * 2]; System.arraycopy(this.line, 0, line2, 0, op.length); this.line = line2;
78 Object[] arg2 = new Object[op.length * 2]; System.arraycopy(arg, 0, arg2, 0, arg.length); arg = arg2;
79 int[] op2 = new int[op.length * 2]; System.arraycopy(op, 0, op2, 0, op.length); op = op2;
81 this.line[size] = line;
89 // Invoking the Bytecode ///////////////////////////////////////////////////////
91 /** returns false if the thread has been paused */
92 static Object eval(final JSContext cx) throws JS.Exn {
93 final int initialPauseCount = cx.pausecount;
94 OUTER: for(;; cx.pc++) {
96 if (cx.f == null || cx.pc >= cx.f.size) return cx.stack.pop();
97 int op = cx.f.op[cx.pc];
98 Object arg = cx.f.arg[cx.pc];
99 if(op == FINALLY_DONE) {
100 FinallyData fd = (FinallyData) cx.stack.pop();
101 if(fd == null) continue OUTER; // NOP
106 case LITERAL: cx.stack.push(arg); break;
107 case OBJECT: cx.stack.push(new JSObj()); break;
108 case ARRAY: cx.stack.push(new JSArray(JS.toNumber(arg).intValue())); break;
109 case DECLARE: cx.scope.declare((String)(arg==null ? cx.stack.peek() : arg)); if(arg != null) cx.stack.push(arg); break;
110 case TOPSCOPE: cx.stack.push(cx.scope); break;
111 case JT: if (JS.toBoolean(cx.stack.pop())) cx.pc += JS.toNumber(arg).intValue() - 1; break;
112 case JF: if (!JS.toBoolean(cx.stack.pop())) cx.pc += JS.toNumber(arg).intValue() - 1; break;
113 case JMP: cx.pc += JS.toNumber(arg).intValue() - 1; break;
114 case POP: cx.stack.pop(); break;
116 int depth = (1 + (arg == null ? 1 : toInt(arg)));
117 Object save = cx.stack.elementAt(cx.stack.size() - 1);
118 for(int i=cx.stack.size() - 1; i > cx.stack.size() - depth; i--)
119 cx.stack.setElementAt(cx.stack.elementAt(i-1), i);
120 cx.stack.setElementAt(save, cx.stack.size() - depth);
122 case DUP: cx.stack.push(cx.stack.peek()); break;
123 case NEWSCOPE: cx.scope = new JSScope(cx.scope); break;
124 case OLDSCOPE: cx.scope = cx.scope.getParentJSScope(); break;
125 case ASSERT: if (!JS.toBoolean(cx.stack.pop())) throw je("assertion failed"); break;
126 case BITNOT: cx.stack.push(new Long(~JS.toLong(cx.stack.pop()))); break;
127 case BANG: cx.stack.push(new Boolean(!JS.toBoolean(cx.stack.pop()))); break;
128 case NEWFUNCTION: cx.stack.push(((JSFunction)arg).cloneWithNewParentJSScope(cx.scope)); break;
132 Object o = cx.stack.pop();
133 if (o == null) cx.stack.push(null);
134 else if (o instanceof JS) cx.stack.push(((JS)o).typeName());
135 else if (o instanceof String) cx.stack.push("string");
136 else if (o instanceof Number) cx.stack.push("number");
137 else if (o instanceof Boolean) cx.stack.push("boolean");
138 else cx.stack.push("unknown");
143 Object o = cx.stack.peek();
144 Enumeration e = ((JS)o).keys();
145 JSArray a = new JSArray();
146 while(e.hasMoreElements()) a.addElement(e.nextElement());
152 cx.stack.push(new LoopMarker(cx.pc, cx.pc > 0 && cx.f.op[cx.pc - 1] == LABEL ?
153 (String)cx.f.arg[cx.pc - 1] : (String)null, cx.scope));
154 cx.stack.push(Boolean.TRUE);
159 while(cx.stack.size() > 0) {
160 Object o = cx.stack.pop();
161 if (o instanceof CallMarker) ee("break or continue not within a loop");
162 if (o instanceof TryMarker) {
163 if(((TryMarker)o).finallyLoc < 0) continue; // no finally block, keep going
164 cx.stack.push(new FinallyData(op, arg));
165 cx.scope = ((TryMarker)o).scope;
166 cx.pc = ((TryMarker)o).finallyLoc - 1;
169 if (o instanceof LoopMarker) {
170 if (arg == null || arg.equals(((LoopMarker)o).label)) {
171 int loopInstructionLocation = ((LoopMarker)o).location;
172 int endOfLoop = ((Integer)cx.f.arg[loopInstructionLocation]).intValue() + loopInstructionLocation;
173 cx.scope = ((LoopMarker)o).scope;
174 if (op == CONTINUE) { cx.stack.push(o); cx.stack.push(Boolean.FALSE); }
175 cx.pc = op == BREAK ? endOfLoop - 1 : loopInstructionLocation;
180 throw new Error("CONTINUE/BREAK invoked but couldn't find LoopMarker at " +
181 cx.getSourceName() + ":" + cx.getLine());
184 int[] jmps = (int[]) arg;
185 // jmps[0] is how far away the catch block is, jmps[1] is how far away the finally block is
186 // each can be < 0 if the specified block does not exist
187 cx.stack.push(new TryMarker(jmps[0] < 0 ? -1 : cx.pc + jmps[0], jmps[1] < 0 ? -1 : cx.pc + jmps[1], cx.scope));
192 Object retval = cx.stack.pop();
193 while(cx.stack.size() > 0) {
194 Object o = cx.stack.pop();
195 if (o instanceof TryMarker) {
196 if(((TryMarker)o).finallyLoc < 0) continue;
197 cx.stack.push(retval);
198 cx.stack.push(new FinallyData(RETURN));
199 cx.scope = ((TryMarker)o).scope;
200 cx.pc = ((TryMarker)o).finallyLoc - 1;
202 } else if (o instanceof CallMarker) {
203 if (cx.scope instanceof JSTrap.JSTrapScope) {
204 JSTrap.JSTrapScope ts = (JSTrap.JSTrapScope)cx.scope;
205 if (!ts.cascadeHappened) {
206 ts.cascadeHappened = true;
207 JSTrap t = ts.t.next;
208 while (t != null && t.f.numFormalArgs == 0) t = t.next;
210 ((JS)ts.t.trapee).put(t.name, ts.val);
211 if (cx.pausecount > initialPauseCount) return null; // we were paused
214 JSArray args = new JSArray();
215 args.addElement(ts.val);
218 cx.scope = new JSTrap.JSTrapScope(cx.f.parentJSScope, t, ts.val);
224 cx.scope = ((CallMarker)o).scope;
225 cx.pc = ((CallMarker)o).pc;
226 cx.f = (JSFunction)((CallMarker)o).f;
227 cx.stack.push(retval);
231 throw new Error("error: RETURN invoked but couldn't find a CallMarker!");
235 Object val = cx.stack.pop();
236 Object key = cx.stack.pop();
237 Object target = cx.stack.peek();
239 throw je("tried to put a value to the " + key + " property on the null value");
240 if (!(target instanceof JS))
241 throw je("tried to put a value to the " + key + " property on a " + target.getClass().getName());
243 throw je("tried to assign \"" + (val==null?"(null)":val.toString()) + "\" to the null key");
245 if (target instanceof JSTrap.JSTrappable) {
246 t = ((JSTrap.JSTrappable)target).getTrap(val);
247 while (t != null && t.f.numFormalArgs == 0) t = t.next;
248 } else if (target instanceof JSTrap.JSTrapScope && key.equals("cascade")) {
249 JSTrap.JSTrapScope ts = (JSTrap.JSTrapScope)target;
251 ts.cascadeHappened = true;
252 while (t != null && t.f.numFormalArgs == 0) t = t.next;
253 if (t == null) target = ts.t.trapee;
256 cx.stack.push(new CallMarker(cx));
257 JSArray args = new JSArray();
258 args.addElement(val);
261 cx.scope = new JSTrap.JSTrapScope(cx.f.parentJSScope, t, val);
265 ((JS)target).put(key, val);
266 if (cx.pausecount > initialPauseCount) return null; // we were paused
275 v = arg == null ? cx.stack.pop() : arg;
283 if (v == null) throw je("tried to get the null key from " + o);
284 if (o == null) throw je("tried to get property \"" + v + "\" from the null value");
285 if (o instanceof String || o instanceof Number || o instanceof Boolean) {
286 ret = Internal.getFromPrimitive(o,v);
289 } else if (o instanceof JS) {
291 if (o instanceof JSTrap.JSTrappable) {
292 t = ((JSTrap.JSTrappable)o).getTrap(v);
293 while (t != null && t.f.numFormalArgs != 0) t = t.next;
294 } else if (o instanceof JSTrap.JSTrapScope && v.equals("cascade")) {
295 t = ((JSTrap.JSTrapScope)o).t.next;
296 while (t != null && t.f.numFormalArgs != 0) t = t.next;
297 if (t == null) o = ((JSTrap.JSTrapScope)o).t.trapee;
300 cx.stack.push(new CallMarker(cx));
301 JSArray args = new JSArray();
304 cx.scope = new JSTrap.JSTrapScope(cx.f.parentJSScope, t, null);
305 ((JSTrap.JSTrapScope)cx.scope).cascadeHappened = true;
309 ret = ((JS)o).get(v);
310 if (cx.pausecount > initialPauseCount) return null; // we were paused
314 throw je("tried to get property " + v + " from a " + o.getClass().getName());
317 case CALL: case CALLMETHOD: {
318 int numArgs = JS.toInt(arg);
319 JSArray arguments = null;
322 Object o = cx.stack.pop();
323 if(o == null) throw je("attempted to call null");
325 Object method = null;
326 if(op == CALLMETHOD) {
328 if (method == null) throw new JS.Exn("cannot call the null method");
330 if(o instanceof String || o instanceof Number || o instanceof Boolean) {
331 arguments = new JSArray();
332 for(int j=numArgs - 1; j >= 0; j--) arguments.setElementAt(cx.stack.pop(), j);
333 ret = Internal.callMethodOnPrimitive(o, method, arguments);
335 cx.pc += 2; // skip the GET and CALL
337 } else if (o instanceof JSCallable) {
338 cx.pc += 2; // skip the GET and CALL
341 // put the args back on the stack and let the GET followed by CALL happen
343 cx.stack.push(method);
347 } else if (o instanceof JSFunction) {
348 // FEATURE: use something similar to call0/call1/call2 here
349 arguments = new JSArray();
350 for(int j=numArgs - 1; j >= 0; j--) arguments.setElementAt(cx.stack.pop(), j);
351 cx.stack.push(new CallMarker(cx));
352 cx.stack.push(arguments);
353 cx.f = (JSFunction)o;
354 cx.scope = new JSScope(cx.f.parentJSScope);
359 if (!(o instanceof JSCallable)) throw new JS.Exn("can't call " + o + " @ " + cx.pc + "\n" + cx.f.dump());
360 JSCallable c = ((JSCallable)o);
362 case 0: ret = c.call0(method); break;
363 case 1: ret = c.call1(method, cx.stack.pop()); break;
364 case 2: { Object first = cx.stack.pop(); ret = c.call2(method, cx.stack.pop(), first); break; }
366 arguments = new JSArray();
367 for(int j=numArgs - 1; j >= 0; j--) arguments.setElementAt(cx.stack.pop(), j);
368 ret = c.call(method, arguments);
369 if (cx.pausecount > initialPauseCount) return null; // we were paused
379 Object o = cx.stack.pop();
380 if(o instanceof JS.Exn) throw (JS.Exn)o;
384 case ASSIGN_SUB: case ASSIGN_ADD: {
385 Object val = cx.stack.pop();
386 Object old = cx.stack.pop();
387 Object key = cx.stack.pop();
388 Object obj = cx.stack.peek();
389 if (val instanceof JSFunction && obj instanceof JSScope) {
390 JSScope parent = (JSScope)obj;
391 while(parent.getParentJSScope() != null) parent = parent.getParentJSScope();
392 if (parent instanceof JSTrap.JSTrappable) {
393 JSTrap.JSTrappable b = (JSTrap.JSTrappable)parent;
394 if (op == ASSIGN_ADD) JSTrap.addTrap(b, key, (JSFunction)val);
395 else JSTrap.delTrap(b, key, (JSFunction)val);
396 // skip over the "normal" implementation of +=/-=
397 cx.pc += ((Integer)arg).intValue() - 1;
401 // use the "normal" implementation
409 int count = ((Number)arg).intValue();
410 if(count < 2) throw new Error("this should never happen");
413 Object right = cx.stack.pop();
414 Object left = cx.stack.pop();
415 if(left instanceof String || right instanceof String)
416 cx.stack.push(JS.toString(left).concat(JS.toString(right)));
417 else cx.stack.push(new Double(JS.toDouble(left) + JS.toDouble(right)));
419 Object[] args = new Object[count];
420 while(--count >= 0) args[count] = cx.stack.pop();
421 if(args[0] instanceof String) {
422 StringBuffer sb = new StringBuffer(64);
423 for(int i=0;i<args.length;i++) sb.append(JS.toString(args[i]));
424 cx.stack.push(sb.toString());
427 for(int i=0;i<args.length;i++) if(args[i] instanceof String) numStrings++;
428 if(numStrings == 0) {
430 for(int i=0;i<args.length;i++) d += JS.toDouble(args[i]);
431 cx.stack.push(new Double(d));
434 StringBuffer sb = new StringBuffer(64);
435 if(!(args[0] instanceof String || args[1] instanceof String)) {
438 d += JS.toDouble(args[i++]);
439 } while(!(args[i] instanceof String));
440 sb.append(JS.toString(new Double(d)));
442 while(i < args.length) sb.append(JS.toString(args[i++]));
443 cx.stack.push(sb.toString());
451 Object right = cx.stack.pop();
452 Object left = cx.stack.pop();
455 case BITOR: cx.stack.push(new Long(JS.toLong(left) | JS.toLong(right))); break;
456 case BITXOR: cx.stack.push(new Long(JS.toLong(left) ^ JS.toLong(right))); break;
457 case BITAND: cx.stack.push(new Long(JS.toLong(left) & JS.toLong(right))); break;
459 case SUB: cx.stack.push(new Double(JS.toDouble(left) - JS.toDouble(right))); break;
460 case MUL: cx.stack.push(new Double(JS.toDouble(left) * JS.toDouble(right))); break;
461 case DIV: cx.stack.push(new Double(JS.toDouble(left) / JS.toDouble(right))); break;
462 case MOD: cx.stack.push(new Double(JS.toDouble(left) % JS.toDouble(right))); break;
464 case LSH: cx.stack.push(new Long(JS.toLong(left) << JS.toLong(right))); break;
465 case RSH: cx.stack.push(new Long(JS.toLong(left) >> JS.toLong(right))); break;
466 case URSH: cx.stack.push(new Long(JS.toLong(left) >>> JS.toLong(right))); break;
468 case LT: case LE: case GT: case GE: {
469 if (left == null) left = new Integer(0);
470 if (right == null) right = new Integer(0);
472 if (left instanceof String || right instanceof String) {
473 result = left.toString().compareTo(right.toString());
475 result = (int)java.lang.Math.ceil(JS.toDouble(left) - JS.toDouble(right));
477 cx.stack.push(new Boolean((op == LT && result < 0) || (op == LE && result <= 0) ||
478 (op == GT && result > 0) || (op == GE && result >= 0)));
487 if (l == null) { Object tmp = r; r = l; l = tmp; }
488 if (l == null && r == null) ret = true;
489 else if (r == null) ret = false; // l != null, so its false
490 else if (l instanceof Boolean) ret = new Boolean(JS.toBoolean(r)).equals(l);
491 else if (l instanceof Number) ret = JS.toNumber(r).doubleValue() == JS.toNumber(l).doubleValue();
492 else if (l instanceof String) ret = r != null && l.equals(r.toString());
493 else ret = l.equals(r);
494 cx.stack.push(new Boolean(op == EQ ? ret : !ret)); break;
497 default: throw new Error("unknown opcode " + op);
502 while(cx.stack.size() > 0) {
503 Object o = cx.stack.pop();
504 if (o instanceof CatchMarker || o instanceof TryMarker) {
505 boolean inCatch = o instanceof CatchMarker;
508 if(((TryMarker)o).finallyLoc < 0) continue; // no finally block, keep going
510 if(!inCatch && ((TryMarker)o).catchLoc >= 0) {
511 // run the catch block, this will implicitly run the finally block, if it exists
513 cx.stack.push(catchMarker);
514 cx.stack.push(e.getObject());
515 cx.scope = ((TryMarker)o).scope;
516 cx.pc = ((TryMarker)o).catchLoc - 1;
520 cx.stack.push(new FinallyData(THROW));
521 cx.scope = ((TryMarker)o).scope;
522 cx.pc = ((TryMarker)o).finallyLoc - 1;
526 // no handler found within this func
527 if(o instanceof CallMarker) throw e;
535 // Debugging //////////////////////////////////////////////////////////////////////
537 public String toString() { return "JSFunction [" + sourceName + ":" + firstLine + "]"; }
538 public String dump() {
539 StringBuffer sb = new StringBuffer(1024);
540 sb.append("\n" + sourceName + ": " + firstLine + "\n");
541 for (int i=0; i < size; i++) {
545 sb.append(bytecodeToString[-op[i]]);
547 sb.append(codeToString[op[i]]);
549 sb.append(arg[i] == null ? "(no arg)" : arg[i]);
550 if((op[i] == JF || op[i] == JT || op[i] == JMP) && arg[i] != null && arg[i] instanceof Number) {
551 sb.append(" jump to ").append(i+((Number) arg[i]).intValue());
552 } else if(op[i] == TRY) {
553 int[] jmps = (int[]) arg[i];
554 sb.append(" catch: ").append(jmps[0] < 0 ? "No catch block" : ""+(i+jmps[0]));
555 sb.append(" finally: ").append(jmps[1] < 0 ? "No finally block" : ""+(i+jmps[1]));
559 return sb.toString();
563 // Exception Stuff ////////////////////////////////////////////////////////////////
565 static class EvaluatorException extends RuntimeException { public EvaluatorException(String s) { super(s); } }
566 static EvaluatorException ee(String s) {
567 throw new EvaluatorException(JSContext.getSourceName() + ":" + JSContext.getLine() + " " + s);
569 static JS.Exn je(String s) {
570 throw new JS.Exn(JSContext.getSourceName() + ":" + JSContext.getLine() + " " + s);
574 // Markers //////////////////////////////////////////////////////////////////////
576 public static class CallMarker {
580 public CallMarker(JSContext cx) { pc = cx.pc + 1; scope = cx.scope; f = cx.f; }
583 public static class CatchMarker { public CatchMarker() { } }
584 private static CatchMarker catchMarker = new CatchMarker();
586 public static class LoopMarker {
589 public JSScope scope;
590 public LoopMarker(int location, String label, JSScope scope) {
591 this.location = location;
596 public static class TryMarker {
598 public int finallyLoc;
599 public JSScope scope;
600 public TryMarker(int catchLoc, int finallyLoc, JSScope scope) {
601 this.catchLoc = catchLoc;
602 this.finallyLoc = finallyLoc;
606 public static class FinallyData {
609 public FinallyData(int op, Object arg) { this.op = op; this.arg = arg; }
610 public FinallyData(int op) { this(op,null); }