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;
115 case SWAP: { Object o1 = cx.stack.pop(); Object o2 = cx.stack.pop(); cx.stack.push(o1); cx.stack.push(o2); break; }
116 case DUP: cx.stack.push(cx.stack.peek()); break;
117 case NEWSCOPE: cx.scope = new JSScope(cx.scope); break;
118 case OLDSCOPE: cx.scope = cx.scope.getParentJSScope(); break;
119 case ASSERT: if (!JS.toBoolean(cx.stack.pop())) throw je("assertion failed"); break;
120 case BITNOT: cx.stack.push(new Long(~JS.toLong(cx.stack.pop()))); break;
121 case BANG: cx.stack.push(new Boolean(!JS.toBoolean(cx.stack.pop()))); break;
122 case NEWFUNCTION: cx.stack.push(((JSFunction)arg).cloneWithNewParentJSScope(cx.scope)); break;
126 Object o = cx.stack.pop();
127 if (o == null) cx.stack.push(null);
128 else if (o instanceof JS) cx.stack.push(((JS)o).typeName());
129 else if (o instanceof String) cx.stack.push("string");
130 else if (o instanceof Number) cx.stack.push("number");
131 else if (o instanceof Boolean) cx.stack.push("boolean");
132 else cx.stack.push("unknown");
137 Object o = cx.stack.peek();
138 Enumeration e = ((JS)o).keys();
139 JSArray a = new JSArray();
140 while(e.hasMoreElements()) a.addElement(e.nextElement());
146 cx.stack.push(new LoopMarker(cx.pc, cx.pc > 0 && cx.f.op[cx.pc - 1] == LABEL ?
147 (String)cx.f.arg[cx.pc - 1] : (String)null, cx.scope));
148 cx.stack.push(Boolean.TRUE);
153 while(cx.stack.size() > 0) {
154 Object o = cx.stack.pop();
155 if (o instanceof CallMarker) ee("break or continue not within a loop");
156 if (o instanceof TryMarker) {
157 if(((TryMarker)o).finallyLoc < 0) continue; // no finally block, keep going
158 cx.stack.push(new FinallyData(op, arg));
159 cx.scope = ((TryMarker)o).scope;
160 cx.pc = ((TryMarker)o).finallyLoc - 1;
163 if (o instanceof LoopMarker) {
164 if (arg == null || arg.equals(((LoopMarker)o).label)) {
165 int loopInstructionLocation = ((LoopMarker)o).location;
166 int endOfLoop = ((Integer)cx.f.arg[loopInstructionLocation]).intValue() + loopInstructionLocation;
167 cx.scope = ((LoopMarker)o).scope;
168 if (op == CONTINUE) { cx.stack.push(o); cx.stack.push(Boolean.FALSE); }
169 cx.pc = op == BREAK ? endOfLoop - 1 : loopInstructionLocation;
174 throw new Error("CONTINUE/BREAK invoked but couldn't find LoopMarker at " +
175 cx.getSourceName() + ":" + cx.getLine());
178 int[] jmps = (int[]) arg;
179 // jmps[0] is how far away the catch block is, jmps[1] is how far away the finally block is
180 // each can be < 0 if the specified block does not exist
181 cx.stack.push(new TryMarker(jmps[0] < 0 ? -1 : cx.pc + jmps[0], jmps[1] < 0 ? -1 : cx.pc + jmps[1], cx.scope));
186 Object retval = cx.stack.pop();
187 while(cx.stack.size() > 0) {
188 Object o = cx.stack.pop();
189 if (o instanceof TryMarker) {
190 if(((TryMarker)o).finallyLoc < 0) continue;
191 cx.stack.push(retval);
192 cx.stack.push(new FinallyData(RETURN));
193 cx.scope = ((TryMarker)o).scope;
194 cx.pc = ((TryMarker)o).finallyLoc - 1;
196 } else if (o instanceof CallMarker) {
197 if (cx.scope instanceof JSTrap.JSTrapScope) {
198 JSTrap.JSTrapScope ts = (JSTrap.JSTrapScope)cx.scope;
199 if (!ts.cascadeHappened) {
200 ts.cascadeHappened = true;
201 JSTrap t = ts.t.next;
202 while (t != null && t.f.numFormalArgs == 0) t = t.next;
204 ((JS)ts.t.trapee).put(t.name, ts.val);
205 if (cx.pausecount > initialPauseCount) return null; // we were paused
208 JSArray args = new JSArray();
209 args.addElement(ts.val);
212 cx.scope = new JSTrap.JSTrapScope(cx.f.parentJSScope, t, ts.val);
218 cx.scope = ((CallMarker)o).scope;
219 cx.pc = ((CallMarker)o).pc;
220 cx.f = (JSFunction)((CallMarker)o).f;
221 cx.stack.push(retval);
225 throw new Error("error: RETURN invoked but couldn't find a CallMarker!");
229 Object val = cx.stack.pop();
230 Object key = cx.stack.pop();
231 Object target = cx.stack.peek();
233 throw je("tried to put a value to the " + key + " property on the null value");
234 if (!(target instanceof JS))
235 throw je("tried to put a value to the " + key + " property on a " + target.getClass().getName());
237 throw je("tried to assign \"" + (val==null?"(null)":val.toString()) + "\" to the null key");
239 if (target instanceof JSTrap.JSTrappable) {
240 t = ((JSTrap.JSTrappable)target).getTrap(val);
241 while (t != null && t.f.numFormalArgs == 0) t = t.next;
242 } else if (target instanceof JSTrap.JSTrapScope && key.equals("cascade")) {
243 JSTrap.JSTrapScope ts = (JSTrap.JSTrapScope)target;
245 ts.cascadeHappened = true;
246 while (t != null && t.f.numFormalArgs == 0) t = t.next;
247 if (t == null) target = ts.t.trapee;
250 cx.stack.push(new CallMarker(cx));
251 JSArray args = new JSArray();
252 args.addElement(val);
255 cx.scope = new JSTrap.JSTrapScope(cx.f.parentJSScope, t, val);
259 ((JS)target).put(key, val);
260 if (cx.pausecount > initialPauseCount) return null; // we were paused
269 v = arg == null ? cx.stack.pop() : arg;
277 if (o == null) throw je("tried to get property \"" + v + "\" from the null value");
278 if (v == null) throw je("tried to get the null key from " + o);
279 if (o instanceof String || o instanceof Number || o instanceof Boolean) {
280 ret = Internal.getFromPrimitive(o,v);
283 } else if (o instanceof JS) {
285 if (o instanceof JSTrap.JSTrappable) {
286 t = ((JSTrap.JSTrappable)o).getTrap(v);
287 while (t != null && t.f.numFormalArgs != 0) t = t.next;
288 } else if (o instanceof JSTrap.JSTrapScope && v.equals("cascade")) {
289 t = ((JSTrap.JSTrapScope)o).t.next;
290 while (t != null && t.f.numFormalArgs != 0) t = t.next;
291 if (t == null) o = ((JSTrap.JSTrapScope)o).t.trapee;
294 cx.stack.push(new CallMarker(cx));
295 JSArray args = new JSArray();
298 cx.scope = new JSTrap.JSTrapScope(cx.f.parentJSScope, t, null);
299 ((JSTrap.JSTrapScope)cx.scope).cascadeHappened = true;
303 ret = ((JS)o).get(v);
304 if (cx.pausecount > initialPauseCount) return null; // we were paused
308 throw je("tried to get property " + v + " from a " + o.getClass().getName());
311 case CALL: case CALLMETHOD: {
312 int numArgs = JS.toNumber(arg).intValue();
313 Object o = cx.stack.pop();
314 if(o == null) throw je("attempted to call null");
316 Object method = null;
317 if(op == CALLMETHOD) {
319 if (method == null) throw new JS.Exn("cannot call the null method");
321 if(o instanceof String || o instanceof Number || o instanceof Boolean) {
322 JSArray arguments = new JSArray();
323 for(int j=numArgs - 1; j >= 0; j--) arguments.setElementAt(cx.stack.pop(), j);
324 ret = Internal.callMethodOnPrimitive(o,method,arguments);
326 cx.pc += 2; // skip the GET and CALL
328 } else if (o instanceof JSCallable) {
331 // put the args back on the stack and let the GET followed by CALL happen
333 cx.stack.push(method);
337 } else if (o instanceof JSFunction) {
338 // FEATURE: use something similar to call0/call1/call2 here
339 JSArray arguments = new JSArray();
340 for(int j=numArgs - 1; j >= 0; j--) arguments.setElementAt(cx.stack.pop(), j);
341 cx.stack.push(new CallMarker(cx));
342 cx.stack.push(arguments);
343 cx.f = (JSFunction)o;
344 cx.scope = new JSScope(cx.f.parentJSScope);
349 JSCallable c = ((JSCallable)o);
351 case 0: ret = c.call0(method); break;
352 case 1: ret = c.call1(method, cx.stack.pop()); break;
353 case 2: ret = c.call2(method, cx.stack.pop(), cx.stack.pop()); break;
355 JSArray arguments = new JSArray();
356 for(int j=numArgs - 1; j >= 0; j--) arguments.setElementAt(cx.stack.pop(), j);
357 ret = c.call(method, arguments);
358 if (cx.pausecount > initialPauseCount) return null; // we were paused
363 if (method != null) cx.pc += 2; // skip the GET and CALL if this was a GETCALL
369 Object o = cx.stack.pop();
370 if(o instanceof JS.Exn) throw (JS.Exn)o;
374 case ASSIGN_SUB: case ASSIGN_ADD: {
375 Object val = cx.stack.pop();
376 Object old = cx.stack.pop();
377 Object key = cx.stack.pop();
378 Object obj = cx.stack.peek();
379 if (val instanceof JSFunction && obj instanceof JSScope) {
380 JSScope parent = (JSScope)obj;
381 while(parent.getParentJSScope() != null) parent = parent.getParentJSScope();
382 if (parent instanceof JSTrap.JSTrappable) {
383 JSTrap.JSTrappable b = (JSTrap.JSTrappable)parent;
384 if (op == ASSIGN_ADD) JSTrap.addTrap(b, key, (JSFunction)val);
385 else JSTrap.delTrap(b, key, (JSFunction)val);
386 // skip over the "normal" implementation of +=/-=
387 cx.pc += ((Integer)arg).intValue() - 1;
391 // use the "normal" implementation
399 int count = ((Number)arg).intValue();
400 if(count < 2) throw new Error("this should never happen");
403 Object right = cx.stack.pop();
404 Object left = cx.stack.pop();
405 if(left instanceof String || right instanceof String)
406 cx.stack.push(JS.toString(left).concat(JS.toString(right)));
407 else cx.stack.push(new Double(JS.toDouble(left) + JS.toDouble(right)));
409 Object[] args = new Object[count];
410 while(--count >= 0) args[count] = cx.stack.pop();
411 if(args[0] instanceof String) {
412 StringBuffer sb = new StringBuffer(64);
413 for(int i=0;i<args.length;i++) sb.append(JS.toString(args[i]));
414 cx.stack.push(sb.toString());
417 for(int i=0;i<args.length;i++) if(args[i] instanceof String) numStrings++;
418 if(numStrings == 0) {
420 for(int i=0;i<args.length;i++) d += JS.toDouble(args[i]);
421 cx.stack.push(new Double(d));
424 StringBuffer sb = new StringBuffer(64);
425 if(!(args[0] instanceof String || args[1] instanceof String)) {
428 d += JS.toDouble(args[i++]);
429 } while(!(args[i] instanceof String));
430 sb.append(JS.toString(new Double(d)));
432 while(i < args.length) sb.append(JS.toString(args[i++]));
433 cx.stack.push(sb.toString());
441 Object right = cx.stack.pop();
442 Object left = cx.stack.pop();
445 case BITOR: cx.stack.push(new Long(JS.toLong(left) | JS.toLong(right))); break;
446 case BITXOR: cx.stack.push(new Long(JS.toLong(left) ^ JS.toLong(right))); break;
447 case BITAND: cx.stack.push(new Long(JS.toLong(left) & JS.toLong(right))); break;
449 case SUB: cx.stack.push(new Double(JS.toDouble(left) - JS.toDouble(right))); break;
450 case MUL: cx.stack.push(new Double(JS.toDouble(left) * JS.toDouble(right))); break;
451 case DIV: cx.stack.push(new Double(JS.toDouble(left) / JS.toDouble(right))); break;
452 case MOD: cx.stack.push(new Double(JS.toDouble(left) % JS.toDouble(right))); break;
454 case LSH: cx.stack.push(new Long(JS.toLong(left) << JS.toLong(right))); break;
455 case RSH: cx.stack.push(new Long(JS.toLong(left) >> JS.toLong(right))); break;
456 case URSH: cx.stack.push(new Long(JS.toLong(left) >>> JS.toLong(right))); break;
458 case LT: case LE: case GT: case GE: {
459 if (left == null) left = new Integer(0);
460 if (right == null) right = new Integer(0);
462 if (left instanceof String || right instanceof String) {
463 result = left.toString().compareTo(right.toString());
465 result = (int)java.lang.Math.ceil(JS.toDouble(left) - JS.toDouble(right));
467 cx.stack.push(new Boolean((op == LT && result < 0) || (op == LE && result <= 0) ||
468 (op == GT && result > 0) || (op == GE && result >= 0)));
477 if (l == null) { Object tmp = r; r = l; l = tmp; }
478 if (l == null && r == null) ret = true;
479 else if (r == null) ret = false; // l != null, so its false
480 else if (l instanceof Boolean) ret = new Boolean(JS.toBoolean(r)).equals(l);
481 else if (l instanceof Number) ret = JS.toNumber(r).doubleValue() == JS.toNumber(l).doubleValue();
482 else if (l instanceof String) ret = r != null && l.equals(r.toString());
483 else ret = l.equals(r);
484 cx.stack.push(new Boolean(op == EQ ? ret : !ret)); break;
487 default: throw new Error("unknown opcode " + op);
492 while(cx.stack.size() > 0) {
493 Object o = cx.stack.pop();
494 if (o instanceof CatchMarker || o instanceof TryMarker) {
495 boolean inCatch = o instanceof CatchMarker;
498 if(((TryMarker)o).finallyLoc < 0) continue; // no finally block, keep going
500 if(!inCatch && ((TryMarker)o).catchLoc >= 0) {
501 // run the catch block, this will implicitly run the finally block, if it exists
503 cx.stack.push(catchMarker);
504 cx.stack.push(e.getObject());
505 cx.scope = ((TryMarker)o).scope;
506 cx.pc = ((TryMarker)o).catchLoc - 1;
510 cx.stack.push(new FinallyData(THROW));
511 cx.scope = ((TryMarker)o).scope;
512 cx.pc = ((TryMarker)o).finallyLoc - 1;
516 // no handler found within this func
517 if(o instanceof CallMarker) throw e;
525 // Debugging //////////////////////////////////////////////////////////////////////
527 public String toString() { return "JSFunction [" + sourceName + ":" + firstLine + "]"; }
528 public String dump() {
529 StringBuffer sb = new StringBuffer(1024);
530 sb.append("\n" + sourceName + ": " + firstLine + "\n");
531 for (int i=0; i < size; i++) {
535 sb.append(bytecodeToString[-op[i]]);
537 sb.append(codeToString[op[i]]);
539 sb.append(arg[i] == null ? "(no arg)" : arg[i]);
540 if((op[i] == JF || op[i] == JT || op[i] == JMP) && arg[i] != null && arg[i] instanceof Number) {
541 sb.append(" jump to ").append(i+((Number) arg[i]).intValue());
542 } else if(op[i] == TRY) {
543 int[] jmps = (int[]) arg[i];
544 sb.append(" catch: ").append(jmps[0] < 0 ? "No catch block" : ""+(i+jmps[0]));
545 sb.append(" finally: ").append(jmps[1] < 0 ? "No finally block" : ""+(i+jmps[1]));
549 return sb.toString();
553 // Exception Stuff ////////////////////////////////////////////////////////////////
555 static class EvaluatorException extends RuntimeException { public EvaluatorException(String s) { super(s); } }
556 static EvaluatorException ee(String s) {
557 throw new EvaluatorException(JSContext.getSourceName() + ":" + JSContext.getLine() + " " + s);
559 static JS.Exn je(String s) {
560 throw new JS.Exn(JSContext.getSourceName() + ":" + JSContext.getLine() + " " + s);
564 // Markers //////////////////////////////////////////////////////////////////////
566 public static class CallMarker {
570 public CallMarker(JSContext cx) { pc = cx.pc + 1; scope = cx.scope; f = cx.f; }
573 public static class CatchMarker { public CatchMarker() { } }
574 private static CatchMarker catchMarker = new CatchMarker();
576 public static class LoopMarker {
579 public JSScope scope;
580 public LoopMarker(int location, String label, JSScope scope) {
581 this.location = location;
586 public static class TryMarker {
588 public int finallyLoc;
589 public JSScope scope;
590 public TryMarker(int catchLoc, int finallyLoc, JSScope scope) {
591 this.catchLoc = catchLoc;
592 this.finallyLoc = finallyLoc;
596 public static class FinallyData {
599 public FinallyData(int op, Object arg) { this.op = op; this.arg = arg; }
600 public FinallyData(int op) { this(op,null); }