1 // Copyright 2003 Adam Megacz, see the COPYING file for licensing [GPL]
7 /** A JavaScript function, compiled into bytecode */
8 public class JSFunction extends JSCallable implements ByteCodes, Tokens {
10 /** Note: code gets run in an <i>unpauseable</i> context. */
11 public Object call(JSArray args) {
12 Context cx = new JSContext(this, false);
14 return cx.stack.pop();
18 // Fields and Accessors ///////////////////////////////////////////////
20 int numFormalArgs = 0; ///< the number of formal arguments
21 String sourceName; ///< the source code file that this block was drawn from
22 int[] line = new int[10]; ///< the line numbers
23 private int firstLine = -1; ///< the first line of this script
24 int[] op = new int[10]; ///< the instructions
25 Object[] arg = new Object[10]; ///< the arguments to the instructions
26 int size = 0; ///< the number of instruction/argument pairs
27 JSScope parentJSScope; ///< the default scope to use as a parent scope when executing this
30 // Constructors ////////////////////////////////////////////////////////
32 public JSFunction cloneWithNewParentJSScope(JSScope s) {
33 JSFunction ret = new JSFunction(sourceName, firstLine, s);
34 // Reuse the same op, arg, line, and size variables for the new "instance" of the function
35 // NOTE: Neither *this* function nor the new function should be modified after this call
40 ret.numFormalArgs = this.numFormalArgs;
44 private JSFunction(String sourceName, int firstLine, JSScope parentJSScope) {
45 this.sourceName = sourceName;
46 this.firstLine = firstLine;
47 this.parentJSScope = parentJSScope;
50 protected JSFunction(String sourceName, int firstLine, Reader sourceCode, JSScope parentJSScope) throws IOException {
51 this(sourceName, firstLine, parentJSScope);
52 if (sourceCode == null) return;
53 Parser p = new Parser(sourceCode, sourceName, firstLine);
56 p.parseStatement(this, null);
59 add(-1, LITERAL, null);
65 // Adding and Altering Bytecodes ///////////////////////////////////////////////////
67 int get(int pos) { return op[pos]; }
68 Object getArg(int pos) { return arg[pos]; }
69 void set(int pos, int op_, Object arg_) { op[pos] = op_; arg[pos] = arg_; }
70 void set(int pos, Object arg_) { arg[pos] = arg_; }
71 int pop() { size--; arg[size] = null; return op[size]; }
72 void paste(JSFunction other) { for(int i=0; i<other.size; i++) add(other.line[i], other.op[i], other.arg[i]); }
73 JSFunction add(int line, int op_) { return add(line, op_, null); }
74 JSFunction add(int line, int op_, Object arg_) {
75 if (size == op.length - 1) {
76 int[] line2 = new int[op.length * 2]; System.arraycopy(this.line, 0, line2, 0, op.length); this.line = line2;
77 Object[] arg2 = new Object[op.length * 2]; System.arraycopy(arg, 0, arg2, 0, arg.length); arg = arg2;
78 int[] op2 = new int[op.length * 2]; System.arraycopy(op, 0, op2, 0, op.length); op = op2;
80 this.line[size] = line;
88 // Invoking the Bytecode ///////////////////////////////////////////////////////
90 /** returns false if the thread has been paused */
91 static Object eval(final JSContext cx) throws JS.Exn {
92 final initialPauseCount = cx.pausecount;
93 OUTER: for(;; cx.pc++) {
95 if (cx.f == null || cx.pc >= cx.f.size) return cx.stack.pop();
96 int op = cx.f.op[cx.pc];
97 Object arg = cx.f.arg[cx.pc];
98 if(op == FINALLY_DONE) {
99 FinallyData fd = (FinallyData) cx.stack.pop();
100 if(fd == null) continue OUTER; // NOP
105 case LITERAL: cx.stack.push(arg); break;
106 case OBJECT: cx.stack.push(new JSObj()); break;
107 case ARRAY: cx.stack.push(new JSArray(JS.toNumber(arg).intValue())); break;
108 case DECLARE: cx.scope.declare((String)(arg==null ? cx.stack.peek() : arg)); if(arg != null) cx.stack.push(arg); break;
109 case TOPSCOPE: cx.stack.push(cx.scope); break;
110 case JT: if (JS.toBoolean(cx.stack.pop())) cx.pc += JS.toNumber(arg).intValue() - 1; break;
111 case JF: if (!JS.toBoolean(cx.stack.pop())) cx.pc += JS.toNumber(arg).intValue() - 1; break;
112 case JMP: cx.pc += JS.toNumber(arg).intValue() - 1; break;
113 case POP: cx.stack.pop(); break;
114 case SWAP: { Object o1 = cx.stack.pop(); Object o2 = cx.stack.pop(); cx.stack.push(o1); cx.stack.push(o2); break; }
115 case DUP: cx.stack.push(cx.stack.peek()); break;
116 case NEWSCOPE: cx.scope = new JSScope(cx.scope); break;
117 case OLDSCOPE: cx.scope = cx.scope.getParentJSScope(); break;
118 case ASSERT: if (!JS.toBoolean(cx.stack.pop())) throw je("assertion failed"); break;
119 case BITNOT: cx.stack.push(new Long(~JS.toLong(cx.stack.pop()))); break;
120 case BANG: cx.stack.push(new Boolean(!JS.toBoolean(cx.stack.pop()))); break;
121 case NEWFUNCTION: cx.stack.push(((JSFunction)arg).cloneWithNewParentJSScope(cx.scope)); break;
125 Object o = cx.stack.pop();
126 if (o == null) cx.stack.push(null);
127 else if (o instanceof JS) cx.stack.push(((JS)o).typeName());
128 else if (o instanceof String) cx.stack.push("string");
129 else if (o instanceof Number) cx.stack.push("number");
130 else if (o instanceof Boolean) cx.stack.push("boolean");
131 else cx.stack.push("unknown");
136 Object o = cx.stack.peek();
137 Enumeration e = ((JS)o).keys();
138 JSArray a = new JSArray();
139 while(e.hasMoreElements()) a.addElement(e.nextElement());
145 cx.stack.push(new LoopMarker(cx.pc, cx.pc > 0 && cx.f.op[cx.pc - 1] == LABEL ?
146 (String)cx.f.arg[cx.pc - 1] : (String)null, cx.scope));
147 cx.stack.push(Boolean.TRUE);
152 while(cx.stack.size() > 0) {
153 Object o = cx.stack.pop();
154 if (o instanceof CallMarker) ee("break or continue not within a loop");
155 if (o instanceof TryMarker) {
156 if(((TryMarker)o).finallyLoc < 0) continue; // no finally block, keep going
157 cx.stack.push(new FinallyData(op, arg));
158 cx.scope = ((TryMarker)o).scope;
159 cx.pc = ((TryMarker)o).finallyLoc - 1;
162 if (o instanceof LoopMarker) {
163 if (arg == null || arg.equals(((LoopMarker)o).label)) {
164 int loopInstructionLocation = ((LoopMarker)o).location;
165 int endOfLoop = ((Integer)cx.f.arg[loopInstructionLocation]).intValue() + loopInstructionLocation;
166 cx.scope = ((LoopMarker)o).scope;
167 if (op == CONTINUE) { cx.stack.push(o); cx.stack.push(Boolean.FALSE); }
168 cx.pc = op == BREAK ? endOfLoop - 1 : loopInstructionLocation;
173 throw new Error("CONTINUE/BREAK invoked but couldn't find LoopMarker at " +
174 cx.getSourceName() + ":" + cx.getLine());
177 int[] jmps = (int[]) arg;
178 // jmps[0] is how far away the catch block is, jmps[1] is how far away the finally block is
179 // each can be < 0 if the specified block does not exist
180 cx.stack.push(new TryMarker(jmps[0] < 0 ? -1 : cx.pc + jmps[0], jmps[1] < 0 ? -1 : cx.pc + jmps[1], cx.scope));
185 Object retval = cx.stack.pop();
186 while(cx.stack.size() > 0) {
187 Object o = cx.stack.pop();
188 if (o instanceof TryMarker) {
189 if(((TryMarker)o).finallyLoc < 0) continue;
190 cx.stack.push(retval);
191 cx.stack.push(new FinallyData(RETURN));
192 cx.scope = ((TryMarker)o).scope;
193 cx.pc = ((TryMarker)o).finallyLoc - 1;
195 } else if (o instanceof CallMarker) {
196 if (cx.scope instanceof JSTrapScope) {
197 JSTrapScope ts = (JSTrapScope)cx.scope;
198 if (!ts.cascadeHappened) {
199 ts.cascadeHappened = true;
200 JSTrap t = ts.t.next;
201 while (t != null && t.f.numFormalArgs == 0) t = t.next;
203 ts.trappee.put(key, val);
204 if (cx.pausecount > initialPauseCount) return; // we were paused
207 JSArray args = new JSArray();
208 args.addElement(ts.val);
211 cx.scope = new JSTrap.JSTrapScope(cx.f.parentJSScope, ts.val);
217 cx.scope = ((CallMarker)o).scope;
218 cx.pc = ((CallMarker)o).pc;
219 cx.f = (JSFunction)((CallMarker)o).f;
220 cx.stack.push(retval);
224 throw new Error("error: RETURN invoked but couldn't find a CallMarker!");
228 Object val = cx.stack.pop();
229 Object key = cx.stack.pop();
230 Object target = cx.stack.peek();
232 throw je("tried to put a value to the " + key + " property on the null value");
233 if (!(target instanceof JS))
234 throw je("tried to put a value to the " + key + " property on a " + target.getClass().getName());
236 throw je("tried to assign \"" + (val==null?"(null)":val.toString()) + "\" to the null key");
238 if (o instanceof JSTrap.JSTrappable) {
239 t = ((JSTrap.JSTrappable)o).getTrap(v);
240 while (t != null && t.f.numFormalArgs == 0) t = t.next;
241 } else if (o instanceof JSTrap.JSTrapScope && key.equals("cascade")) {
242 JSTrap.JSTrapScope ts = (JSTrap.JSTrapScope)o;
244 ts.cascadeHappened = true;
245 while (t != null && t.f.numFormalArgs == 0) t = t.next;
246 if (t == null) o = ts.t.trappee;
249 cx.stack.push(new CallMarker(cx));
250 JSArray args = new JSArray();
251 args.addElement(val);
254 cx.scope = new JSTrap.JSTrapScope(cx.f.parentJSScope, val);
258 ((JS)target).put(key, val);
259 if (cx.pausecount > initialPauseCount) return; // we were paused
268 v = arg == null ? cx.stack.pop() : arg;
276 if (o == null) throw je("tried to get property \"" + v + "\" from the null value");
277 if (v == null) throw je("tried to get the null key from " + o);
278 if (o instanceof String || o instanceof Number || o instanceof Boolean) {
279 ret = Internal.getFromPrimitive(o,v);
282 } else if (o instanceof JS) {
284 if (o instanceof JSTrap.JSTrappable) {
285 t = ((JSTrap.JSTrappable)o).getTrap(v);
286 while (t != null && t.f.numFormalArgs != 0) t = t.next;
287 } else if (o instanceof JSTrap.JSTrapScope && key.equals("cascade")) {
288 t = ((JSTrap.JSTrapScope)o).t.next;
289 while (t != null && t.f.numFormalArgs != 0) t = t.next;
290 if (t == null) o = ((JSTrap.JSTrapScope)o).t.trappee;
293 cx.stack.push(new CallMarker(cx));
294 JSArray args = new JSArray();
297 cx.scope = new JSTrap.JSTrapScope(cx.f.parentJSScope, null);
298 ((JSTrap.JSTrapScope)cx.scope).cascadeHappened = true;
302 ret = ((JS)o).get(v);
303 if (cx.pausecount > initialPauseCount) return; // we were paused
307 throw je("tried to get property " + v + " from a " + o.getClass().getName());
310 case CALL: case CALLMETHOD: {
311 int numArgs = JS.toNumber(arg).intValue();
312 Object o = cx.stack.pop();
313 if(o == null) throw je("attempted to call null");
315 Object method = null;
316 if(op == CALLMETHOD) {
318 if (method == null) throw new JS.Exn("cannot call the null method");
320 if(o instanceof String || o instanceof Number || o instanceof Boolean) {
321 JSArray arguments = new JSArray();
322 for(int j=numArgs - 1; j >= 0; j--) arguments.setElementAt(cx.stack.pop(), j);
323 ret = Internal.callMethodOnPrimitive(o,method,arguments);
325 cx.pc += 2; // skip the GET and CALL
327 } else if (o instanceof JSCallable) {
330 // put the args back on the stack and let the GET followed by CALL happen
332 cx.stack.push(method);
336 } else if (o instanceof JSFunction) {
337 // FEATURE: use something similar to call0/call1/call2 here
338 JSArray arguments = new JSArray();
339 for(int j=numArgs - 1; j >= 0; j--) arguments.setElementAt(cx.stack.pop(), j);
340 cx.stack.push(new CallMarker(cx));
341 cx.stack.push(arguments);
342 cx.f = (JSFunction)o;
343 cx.scope = new JSScope(cx.f.parentJSScope);
348 JSCallable c = ((JSCallable)o);
350 case 0: ret = c.call0(method); break;
351 case 1: ret = c.call1(method, cx.stack.pop()); break;
352 case 2: ret = c.call2(method, cx.stack.pop(), cx.stack.pop()); break;
354 JSArray arguments = new JSArray();
355 for(int j=numArgs - 1; j >= 0; j--) arguments.setElementAt(cx.stack.pop(), j);
356 ret = c.call(method, arguments);
357 if (cx.pausecount > initialPauseCount) return; // we were paused
362 if (method != null) cx.pc += 2; // skip the GET and CALL if this was a GETCALL
368 Object o = cx.stack.pop();
369 if(o instanceof JS.Exn) throw (JS.Exn)o;
373 case ASSIGN_SUB: case ASSIGN_ADD: {
374 Object val = cx.stack.pop();
375 Object old = cx.stack.pop();
376 Object key = cx.stack.pop();
377 Object obj = cx.stack.peek();
378 if (val instanceof JSFunction && obj instanceof JSScope) {
379 JSScope parent = (JSScope)obj;
380 while(parent.getParentJSScope() != null) parent = parent.getParentJSScope();
381 if (parent instanceof JSTrap.JSTrappable) {
382 JSTrap.JSTrappable b = (JSTrap.JSTrappable)parent;
383 if (op == ASSIGN_ADD) JSTrap.addTrap(b, key, (JSFunction)val);
384 else JSTrap.delTrap(b, key, (JSFunction)val);
385 // skip over the "normal" implementation of +=/-=
386 cx.pc += ((Integer)arg).intValue() - 1;
390 // use the "normal" implementation
398 int count = ((Number)arg).intValue();
399 if(count < 2) throw new Error("this should never happen");
402 Object right = cx.stack.pop();
403 Object left = cx.stack.pop();
404 if(left instanceof String || right instanceof String)
405 cx.stack.push(JS.toString(left).concat(JS.toString(right)));
406 else cx.stack.push(new Double(JS.toDouble(left) + JS.toDouble(right)));
408 Object[] args = new Object[count];
409 while(--count >= 0) args[count] = cx.stack.pop();
410 if(args[0] instanceof String) {
411 StringBuffer sb = new StringBuffer(64);
412 for(int i=0;i<args.length;i++) sb.append(JS.toString(args[i]));
413 cx.stack.push(sb.toString());
416 for(int i=0;i<args.length;i++) if(args[i] instanceof String) numStrings++;
417 if(numStrings == 0) {
419 for(int i=0;i<args.length;i++) d += JS.toDouble(args[i]);
420 cx.stack.push(new Double(d));
423 StringBuffer sb = new StringBuffer(64);
424 if(!(args[0] instanceof String || args[1] instanceof String)) {
427 d += JS.toDouble(args[i++]);
428 } while(!(args[i] instanceof String));
429 sb.append(JS.toString(new Double(d)));
431 while(i < args.length) sb.append(JS.toString(args[i++]));
432 cx.stack.push(sb.toString());
440 Object right = cx.stack.pop();
441 Object left = cx.stack.pop();
444 case BITOR: cx.stack.push(new Long(JS.toLong(left) | JS.toLong(right))); break;
445 case BITXOR: cx.stack.push(new Long(JS.toLong(left) ^ JS.toLong(right))); break;
446 case BITAND: cx.stack.push(new Long(JS.toLong(left) & JS.toLong(right))); break;
448 case SUB: cx.stack.push(new Double(JS.toDouble(left) - JS.toDouble(right))); break;
449 case MUL: cx.stack.push(new Double(JS.toDouble(left) * JS.toDouble(right))); break;
450 case DIV: cx.stack.push(new Double(JS.toDouble(left) / JS.toDouble(right))); break;
451 case MOD: cx.stack.push(new Double(JS.toDouble(left) % JS.toDouble(right))); break;
453 case LSH: cx.stack.push(new Long(JS.toLong(left) << JS.toLong(right))); break;
454 case RSH: cx.stack.push(new Long(JS.toLong(left) >> JS.toLong(right))); break;
455 case URSH: cx.stack.push(new Long(JS.toLong(left) >>> JS.toLong(right))); break;
457 case LT: case LE: case GT: case GE: {
458 if (left == null) left = new Integer(0);
459 if (right == null) right = new Integer(0);
461 if (left instanceof String || right instanceof String) {
462 result = left.toString().compareTo(right.toString());
464 result = (int)java.lang.Math.ceil(JS.toDouble(left) - JS.toDouble(right));
466 cx.stack.push(new Boolean((op == LT && result < 0) || (op == LE && result <= 0) ||
467 (op == GT && result > 0) || (op == GE && result >= 0)));
476 if (l == null) { Object tmp = r; r = l; l = tmp; }
477 if (l == null && r == null) ret = true;
478 else if (r == null) ret = false; // l != null, so its false
479 else if (l instanceof Boolean) ret = new Boolean(JS.toBoolean(r)).equals(l);
480 else if (l instanceof Number) ret = JS.toNumber(r).doubleValue() == JS.toNumber(l).doubleValue();
481 else if (l instanceof String) ret = r != null && l.equals(r.toString());
482 else ret = l.equals(r);
483 cx.stack.push(new Boolean(op == EQ ? ret : !ret)); break;
486 default: throw new Error("unknown opcode " + op);
491 while(cx.stack.size() > 0) {
492 Object o = cx.stack.pop();
493 if (o instanceof CatchMarker || o instanceof TryMarker) {
494 boolean inCatch = o instanceof CatchMarker;
497 if(((TryMarker)o).finallyLoc < 0) continue; // no finally block, keep going
499 if(!inCatch && ((TryMarker)o).catchLoc >= 0) {
500 // run the catch block, this will implicitly run the finally block, if it exists
502 cx.stack.push(catchMarker);
503 cx.stack.push(e.getObject());
504 cx.scope = ((TryMarker)o).scope;
505 cx.pc = ((TryMarker)o).catchLoc - 1;
509 cx.stack.push(new FinallyData(THROW));
510 cx.scope = ((TryMarker)o).scope;
511 cx.pc = ((TryMarker)o).finallyLoc - 1;
515 // no handler found within this func
516 if(o instanceof CallMarker) throw e;
524 // Debugging //////////////////////////////////////////////////////////////////////
526 public String toString() { return "JSFunction [" + sourceName + ":" + firstLine + "]"; }
527 public String dump() {
528 StringBuffer sb = new StringBuffer(1024);
529 sb.append("\n" + sourceName + ": " + firstLine + "\n");
530 for (int i=0; i < size; i++) {
534 sb.append(bytecodeToString[-op[i]]);
536 sb.append(codeToString[op[i]]);
538 sb.append(arg[i] == null ? "(no arg)" : arg[i]);
539 if((op[i] == JF || op[i] == JT || op[i] == JMP) && arg[i] != null && arg[i] instanceof Number) {
540 sb.append(" jump to ").append(i+((Number) arg[i]).intValue());
541 } else if(op[i] == TRY) {
542 int[] jmps = (int[]) arg[i];
543 sb.append(" catch: ").append(jmps[0] < 0 ? "No catch block" : ""+(i+jmps[0]));
544 sb.append(" finally: ").append(jmps[1] < 0 ? "No finally block" : ""+(i+jmps[1]));
548 return sb.toString();
552 // Exception Stuff ////////////////////////////////////////////////////////////////
554 static class EvaluatorException extends RuntimeException { public EvaluatorException(String s) { super(s); } }
555 static EvaluatorException ee(String s) {
556 throw new EvaluatorException(JSContext.getSourceName() + ":" + JSContext.getLine() + " " + s);
558 static JS.Exn je(String s) {
559 throw new JS.Exn(JSContext.getSourceName() + ":" + JSContext.getLine() + " " + s);
563 // Markers //////////////////////////////////////////////////////////////////////
565 public static class CallMarker {
569 public CallMarker(JSContext cx) { pc = cx.pc + 1; scope = cx.scope; f = cx.f; }
572 public static class CatchMarker { public CatchMarker() { } }
573 private static CatchMarker catchMarker = new CatchMarker();
575 public static class LoopMarker {
578 public JSScope scope;
579 public LoopMarker(int location, String label, JSScope scope) {
580 this.location = location;
585 public static class TryMarker {
587 public int finallyLoc;
588 public JSScope scope;
589 public TryMarker(int catchLoc, int finallyLoc, JSScope scope) {
590 this.catchLoc = catchLoc;
591 this.finallyLoc = finallyLoc;
595 public static class FinallyData {
598 public FinallyData(int op, Object arg) { this.op = op; this.arg = arg; }
599 public FinallyData(int op) { this(op,null); }