1 // Copyright 2003 Adam Megacz, see the COPYING file for licensing [GPL]
7 // FIXME: could use some cleaning up
8 /** a JavaScript function, compiled into bytecode */
9 class CompiledFunctionImpl extends JSCallable implements ByteCodes, Tokens {
11 // Fields and Accessors ///////////////////////////////////////////////
13 /** the source code file that this block was drawn from */
14 private String sourceName;
15 public String getSourceName() throws JS.Exn { return sourceName; }
17 /** the line numbers */
18 private int[] line = new int[10];
20 /** the first line of this script */
21 private int firstLine = -1;
23 /** the instructions */
24 private int[] op = new int[10];
26 /** the arguments to the instructions */
27 private Object[] arg = new Object[10];
29 /** the number of instruction/argument pairs */
31 int size() { return size; }
33 /** the scope in which this function was declared; by default this function is called in a fresh subscope of the parentScope */
34 private JS.Scope parentScope;
36 // Constructors ////////////////////////////////////////////////////////
38 private CompiledFunctionImpl cloneWithNewParentScope(JS.Scope s) throws IOException {
39 CompiledFunctionImpl ret = new JS.CompiledFunction(sourceName, firstLine, null, s);
40 // Reuse the same op, arg, line, and size variables for the new "instance" of the function
41 // NOTE: Neither *this* function nor the new function should be modified after this call
49 protected CompiledFunctionImpl(String sourceName, int firstLine, Reader sourceCode, JS.Scope parentScope) throws IOException {
50 this.sourceName = sourceName;
51 this.firstLine = firstLine;
52 this.parentScope = parentScope;
53 if (sourceCode == null) return;
54 Parser p = new Parser(sourceCode, sourceName, firstLine);
57 p.parseStatement(this, null);
58 if (s == size()) break;
60 add(-1, LITERAL, null);
64 public Object call(JS.Array args) throws JS.Exn { return call(args, new FunctionScope(sourceName, parentScope)); }
65 public Object call(JS.Array args, JS.Scope scope) throws JS.Exn {
66 JS.Thread cx = JS.Thread.fromJavaThread(java.lang.Thread.currentThread());
67 CompiledFunction saved = cx.currentCompiledFunction;
69 cx.currentCompiledFunction = (CompiledFunction)this;
70 int size = cx.stack.size();
71 cx.stack.push(callMarker);
74 Object ret = cx.stack.pop();
75 // FIXME: if we catch an exception in Java, JS won't notice and the stack will be messed up
76 if (cx.stack.size() > size)
77 // this should never happen
78 throw new Error("ERROR: stack grew by " + (cx.stack.size() - size) + " elements during call");
81 cx.currentCompiledFunction = saved;
86 // Adding and Altering Bytecodes ///////////////////////////////////////////////////
88 int get(int pos) { return op[pos]; }
89 Object getArg(int pos) { return arg[pos]; }
90 void set(int pos, int op_, Object arg_) { op[pos] = op_; arg[pos] = arg_; }
91 void set(int pos, Object arg_) { arg[pos] = arg_; }
92 int pop() { size--; arg[size] = null; return op[size]; }
93 void paste(CompiledFunctionImpl other) { for(int i=0; i<other.size; i++) add(other.line[i], other.op[i], other.arg[i]); }
94 CompiledFunctionImpl add(int line, int op_) { return add(line, op_, null); }
95 CompiledFunctionImpl add(int line, int op_, Object arg_) {
96 if (size == op.length - 1) {
97 int[] line2 = new int[op.length * 2]; System.arraycopy(this.line, 0, line2, 0, op.length); this.line = line2;
98 Object[] arg2 = new Object[op.length * 2]; System.arraycopy(arg, 0, arg2, 0, arg.length); arg = arg2;
99 int[] op2 = new int[op.length * 2]; System.arraycopy(op, 0, op2, 0, op.length); op = op2;
101 this.line[size] = line;
108 public int getLine(int pc) {
109 if(pc < 0 || pc >= size) return -1;
114 // Invoking the Bytecode ///////////////////////////////////////////////////////
116 void eval(JS.Scope s) {
117 final JS.Thread cx = JS.Thread.fromJavaThread(java.lang.Thread.currentThread());
118 final Vec t = cx.stack;
121 OUTER: for(pc=0; pc<size; pc++) {
125 Object curArg = arg[pc];
126 if(curOP == FINALLY_DONE) {
127 FinallyData fd = (FinallyData) t.pop();
128 if(fd == null) continue OUTER; // NOP
133 case LITERAL: t.push(arg[pc]); break;
134 case OBJECT: t.push(new JS.Obj()); break;
135 case ARRAY: t.push(new JS.Array(JS.toNumber(arg[pc]).intValue())); break;
136 case DECLARE: s.declare((String)(arg[pc]==null ? t.peek() : arg[pc])); if(arg[pc] != null) t.push(arg[pc]); break;
137 case TOPSCOPE: t.push(s); break;
138 case JT: if (JS.toBoolean(t.pop())) pc += JS.toNumber(arg[pc]).intValue() - 1; break;
139 case JF: if (!JS.toBoolean(t.pop())) pc += JS.toNumber(arg[pc]).intValue() - 1; break;
140 case JMP: pc += JS.toNumber(arg[pc]).intValue() - 1; break;
141 case POP: t.pop(); break;
142 case SWAP: { Object o1 = t.pop(); Object o2 = t.pop(); t.push(o1); t.push(o2); break; }
143 case DUP: t.push(t.peek()); break;
144 case NEWSCOPE: s = new JS.Scope(s); break;
145 case OLDSCOPE: s = s.getParentScope(); break;
146 case ASSERT: if (!JS.toBoolean(t.pop())) throw je("assertion failed"); break;
147 case BITNOT: t.push(new Long(~JS.toLong(t.pop()))); break;
148 case BANG: t.push(new Boolean(!JS.toBoolean(t.pop()))); break;
152 if (o == null) t.push(null);
153 else if (o instanceof JS) t.push(((JS)o).typeName());
154 else if (o instanceof String) t.push("string");
155 else if (o instanceof Number) t.push("number");
156 else if (o instanceof Boolean) t.push("boolean");
157 else t.push("unknown");
163 t.push(((CompiledFunctionImpl)arg[pc]).cloneWithNewParentScope(s));
164 } catch (IOException e) {
165 throw new Error("this should never happen");
172 Object[] keys = ((JS)o).keys();
173 JS.Array a = new JS.Array();
174 a.setSize(keys.length);
175 for(int j=0; j<keys.length; j++) a.setElementAt(keys[j], j);
182 t.push(new LoopMarker(pc, pc > 0 && op[pc - 1] == LABEL ? (String)arg[pc - 1] : (String)null,s));
183 t.push(Boolean.TRUE);
189 while(t.size() > 0) {
191 if (o instanceof CallMarker) ee("break or continue not within a loop");
192 if (o instanceof TryMarker) {
193 if(((TryMarker)o).finallyLoc < 0) continue; // no finally block, keep going
194 t.push(new FinallyData(curOP, curArg));
195 s = ((TryMarker)o).scope;
196 pc = ((TryMarker)o).finallyLoc - 1;
199 if (o instanceof LoopMarker) {
200 if (curArg == null || curArg.equals(((LoopMarker)o).label)) {
201 int loopInstructionLocation = ((LoopMarker)o).location;
202 int endOfLoop = ((Integer)arg[loopInstructionLocation]).intValue() + loopInstructionLocation;
203 s = ((LoopMarker)o).scope;
204 if (curOP == CONTINUE) { t.push(o); t.push(Boolean.FALSE); }
205 pc = curOP == BREAK ? endOfLoop - 1 : loopInstructionLocation;
210 throw new Error("CONTINUE/BREAK invoked but couldn't find a LoopMarker at " + sourceName + ":" + getLine(pc));
213 int[] jmps = (int[]) arg[pc];
214 // jmps[0] is how far away the catch block is, jmps[1] is how far away the finally block is
215 // each can be < 0 if the specified block does not exist
216 t.push(new TryMarker(jmps[0] < 0 ? -1 : pc + jmps[0], jmps[1] < 0 ? -1 : pc + jmps[1],s));
221 Object retval = t.pop();
222 while(t.size() > 0) {
224 if (o instanceof TryMarker) {
225 if(((TryMarker)o).finallyLoc < 0) continue;
227 t.push(new FinallyData(RETURN));
228 s = ((TryMarker)o).scope;
229 pc = ((TryMarker)o).finallyLoc - 1;
232 if (o instanceof CallMarker) {
237 throw new Error("error: RETURN invoked but couldn't find a CallMarker!");
241 Object val = t.pop();
242 Object key = t.pop();
243 Object target = t.peek();
245 throw je("tried to put a value to the " + key + " property on the null value");
246 if (!(target instanceof JS))
247 throw je("tried to put a value to the " + key + " property on a " + target.getClass().getName());
249 throw je("tried to assign \"" + (val==null?"(null)":val.toString()) + "\" to the null key");
250 ((JS)target).put(key, val);
259 v = arg[pc] == null ? t.pop() : arg[pc];
267 if (o == null) throw je("tried to get property \"" + v + "\" from the null value");
268 if (v == null) throw je("tried to get the null key from " + o);
269 if (o instanceof String || o instanceof Number || o instanceof Boolean)
270 ret = Internal.getFromPrimitive(o,v);
271 else if (o instanceof JS)
272 ret = ((JS)o).get(v);
274 throw je("tried to get property " + v + " from a " + o.getClass().getName());
282 JS.Array arguments = new JS.Array();
283 int numArgs = JS.toNumber(arg[pc]).intValue();
284 arguments.setSize(numArgs);
285 for(int j=numArgs - 1; j >= 0; j--) arguments.setElementAt(t.pop(), j);
287 if(o == null) throw je("attempted to call null");
290 if(op[pc] == CALLMETHOD) {
293 if(o instanceof String || o instanceof Number || o instanceof Boolean)
294 ret = Internal.callMethodOnPrimitive(o,method,arguments);
295 else if(o instanceof JS)
296 ret = ((JS)o).callMethod(method,arguments,false);
298 throw new JS.Exn("Tried to call a method on an object that isn't a JS object");
300 ret = ((JS.Callable)o).call(arguments);
308 // fall through if exception was thrown
310 Object exn = t.pop();
311 while(t.size() > 0) {
313 if (o instanceof CatchMarker || o instanceof TryMarker) {
314 boolean inCatch = o instanceof CatchMarker;
317 if(((TryMarker)o).finallyLoc < 0) continue; // no finally block, keep going
319 if(!inCatch && ((TryMarker)o).catchLoc >= 0) {
320 // run the catch block, this will implicitly run the finally block, if it exists
323 t.push((exn instanceof JS.Exn) ? ((JS.Exn)exn).getObject() : exn);
324 s = ((TryMarker)o).scope;
325 pc = ((TryMarker)o).catchLoc - 1;
329 t.push(new FinallyData(THROW));
330 s = ((TryMarker)o).scope;
331 pc = ((TryMarker)o).finallyLoc - 1;
335 // no handler found within this func
336 if(o instanceof CallMarker) {
337 if(exn instanceof JS.Exn)
340 throw new JS.Exn(exn);
343 throw new Error("error: THROW invoked but couldn't find a Try or Call Marker!");
346 case INC: case DEC: {
347 boolean isPrefix = JS.toBoolean(arg[pc]);
348 Object key = t.pop();
349 JS obj = (JS)t.pop();
350 Number num = JS.toNumber(obj.get(key));
351 Number val = new Double(op[pc] == INC ? num.doubleValue() + 1.0 : num.doubleValue() - 1.0);
353 t.push(isPrefix ? val : num);
358 Object right = t.pop();
359 Object left = t.pop();
365 if (l instanceof String || r instanceof String) {
366 if (l == null) l = "null";
367 if (r == null) r = "null";
368 if (l instanceof Number && ((Number)l).doubleValue() == ((Number)l).longValue())
369 l = new Long(((Number)l).longValue());
370 if (r instanceof Number && ((Number)r).doubleValue() == ((Number)r).longValue())
371 r = new Long(((Number)r).longValue());
372 t.push(l.toString() + r.toString()); break;
374 t.push(new Double(JS.toDouble(l) + JS.toDouble(r))); break;
377 case BITOR: t.push(new Long(JS.toLong(left) | JS.toLong(right))); break;
378 case BITXOR: t.push(new Long(JS.toLong(left) ^ JS.toLong(right))); break;
379 case BITAND: t.push(new Long(JS.toLong(left) & JS.toLong(right))); break;
381 case SUB: t.push(new Double(JS.toDouble(left) - JS.toDouble(right))); break;
382 case MUL: t.push(new Double(JS.toDouble(left) * JS.toDouble(right))); break;
383 case DIV: t.push(new Double(JS.toDouble(left) / JS.toDouble(right))); break;
384 case MOD: t.push(new Double(JS.toDouble(left) % JS.toDouble(right))); break;
386 case LSH: t.push(new Long(JS.toLong(left) << JS.toLong(right))); break;
387 case RSH: t.push(new Long(JS.toLong(left) >> JS.toLong(right))); break;
388 case URSH: t.push(new Long(JS.toLong(left) >>> JS.toLong(right))); break;
390 case LT: case LE: case GT: case GE: {
391 if (left == null) left = new Integer(0);
392 if (right == null) right = new Integer(0);
394 if (left instanceof String || right instanceof String) {
395 result = left.toString().compareTo(right.toString());
397 result = (int)java.lang.Math.ceil(JS.toDouble(left) - JS.toDouble(right));
399 t.push(new Boolean((op[pc] == LT && result < 0) || (op[pc] == LE && result <= 0) ||
400 (op[pc] == GT && result > 0) || (op[pc] == GE && result >= 0)));
409 if (l == null) { Object tmp = r; r = l; l = tmp; }
410 if (l == null && r == null) ret = true;
411 else if (r == null) ret = false; // l != null, so its false
412 else if (l instanceof Boolean) ret = new Boolean(JS.toBoolean(r)).equals(l);
413 else if (l instanceof Number) ret = JS.toNumber(r).doubleValue() == JS.toNumber(l).doubleValue();
414 else if (l instanceof String) ret = r != null && l.equals(r.toString());
415 else ret = l.equals(r);
416 t.push(new Boolean(op[pc] == EQ ? ret : !ret)); break;
419 default: throw new Error("unknown opcode " + op[pc]);
423 // this should never happen, we will ALWAYS have a RETURN at the end of the func
424 throw new Error("Just fell out of CompiledFunction::eval() loop. Last PC was " + lastPC);
427 // Debugging //////////////////////////////////////////////////////////////////////
429 public String toString() {
430 StringBuffer sb = new StringBuffer(1024);
431 sb.append("\n" + sourceName + ": " + firstLine + "\n");
432 for (int i=0; i < size; i++) {
436 sb.append(bytecodeToString[-op[i]]);
438 sb.append(codeToString[op[i]]);
440 sb.append(arg[i] == null ? "(no arg)" : arg[i]);
441 if((op[i] == JF || op[i] == JT || op[i] == JMP) && arg[i] != null && arg[i] instanceof Number) {
442 sb.append(" jump to ").append(i+((Number) arg[i]).intValue());
443 } else if(op[i] == TRY) {
444 int[] jmps = (int[]) arg[i];
445 sb.append(" catch: ").append(jmps[0] < 0 ? "No catch block" : ""+(i+jmps[0]));
446 sb.append(" finally: ").append(jmps[1] < 0 ? "No finally block" : ""+(i+jmps[1]));
450 return sb.toString();
453 // Exception Stuff ////////////////////////////////////////////////////////////////
455 static class EvaluatorException extends RuntimeException { public EvaluatorException(String s) { super(s); } }
456 EvaluatorException ee(String s) { throw new EvaluatorException(sourceName + ":" + JS.Thread.currentJSThread().getLine() + " " + s); }
457 JS.Exn je(String s) { throw new JS.Exn(sourceName + ":" + JS.Thread.currentJSThread().getLine() + " " + s); }
460 // FunctionScope /////////////////////////////////////////////////////////////////
462 private static class FunctionScope extends JS.Scope {
464 public FunctionScope(String sourceName, Scope parentScope) { super(parentScope); this.sourceName = sourceName; }
465 public String getSourceName() { return sourceName; }
469 // Markers //////////////////////////////////////////////////////////////////////
471 public static class CallMarker { public CallMarker() { } }
472 private static CallMarker callMarker = new CallMarker();
474 public static class CatchMarker { public CatchMarker() { } }
475 private static CatchMarker catchMarker = new CatchMarker();
477 public static class LoopMarker {
480 public JS.Scope scope;
481 public LoopMarker(int location, String label, JS.Scope scope) {
482 this.location = location;
487 public static class TryMarker {
489 public int finallyLoc;
490 public JS.Scope scope;
491 public TryMarker(int catchLoc, int finallyLoc, JS.Scope scope) {
492 this.catchLoc = catchLoc;
493 this.finallyLoc = finallyLoc;
497 public static class FinallyData {
500 public FinallyData(int op, Object arg) { this.op = op; this.arg = arg; }
501 public FinallyData(int op) { this(op,null); }
505 /** this class exists solely to work around a GCJ bug */
506 abstract class JSCallable extends JS.Callable {
507 public abstract Object call(JS.Array args) throws JS.Exn;