1 // Copyright 2003 Adam Megacz, see the COPYING file for licensing [GPL]
7 /** a JavaScript function, compiled into bytecode */
8 class CompiledFunctionImpl extends JS.Obj implements ByteCodes, Tokens {
10 // Fields and Accessors ///////////////////////////////////////////////
12 /** the number of formal arguments */
13 int numFormalArgs = 0;
15 /** the source code file that this block was drawn from */
17 public String getSourceName() throws JS.Exn { return sourceName; }
19 /** the line numbers */
20 int[] line = new int[10];
22 /** the first line of this script */
23 private int firstLine = -1;
25 /** the instructions */
26 int[] op = new int[10];
28 /** the arguments to the instructions */
29 Object[] arg = new Object[10];
31 /** the number of instruction/argument pairs */
33 int size() { return size; }
35 /** the scope in which this function was declared; by default this function is called in a fresh subscope of the parentScope */
38 // Constructors ////////////////////////////////////////////////////////
40 private CompiledFunctionImpl cloneWithNewParentScope(JS.Scope s) throws IOException {
41 CompiledFunctionImpl ret = new JS.CompiledFunction(sourceName, firstLine, null, s);
42 // Reuse the same op, arg, line, and size variables for the new "instance" of the function
43 // NOTE: Neither *this* function nor the new function should be modified after this call
51 protected CompiledFunctionImpl(String sourceName, int firstLine, Reader sourceCode, JS.Scope parentScope) throws IOException {
52 this.sourceName = sourceName;
53 this.firstLine = firstLine;
54 this.parentScope = parentScope;
55 if (sourceCode == null) return;
56 Parser p = new Parser(sourceCode, sourceName, firstLine);
59 p.parseStatement(this, null);
60 if (s == size()) break;
62 add(-1, LITERAL, null);
68 // Adding and Altering Bytecodes ///////////////////////////////////////////////////
70 int get(int pos) { return op[pos]; }
71 Object getArg(int pos) { return arg[pos]; }
72 void set(int pos, int op_, Object arg_) { op[pos] = op_; arg[pos] = arg_; }
73 void set(int pos, Object arg_) { arg[pos] = arg_; }
74 int pop() { size--; arg[size] = null; return op[size]; }
75 void paste(CompiledFunctionImpl other) { for(int i=0; i<other.size; i++) add(other.line[i], other.op[i], other.arg[i]); }
76 CompiledFunctionImpl add(int line, int op_) { return add(line, op_, null); }
77 CompiledFunctionImpl add(int line, int op_, Object arg_) {
78 if (size == op.length - 1) {
79 int[] line2 = new int[op.length * 2]; System.arraycopy(this.line, 0, line2, 0, op.length); this.line = line2;
80 Object[] arg2 = new Object[op.length * 2]; System.arraycopy(arg, 0, arg2, 0, arg.length); arg = arg2;
81 int[] op2 = new int[op.length * 2]; System.arraycopy(op, 0, op2, 0, op.length); op = op2;
83 this.line[size] = line;
90 public static int getLine(JS.Thread cx) {
91 if(cx.pc < 0 || cx.pc >= ((CompiledFunctionImpl)cx.currentCompiledFunction).size) return -1;
92 return ((CompiledFunctionImpl)cx.currentCompiledFunction).line[cx.pc];
96 // Invoking the Bytecode ///////////////////////////////////////////////////////
98 /** returns false if the thread has been paused */
99 static void eval(final JS.Thread cx) throws JS.Exn {
100 OUTER: for(; cx.currentCompiledFunction == null || cx.pc<((CompiledFunctionImpl)cx.currentCompiledFunction).size; cx.pc++) {
102 if (cx.paused || cx.currentCompiledFunction == null) return;
103 if (cx.tailCallFunction != null) {
104 cx.stack.pop(); // discard actual return value
106 cx.stack.push(new CallMarker(cx));
107 cx.stack.push(cx.tailCallArgs);
108 cx.currentCompiledFunction = cx.tailCallFunction;
109 cx.tailCallFunction = null;
110 cx.tailCallArgs = null;
111 cx.scope = new FunctionScope("unknown", cx.currentCompiledFunction.parentScope);
115 int curOP = cx.currentCompiledFunction.op[cx.pc];
116 Object curArg = cx.currentCompiledFunction.arg[cx.pc];
117 if(curOP == FINALLY_DONE) {
118 FinallyData fd = (FinallyData) cx.stack.pop();
119 if(fd == null) continue OUTER; // NOP
124 case LITERAL: cx.stack.push(curArg); break;
125 case OBJECT: cx.stack.push(new JS.Obj()); break;
126 case ARRAY: cx.stack.push(new JS.Array(JS.toNumber(curArg).intValue())); break;
127 case DECLARE: cx.scope.declare((String)(curArg==null ? cx.stack.peek() : curArg)); if(curArg != null) cx.stack.push(curArg); break;
128 case TOPSCOPE: cx.stack.push(cx.scope); break;
129 case JT: if (JS.toBoolean(cx.stack.pop())) cx.pc += JS.toNumber(curArg).intValue() - 1; break;
130 case JF: if (!JS.toBoolean(cx.stack.pop())) cx.pc += JS.toNumber(curArg).intValue() - 1; break;
131 case JMP: cx.pc += JS.toNumber(curArg).intValue() - 1; break;
132 case POP: cx.stack.pop(); break;
133 case SWAP: { Object o1 = cx.stack.pop(); Object o2 = cx.stack.pop(); cx.stack.push(o1); cx.stack.push(o2); break; }
134 case DUP: cx.stack.push(cx.stack.peek()); break;
135 case NEWSCOPE: cx.scope = new JS.Scope(cx.scope); break;
136 case OLDSCOPE: cx.scope = cx.scope.getParentScope(); break;
137 case ASSERT: if (!JS.toBoolean(cx.stack.pop())) throw je("assertion failed"); break;
138 case BITNOT: cx.stack.push(new Long(~JS.toLong(cx.stack.pop()))); break;
139 case BANG: cx.stack.push(new Boolean(!JS.toBoolean(cx.stack.pop()))); break;
142 Object o = cx.stack.pop();
143 if (o == null) cx.stack.push(null);
144 else if (o instanceof JS) cx.stack.push(((JS)o).typeName());
145 else if (o instanceof String) cx.stack.push("string");
146 else if (o instanceof Number) cx.stack.push("number");
147 else if (o instanceof Boolean) cx.stack.push("boolean");
148 else cx.stack.push("unknown");
154 cx.stack.push(((CompiledFunctionImpl)curArg).cloneWithNewParentScope(cx.scope));
155 } catch (IOException e) {
156 throw new Error("this should never happen");
162 Object o = cx.stack.peek();
163 Object[] keys = ((JS)o).keys();
164 JS.Array a = new JS.Array();
165 a.setSize(keys.length);
166 for(int j=0; j<keys.length; j++) a.setElementAt(keys[j], j);
173 cx.stack.push(new LoopMarker(cx.pc, cx.pc > 0 && cx.currentCompiledFunction.op[cx.pc - 1] == LABEL ? (String)cx.currentCompiledFunction.arg[cx.pc - 1] : (String)null, cx.scope));
174 cx.stack.push(Boolean.TRUE);
180 while(cx.stack.size() > 0) {
181 Object o = cx.stack.pop();
182 if (o instanceof CallMarker) ee("break or continue not within a loop");
183 if (o instanceof TryMarker) {
184 if(((TryMarker)o).finallyLoc < 0) continue; // no finally block, keep going
185 cx.stack.push(new FinallyData(curOP, curArg));
186 cx.scope = ((TryMarker)o).scope;
187 cx.pc = ((TryMarker)o).finallyLoc - 1;
190 if (o instanceof LoopMarker) {
191 if (curArg == null || curArg.equals(((LoopMarker)o).label)) {
192 int loopInstructionLocation = ((LoopMarker)o).location;
193 int endOfLoop = ((Integer)cx.currentCompiledFunction.arg[loopInstructionLocation]).intValue() + loopInstructionLocation;
194 cx.scope = ((LoopMarker)o).scope;
195 if (curOP == CONTINUE) { cx.stack.push(o); cx.stack.push(Boolean.FALSE); }
196 cx.pc = curOP == BREAK ? endOfLoop - 1 : loopInstructionLocation;
201 throw new Error("CONTINUE/BREAK invoked but couldn't find a LoopMarker at " + ((CompiledFunctionImpl)cx.currentCompiledFunction).sourceName + ":" + getLine(cx));
204 int[] jmps = (int[]) curArg;
205 // jmps[0] is how far away the catch block is, jmps[1] is how far away the finally block is
206 // each can be < 0 if the specified block does not exist
207 cx.stack.push(new TryMarker(jmps[0] < 0 ? -1 : cx.pc + jmps[0], jmps[1] < 0 ? -1 : cx.pc + jmps[1], cx.scope));
212 Object retval = cx.stack.pop();
213 while(cx.stack.size() > 0) {
214 Object o = cx.stack.pop();
215 if (o instanceof TryMarker) {
216 if(((TryMarker)o).finallyLoc < 0) continue;
217 cx.stack.push(retval);
218 cx.stack.push(new FinallyData(RETURN));
219 cx.scope = ((TryMarker)o).scope;
220 cx.pc = ((TryMarker)o).finallyLoc - 1;
223 if (o instanceof CallMarker) {
224 cx.scope = ((CallMarker)o).scope;
225 cx.pc = ((CallMarker)o).pc;
226 cx.currentCompiledFunction = (CompiledFunction)((CallMarker)o).currentCompiledFunction;
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");
244 ((JS)target).put(key, val);
253 v = curArg == null ? cx.stack.pop() : curArg;
261 if (o == null) throw je("tried to get property \"" + v + "\" from the null value");
262 if (v == null) throw je("tried to get the null key from " + o);
263 if (o instanceof String || o instanceof Number || o instanceof Boolean)
264 ret = Internal.getFromPrimitive(o,v);
265 else if (o instanceof JS) {
266 ret = ((JS)o).get(v);
268 throw je("tried to get property " + v + " from a " + o.getClass().getName());
276 JS.Array arguments = new JS.Array();
277 int numArgs = JS.toNumber(curArg).intValue();
278 arguments.setSize(numArgs);
279 for(int j=numArgs - 1; j >= 0; j--) arguments.setElementAt(cx.stack.pop(), j);
280 Object o = cx.stack.pop();
281 if(o == null) throw je("attempted to call null");
283 if(curOP == CALLMETHOD) {
286 if(o instanceof String || o instanceof Number || o instanceof Boolean) {
287 ret = Internal.callMethodOnPrimitive(o,method,arguments);
290 } else if (o instanceof JS) {
291 if (((JS)o).callMethod(method, arguments, true) == Boolean.TRUE) {
292 ret = ((JS)o).callMethod(method,arguments,false);
296 o = ((JS)o).get(method);
299 throw new JS.Exn("Tried to call a method on an object that isn't a JS object: " + o);
303 if (o instanceof CompiledFunctionImpl) {
304 cx.stack.push(new CallMarker(cx));
305 cx.stack.push(arguments);
306 cx.currentCompiledFunction = (CompiledFunction)o;
307 cx.scope = new FunctionScope("unknown", cx.currentCompiledFunction.parentScope);
312 ret = ((JS.Callable)o).call(arguments);
317 // fall through if exception was thrown
319 Object o = cx.stack.pop();
320 if(o instanceof JS.Exn) throw (JS.Exn)o;
324 case INC: case DEC: {
325 boolean isPrefix = JS.toBoolean(curArg);
326 Object key = cx.stack.pop();
327 JS obj = (JS)cx.stack.pop();
328 Number num = JS.toNumber(obj.get(key));
329 Number val = new Double(curOP == INC ? num.doubleValue() + 1.0 : num.doubleValue() - 1.0);
331 cx.stack.push(isPrefix ? val : num);
335 case ASSIGN_SUB: case ASSIGN_ADD: {
336 Object val = cx.stack.pop();
337 Object old = cx.stack.pop();
338 Object key = cx.stack.pop();
339 Object obj = cx.stack.peek();
340 if (val instanceof CompiledFunction) {
341 if (obj instanceof JS.Scope) {
342 JS.Scope parent = (JS.Scope)obj;
343 while(parent.getParentScope() != null) parent = parent.getParentScope();
344 if (parent instanceof org.xwt.Box) {
345 if (curOP == ASSIGN_ADD) {
346 ((org.xwt.Box)parent).addTrap(key, val);
348 ((org.xwt.Box)parent).delTrap(key, val);
350 // skip over the "normal" implementation of +=/-=
351 cx.pc += ((Integer)curArg).intValue() - 1;
356 // use the "normal" implementation
364 int count = ((Number)curArg).intValue();
365 if(count < 2) throw new Error("this should never happen");
368 Object right = cx.stack.pop();
369 Object left = cx.stack.pop();
370 if(left instanceof String || right instanceof String) cx.stack.push(JS.toString(left).concat(JS.toString(right)));
371 else cx.stack.push(new Double(JS.toDouble(left) + JS.toDouble(right)));
373 Object[] args = new Object[count];
374 while(--count >= 0) args[count] = cx.stack.pop();
375 if(args[0] instanceof String) {
376 StringBuffer sb = new StringBuffer(64);
377 for(int i=0;i<args.length;i++) sb.append(JS.toString(args[i]));
378 cx.stack.push(sb.toString());
381 for(int i=0;i<args.length;i++) if(args[i] instanceof String) numStrings++;
382 if(numStrings == 0) {
384 for(int i=0;i<args.length;i++) d += JS.toDouble(args[i]);
385 cx.stack.push(new Double(d));
388 StringBuffer sb = new StringBuffer(64);
389 if(!(args[0] instanceof String || args[1] instanceof String)) {
392 d += JS.toDouble(args[i++]);
393 } while(!(args[i] instanceof String));
394 sb.append(JS.toString(new Double(d)));
396 while(i < args.length) sb.append(JS.toString(args[i++]));
397 cx.stack.push(sb.toString());
405 Object right = cx.stack.pop();
406 Object left = cx.stack.pop();
409 case BITOR: cx.stack.push(new Long(JS.toLong(left) | JS.toLong(right))); break;
410 case BITXOR: cx.stack.push(new Long(JS.toLong(left) ^ JS.toLong(right))); break;
411 case BITAND: cx.stack.push(new Long(JS.toLong(left) & JS.toLong(right))); break;
413 case SUB: cx.stack.push(new Double(JS.toDouble(left) - JS.toDouble(right))); break;
414 case MUL: cx.stack.push(new Double(JS.toDouble(left) * JS.toDouble(right))); break;
415 case DIV: cx.stack.push(new Double(JS.toDouble(left) / JS.toDouble(right))); break;
416 case MOD: cx.stack.push(new Double(JS.toDouble(left) % JS.toDouble(right))); break;
418 case LSH: cx.stack.push(new Long(JS.toLong(left) << JS.toLong(right))); break;
419 case RSH: cx.stack.push(new Long(JS.toLong(left) >> JS.toLong(right))); break;
420 case URSH: cx.stack.push(new Long(JS.toLong(left) >>> JS.toLong(right))); break;
422 case LT: case LE: case GT: case GE: {
423 if (left == null) left = new Integer(0);
424 if (right == null) right = new Integer(0);
426 if (left instanceof String || right instanceof String) {
427 result = left.toString().compareTo(right.toString());
429 result = (int)java.lang.Math.ceil(JS.toDouble(left) - JS.toDouble(right));
431 cx.stack.push(new Boolean((curOP == LT && result < 0) || (curOP == LE && result <= 0) ||
432 (curOP == GT && result > 0) || (curOP == GE && result >= 0)));
441 if (l == null) { Object tmp = r; r = l; l = tmp; }
442 if (l == null && r == null) ret = true;
443 else if (r == null) ret = false; // l != null, so its false
444 else if (l instanceof Boolean) ret = new Boolean(JS.toBoolean(r)).equals(l);
445 else if (l instanceof Number) ret = JS.toNumber(r).doubleValue() == JS.toNumber(l).doubleValue();
446 else if (l instanceof String) ret = r != null && l.equals(r.toString());
447 else ret = l.equals(r);
448 cx.stack.push(new Boolean(curOP == EQ ? ret : !ret)); break;
451 default: throw new Error("unknown opcode " + curOP);
455 while(cx.stack.size() > 0) {
456 Object o = cx.stack.pop();
457 if (o instanceof CatchMarker || o instanceof TryMarker) {
458 boolean inCatch = o instanceof CatchMarker;
461 if(((TryMarker)o).finallyLoc < 0) continue; // no finally block, keep going
463 if(!inCatch && ((TryMarker)o).catchLoc >= 0) {
464 // run the catch block, this will implicitly run the finally block, if it exists
466 cx.stack.push(catchMarker);
467 cx.stack.push(e.getObject());
468 cx.scope = ((TryMarker)o).scope;
469 cx.pc = ((TryMarker)o).catchLoc - 1;
473 cx.stack.push(new FinallyData(THROW));
474 cx.scope = ((TryMarker)o).scope;
475 cx.pc = ((TryMarker)o).finallyLoc - 1;
479 // no handler found within this func
480 if(o instanceof CallMarker) throw e;
485 // this should never happen, we will ALWAYS have a RETURN at the end of the func
486 throw new Error("Just fell out of CompiledFunction::eval() loop.");
489 // Debugging //////////////////////////////////////////////////////////////////////
491 public String toString() {
492 StringBuffer sb = new StringBuffer(1024);
493 sb.append("\n" + sourceName + ": " + firstLine + "\n");
494 for (int i=0; i < size; i++) {
498 sb.append(bytecodeToString[-op[i]]);
500 sb.append(codeToString[op[i]]);
502 sb.append(arg[i] == null ? "(no arg)" : arg[i]);
503 if((op[i] == JF || op[i] == JT || op[i] == JMP) && arg[i] != null && arg[i] instanceof Number) {
504 sb.append(" jump to ").append(i+((Number) arg[i]).intValue());
505 } else if(op[i] == TRY) {
506 int[] jmps = (int[]) arg[i];
507 sb.append(" catch: ").append(jmps[0] < 0 ? "No catch block" : ""+(i+jmps[0]));
508 sb.append(" finally: ").append(jmps[1] < 0 ? "No finally block" : ""+(i+jmps[1]));
512 return sb.toString();
515 // Exception Stuff ////////////////////////////////////////////////////////////////
517 static class EvaluatorException extends RuntimeException { public EvaluatorException(String s) { super(s); } }
518 static EvaluatorException ee(String s) { throw new EvaluatorException(((CompiledFunctionImpl)(JS.Thread.current()).currentCompiledFunction).sourceName + ":" + JS.Thread.current().getLine() + " " + s); }
519 static JS.Exn je(String s) { throw new JS.Exn(((CompiledFunctionImpl)(JS.Thread.current()).currentCompiledFunction).sourceName + ":" + JS.Thread.current().getLine() + " " + s); }
522 // FunctionScope /////////////////////////////////////////////////////////////////
524 static class FunctionScope extends JS.Scope {
526 public FunctionScope(String sourceName, Scope parentScope) { super(parentScope); this.sourceName = sourceName; }
527 public String getSourceName() { return sourceName; }
531 // Markers //////////////////////////////////////////////////////////////////////
533 public static class CallMarker {
536 CompiledFunctionImpl currentCompiledFunction;
537 public CallMarker(JS.Thread cx) { pc = cx.pc + 1; scope = cx.scope; currentCompiledFunction = cx.currentCompiledFunction; }
540 public static class CatchMarker { public CatchMarker() { } }
541 private static CatchMarker catchMarker = new CatchMarker();
543 public static class LoopMarker {
546 public JS.Scope scope;
547 public LoopMarker(int location, String label, JS.Scope scope) {
548 this.location = location;
553 public static class TryMarker {
555 public int finallyLoc;
556 public JS.Scope scope;
557 public TryMarker(int catchLoc, int finallyLoc, JS.Scope scope) {
558 this.catchLoc = catchLoc;
559 this.finallyLoc = finallyLoc;
563 public static class FinallyData {
566 public FinallyData(int op, Object arg) { this.op = op; this.arg = arg; }
567 public FinallyData(int op) { this(op,null); }
571 /** this class exists solely to work around a GCJ bug */
572 abstract class JSCallable extends JS.Callable {
573 public abstract Object call(JS.Array args) throws JS.Exn;