1 // Copyright 2003 Adam Megacz, see the COPYING file for licensing [GPL]
7 /** a JavaScript function, compiled into bytecode */
8 public class Function extends JS.Obj implements ByteCodes, Tokens {
10 public int getNumFormalArgs() { return numFormalArgs; }
13 // Fields and Accessors ///////////////////////////////////////////////
15 int numFormalArgs = 0; ///< the number of formal arguments
16 String sourceName; ///< the source code file that this block was drawn from
17 int[] line = new int[10]; ///< the line numbers
18 private int firstLine = -1; ///< the first line of this script
19 int[] op = new int[10]; ///< the instructions
20 Object[] arg = new Object[10]; ///< the arguments to the instructions
21 int size = 0; ///< the number of instruction/argument pairs
22 JS.Scope parentScope; ///< the default scope to use as a parent scope when executing this
25 // Constructors ////////////////////////////////////////////////////////
27 private Function cloneWithNewParentScope(JS.Scope s) {
28 Function ret = new Function(sourceName, firstLine, s);
29 // Reuse the same op, arg, line, and size variables for the new "instance" of the function
30 // NOTE: Neither *this* function nor the new function should be modified after this call
35 ret.numFormalArgs = this.numFormalArgs;
39 private Function(String sourceName, int firstLine, JS.Scope parentScope) {
40 this.sourceName = sourceName;
41 this.firstLine = firstLine;
42 this.parentScope = parentScope;
45 protected Function(String sourceName, int firstLine, Reader sourceCode, JS.Scope parentScope) throws IOException {
46 this(sourceName, firstLine, parentScope);
47 if (sourceCode == null) return;
48 Parser p = new Parser(sourceCode, sourceName, firstLine);
51 p.parseStatement(this, null);
54 add(-1, LITERAL, null);
60 // Adding and Altering Bytecodes ///////////////////////////////////////////////////
62 int get(int pos) { return op[pos]; }
63 Object getArg(int pos) { return arg[pos]; }
64 void set(int pos, int op_, Object arg_) { op[pos] = op_; arg[pos] = arg_; }
65 void set(int pos, Object arg_) { arg[pos] = arg_; }
66 int pop() { size--; arg[size] = null; return op[size]; }
67 void paste(Function other) { for(int i=0; i<other.size; i++) add(other.line[i], other.op[i], other.arg[i]); }
68 Function add(int line, int op_) { return add(line, op_, null); }
69 Function add(int line, int op_, Object arg_) {
70 if (size == op.length - 1) {
71 int[] line2 = new int[op.length * 2]; System.arraycopy(this.line, 0, line2, 0, op.length); this.line = line2;
72 Object[] arg2 = new Object[op.length * 2]; System.arraycopy(arg, 0, arg2, 0, arg.length); arg = arg2;
73 int[] op2 = new int[op.length * 2]; System.arraycopy(op, 0, op2, 0, op.length); op = op2;
75 this.line[size] = line;
83 // Invoking the Bytecode ///////////////////////////////////////////////////////
85 /** returns false if the thread has been paused */
86 static Object eval(final Context cx) throws JS.Exn {
87 OUTER: for(;; cx.pc++) {
89 if (cx.f == null || cx.pc >= cx.f.size) return cx.stack.pop();
90 int op = cx.f.op[cx.pc];
91 Object arg = cx.f.arg[cx.pc];
92 Object returnedFromJava = null;
93 boolean checkReturnedFromJava = false;
94 if(op == FINALLY_DONE) {
95 FinallyData fd = (FinallyData) cx.stack.pop();
96 if(fd == null) continue OUTER; // NOP
101 case LITERAL: cx.stack.push(arg); break;
102 case OBJECT: cx.stack.push(new JS.Obj()); break;
103 case ARRAY: cx.stack.push(new JS.Array(JS.toNumber(arg).intValue())); break;
104 case DECLARE: cx.scope.declare((String)(arg==null ? cx.stack.peek() : arg)); if(arg != null) cx.stack.push(arg); break;
105 case TOPSCOPE: cx.stack.push(cx.scope); break;
106 case JT: if (JS.toBoolean(cx.stack.pop())) cx.pc += JS.toNumber(arg).intValue() - 1; break;
107 case JF: if (!JS.toBoolean(cx.stack.pop())) cx.pc += JS.toNumber(arg).intValue() - 1; break;
108 case JMP: cx.pc += JS.toNumber(arg).intValue() - 1; break;
109 case POP: cx.stack.pop(); break;
110 case SWAP: { Object o1 = cx.stack.pop(); Object o2 = cx.stack.pop(); cx.stack.push(o1); cx.stack.push(o2); break; }
111 case DUP: cx.stack.push(cx.stack.peek()); break;
112 case NEWSCOPE: cx.scope = new JS.Scope(cx.scope); break;
113 case OLDSCOPE: cx.scope = cx.scope.getParentScope(); break;
114 case ASSERT: if (!JS.toBoolean(cx.stack.pop())) throw je("assertion failed"); break;
115 case BITNOT: cx.stack.push(new Long(~JS.toLong(cx.stack.pop()))); break;
116 case BANG: cx.stack.push(new Boolean(!JS.toBoolean(cx.stack.pop()))); break;
117 case NEWFUNCTION: cx.stack.push(((Function)arg).cloneWithNewParentScope(cx.scope)); break;
121 Object o = cx.stack.pop();
122 if (o == null) cx.stack.push(null);
123 else if (o instanceof JS) cx.stack.push(((JS)o).typeName());
124 else if (o instanceof String) cx.stack.push("string");
125 else if (o instanceof Number) cx.stack.push("number");
126 else if (o instanceof Boolean) cx.stack.push("boolean");
127 else cx.stack.push("unknown");
132 Object o = cx.stack.peek();
133 Object[] keys = ((JS)o).keys();
134 JS.Array a = new JS.Array();
135 a.setSize(keys.length);
136 for(int j=0; j<keys.length; j++) a.setElementAt(keys[j], j);
142 cx.stack.push(new LoopMarker(cx.pc, cx.pc > 0 && cx.f.op[cx.pc - 1] == LABEL ?
143 (String)cx.f.arg[cx.pc - 1] : (String)null, cx.scope));
144 cx.stack.push(Boolean.TRUE);
149 while(cx.stack.size() > 0) {
150 Object o = cx.stack.pop();
151 if (o instanceof CallMarker) ee("break or continue not within a loop");
152 if (o instanceof TryMarker) {
153 if(((TryMarker)o).finallyLoc < 0) continue; // no finally block, keep going
154 cx.stack.push(new FinallyData(op, arg));
155 cx.scope = ((TryMarker)o).scope;
156 cx.pc = ((TryMarker)o).finallyLoc - 1;
159 if (o instanceof LoopMarker) {
160 if (arg == null || arg.equals(((LoopMarker)o).label)) {
161 int loopInstructionLocation = ((LoopMarker)o).location;
162 int endOfLoop = ((Integer)cx.f.arg[loopInstructionLocation]).intValue() + loopInstructionLocation;
163 cx.scope = ((LoopMarker)o).scope;
164 if (op == CONTINUE) { cx.stack.push(o); cx.stack.push(Boolean.FALSE); }
165 cx.pc = op == BREAK ? endOfLoop - 1 : loopInstructionLocation;
170 throw new Error("CONTINUE/BREAK invoked but couldn't find LoopMarker at " +
171 cx.getSourceName() + ":" + cx.getLine());
174 int[] jmps = (int[]) arg;
175 // jmps[0] is how far away the catch block is, jmps[1] is how far away the finally block is
176 // each can be < 0 if the specified block does not exist
177 cx.stack.push(new TryMarker(jmps[0] < 0 ? -1 : cx.pc + jmps[0], jmps[1] < 0 ? -1 : cx.pc + jmps[1], cx.scope));
182 Object retval = cx.stack.pop();
183 while(cx.stack.size() > 0) {
184 Object o = cx.stack.pop();
185 if (o instanceof TryMarker) {
186 if(((TryMarker)o).finallyLoc < 0) continue;
187 cx.stack.push(retval);
188 cx.stack.push(new FinallyData(RETURN));
189 cx.scope = ((TryMarker)o).scope;
190 cx.pc = ((TryMarker)o).finallyLoc - 1;
192 } else if (o instanceof CallMarker) {
193 cx.scope = ((CallMarker)o).scope;
194 cx.pc = ((CallMarker)o).pc;
195 cx.f = (Function)((CallMarker)o).f;
196 cx.stack.push(retval);
200 throw new Error("error: RETURN invoked but couldn't find a CallMarker!");
204 Object val = cx.stack.pop();
205 Object key = cx.stack.pop();
206 Object target = cx.stack.peek();
208 throw je("tried to put a value to the " + key + " property on the null value");
209 if (!(target instanceof JS))
210 throw je("tried to put a value to the " + key + " property on a " + target.getClass().getName());
212 throw je("tried to assign \"" + (val==null?"(null)":val.toString()) + "\" to the null key");
213 returnedFromJava = ((JS)target).put(key, val);
214 if (returnedFromJava != null) checkReturnedFromJava = true;
215 else cx.stack.push(val);
223 v = arg == null ? cx.stack.pop() : arg;
231 if (o == null) throw je("tried to get property \"" + v + "\" from the null value");
232 if (v == null) throw je("tried to get the null key from " + o);
233 if (o instanceof String || o instanceof Number || o instanceof Boolean) {
234 ret = Internal.getFromPrimitive(o,v);
237 } else if (o instanceof JS) {
238 returnedFromJava = ((JS)o).get(v);
239 checkReturnedFromJava = true;
242 throw je("tried to get property " + v + " from a " + o.getClass().getName());
245 case CALL: case CALLMETHOD: case CALL_REVERSED: {
246 JS.Array arguments = new JS.Array();
247 int numArgs = JS.toNumber(arg).intValue();
248 arguments.setSize(numArgs);
250 if (op == CALL_REVERSED) o = cx.stack.pop();
251 for(int j=numArgs - 1; j >= 0; j--) arguments.setElementAt(cx.stack.pop(), j);
252 if (op != CALL_REVERSED) o = cx.stack.pop();
253 if(o == null) throw je("attempted to call null");
256 if(op == CALLMETHOD) {
259 if(o instanceof String || o instanceof Number || o instanceof Boolean) {
260 ret = Internal.callMethodOnPrimitive(o,method,arguments);
262 cx.pc += 2; // skip the GET and CALL
263 } else if (o instanceof JS && ((JS)o).callMethod(method, arguments, true) == Boolean.TRUE) {
264 returnedFromJava = ((JS)o).callMethod(method, arguments, false);
265 checkReturnedFromJava = true;
266 cx.pc += 2; // skip the GET and CALL
268 // put the args back on the stack and let the GET followed by CALL happen
269 for(int j=0; j<numArgs; j++) cx.stack.push(arguments.elementAt(j));
271 cx.stack.push(method);
274 } else if (o instanceof Function) {
275 cx.stack.push(new CallMarker(cx));
276 cx.stack.push(arguments);
278 cx.scope = new Scope(cx.f.parentScope);
282 returnedFromJava = ((JS.Callable)o).call(arguments);
283 checkReturnedFromJava = true;
289 Object o = cx.stack.pop();
290 if(o instanceof JS.Exn) throw (JS.Exn)o;
294 case INC: case DEC: {
295 boolean isPrefix = JS.toBoolean(arg);
296 Object key = cx.stack.pop();
297 JS obj = (JS)cx.stack.pop();
298 Number num = JS.toNumber(obj.get(key));
299 Number val = new Double(op == INC ? num.doubleValue() + 1.0 : num.doubleValue() - 1.0);
301 cx.stack.push(isPrefix ? val : num);
305 case ASSIGN_SUB: case ASSIGN_ADD: {
306 Object val = cx.stack.pop();
307 Object old = cx.stack.pop();
308 Object key = cx.stack.pop();
309 Object obj = cx.stack.peek();
310 if (val instanceof Function && obj instanceof JS.Scope) {
311 JS.Scope parent = (JS.Scope)obj;
312 while(parent.getParentScope() != null) parent = parent.getParentScope();
313 if (parent instanceof org.xwt.Box) {
314 org.xwt.Box b = (org.xwt.Box)parent;
315 if (op == ASSIGN_ADD) b.addTrap(key, val); else b.delTrap(key, val);
316 // skip over the "normal" implementation of +=/-=
317 cx.pc += ((Integer)arg).intValue() - 1;
321 // use the "normal" implementation
329 int count = ((Number)arg).intValue();
330 if(count < 2) throw new Error("this should never happen");
333 Object right = cx.stack.pop();
334 Object left = cx.stack.pop();
335 if(left instanceof String || right instanceof String)
336 cx.stack.push(JS.toString(left).concat(JS.toString(right)));
337 else cx.stack.push(new Double(JS.toDouble(left) + JS.toDouble(right)));
339 Object[] args = new Object[count];
340 while(--count >= 0) args[count] = cx.stack.pop();
341 if(args[0] instanceof String) {
342 StringBuffer sb = new StringBuffer(64);
343 for(int i=0;i<args.length;i++) sb.append(JS.toString(args[i]));
344 cx.stack.push(sb.toString());
347 for(int i=0;i<args.length;i++) if(args[i] instanceof String) numStrings++;
348 if(numStrings == 0) {
350 for(int i=0;i<args.length;i++) d += JS.toDouble(args[i]);
351 cx.stack.push(new Double(d));
354 StringBuffer sb = new StringBuffer(64);
355 if(!(args[0] instanceof String || args[1] instanceof String)) {
358 d += JS.toDouble(args[i++]);
359 } while(!(args[i] instanceof String));
360 sb.append(JS.toString(new Double(d)));
362 while(i < args.length) sb.append(JS.toString(args[i++]));
363 cx.stack.push(sb.toString());
371 Object right = cx.stack.pop();
372 Object left = cx.stack.pop();
375 case BITOR: cx.stack.push(new Long(JS.toLong(left) | JS.toLong(right))); break;
376 case BITXOR: cx.stack.push(new Long(JS.toLong(left) ^ JS.toLong(right))); break;
377 case BITAND: cx.stack.push(new Long(JS.toLong(left) & JS.toLong(right))); break;
379 case SUB: cx.stack.push(new Double(JS.toDouble(left) - JS.toDouble(right))); break;
380 case MUL: cx.stack.push(new Double(JS.toDouble(left) * JS.toDouble(right))); break;
381 case DIV: cx.stack.push(new Double(JS.toDouble(left) / JS.toDouble(right))); break;
382 case MOD: cx.stack.push(new Double(JS.toDouble(left) % JS.toDouble(right))); break;
384 case LSH: cx.stack.push(new Long(JS.toLong(left) << JS.toLong(right))); break;
385 case RSH: cx.stack.push(new Long(JS.toLong(left) >> JS.toLong(right))); break;
386 case URSH: cx.stack.push(new Long(JS.toLong(left) >>> JS.toLong(right))); break;
388 case LT: case LE: case GT: case GE: {
389 if (left == null) left = new Integer(0);
390 if (right == null) right = new Integer(0);
392 if (left instanceof String || right instanceof String) {
393 result = left.toString().compareTo(right.toString());
395 result = (int)java.lang.Math.ceil(JS.toDouble(left) - JS.toDouble(right));
397 cx.stack.push(new Boolean((op == LT && result < 0) || (op == LE && result <= 0) ||
398 (op == GT && result > 0) || (op == GE && result >= 0)));
407 if (l == null) { Object tmp = r; r = l; l = tmp; }
408 if (l == null && r == null) ret = true;
409 else if (r == null) ret = false; // l != null, so its false
410 else if (l instanceof Boolean) ret = new Boolean(JS.toBoolean(r)).equals(l);
411 else if (l instanceof Number) ret = JS.toNumber(r).doubleValue() == JS.toNumber(l).doubleValue();
412 else if (l instanceof String) ret = r != null && l.equals(r.toString());
413 else ret = l.equals(r);
414 cx.stack.push(new Boolean(op == EQ ? ret : !ret)); break;
417 default: throw new Error("unknown opcode " + op);
421 // handle special directions returned from Java callouts
422 // ideally we would do this with exceptions, but they're *very* slow in gcj
423 if (checkReturnedFromJava) {
424 checkReturnedFromJava = false;
425 if (returnedFromJava == Context.pause) {
427 return Context.pause;
428 } else if (returnedFromJava instanceof TailCall) {
429 cx.stack.push(new CallMarker(cx));
430 cx.stack.push(((JS.TailCall)returnedFromJava).args);
431 cx.f = ((JS.TailCall)returnedFromJava).func;
432 cx.scope = new Scope(cx.f.parentScope);
435 cx.stack.push(returnedFromJava);
442 while(cx.stack.size() > 0) {
443 Object o = cx.stack.pop();
444 if (o instanceof CatchMarker || o instanceof TryMarker) {
445 boolean inCatch = o instanceof CatchMarker;
448 if(((TryMarker)o).finallyLoc < 0) continue; // no finally block, keep going
450 if(!inCatch && ((TryMarker)o).catchLoc >= 0) {
451 // run the catch block, this will implicitly run the finally block, if it exists
453 cx.stack.push(catchMarker);
454 cx.stack.push(e.getObject());
455 cx.scope = ((TryMarker)o).scope;
456 cx.pc = ((TryMarker)o).catchLoc - 1;
460 cx.stack.push(new FinallyData(THROW));
461 cx.scope = ((TryMarker)o).scope;
462 cx.pc = ((TryMarker)o).finallyLoc - 1;
466 // no handler found within this func
467 if(o instanceof CallMarker) throw e;
475 // Debugging //////////////////////////////////////////////////////////////////////
477 public String toString() { return "Function [" + sourceName + ":" + firstLine + "]"; }
478 public String dump() {
479 StringBuffer sb = new StringBuffer(1024);
480 sb.append("\n" + sourceName + ": " + firstLine + "\n");
481 for (int i=0; i < size; i++) {
485 sb.append(bytecodeToString[-op[i]]);
487 sb.append(codeToString[op[i]]);
489 sb.append(arg[i] == null ? "(no arg)" : arg[i]);
490 if((op[i] == JF || op[i] == JT || op[i] == JMP) && arg[i] != null && arg[i] instanceof Number) {
491 sb.append(" jump to ").append(i+((Number) arg[i]).intValue());
492 } else if(op[i] == TRY) {
493 int[] jmps = (int[]) arg[i];
494 sb.append(" catch: ").append(jmps[0] < 0 ? "No catch block" : ""+(i+jmps[0]));
495 sb.append(" finally: ").append(jmps[1] < 0 ? "No finally block" : ""+(i+jmps[1]));
499 return sb.toString();
503 // Exception Stuff ////////////////////////////////////////////////////////////////
505 static class EvaluatorException extends RuntimeException { public EvaluatorException(String s) { super(s); } }
506 static EvaluatorException ee(String s) {
507 throw new EvaluatorException(Context.getSourceName() + ":" + Context.getLine() + " " + s);
509 static JS.Exn je(String s) {
510 throw new JS.Exn(Context.getSourceName() + ":" + Context.getLine() + " " + s);
514 // Markers //////////////////////////////////////////////////////////////////////
516 public static class CallMarker {
520 public CallMarker(Context cx) { pc = cx.pc + 1; scope = cx.scope; f = cx.f; }
523 public static class CatchMarker { public CatchMarker() { } }
524 private static CatchMarker catchMarker = new CatchMarker();
526 public static class LoopMarker {
529 public JS.Scope scope;
530 public LoopMarker(int location, String label, JS.Scope scope) {
531 this.location = location;
536 public static class TryMarker {
538 public int finallyLoc;
539 public JS.Scope scope;
540 public TryMarker(int catchLoc, int finallyLoc, JS.Scope scope) {
541 this.catchLoc = catchLoc;
542 this.finallyLoc = finallyLoc;
546 public static class FinallyData {
549 public FinallyData(int op, Object arg) { this.op = op; this.arg = arg; }
550 public FinallyData(int op) { this(op,null); }